答:
There are several implementations of these, the most popular ones being the GNU coreutils (found in most Linux distributions) and the BSD implementation (found in FreeBSD, OS X, and other mostly non-linux Unix-likes).

Unless you are on a distro that installs everything from source (like Gentoo), you will have to ask your package manager to download the sources for you. On Debian-based systems, the appropriate command is apt-get source {package-name}, which downloads the source for the specified package and stores it in the current directory. All that's left is find out which package those commands are in; you can either dig through your package manager's documentation to find out how, or you can search your distro's website - most of them have a package search that allows you to search for individual files within packages.

For Debian-based systems (such as Ubuntu):

```<code>$ dpkg -S /bin/rm
coreutils: /bin/rm
$ dpkg -l coreutils
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                         Version                      Description
+++-============================-============================-========================================================================
ii  coreutils                    8.13-3ubuntu3                GNU core utilities
</code>```

For Red Hat-based systems (such as Fedora and Centos):

```<code>$ rpm -qf /bin/rm
coreutils-5.97-34.el5_8.1
</code>```

Title: Where to find the source code for the Linux command line functions

Body:
I would like to study the source code of the standard command line functions in Linux such as ls, echo, cat, etc. But I have been unable to find the source code (a Google search was useless).

Does someone know where it's available? I know it's a naive question but I really can't find this source code.

Body:
There are several implementations of these, the most popular ones being the GNU coreutils (found in most Linux distributions) and the BSD implementation (found in FreeBSD, OS X, and other mostly non-linux Unix-likes).

Unless you are on a distro that installs everything from source (like Gentoo), you will have to ask your package manager to download the sources for you. On Debian-based systems, the appropriate command is apt-get source {package-name}, which downloads the source for the specified package and stores it in the current directory. All that's left is find out which package those commands are in; you can either dig through your package manager's documentation to find out how, or you can search your distro's website - most of them have a package search that allows you to search for individual files within packages.

For Debian-based systems (such as Ubuntu):

$ dpkg -S /bin/rm
coreutils: /bin/rm
$ dpkg -l coreutils
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                         Version                      Description
+++-============================-============================-========================================================================
ii  coreutils                    8.13-3ubuntu3                GNU core utilities

For Red Hat-based systems (such as Fedora and Centos):

$ rpm -qf /bin/rm
coreutils-5.97-34.el5_8.1


问:
Senior team members want to move query-relevant persistent data from DB to cache. Does this make sense?
I am a young engineer recently employed at a small company that sells products to the general public. We use Ruby On Rails and MySQL. Our database has a lot of customer data, but a great deal more of "static" persistent data. This data is so rarely changed that some of the more senior engineers have begun to talk about moving it to a cache data store. One of the touted benefits of this plan is that it would make deployments easier, since we would no longer have to bootstrap the database; instead, a lot of data would have permanent IDs, and we could just backup the cache and deploy the backup.

My query is related to the operational aspects of running the site once the change is done, not the change itself. We have persistent data that is used for database queries in response to user activities, which is used on a day basis. Putting it in a cache would remove our abilities to run SQL queries, instead querying the cache from RoR code. I don't have enough experience to judge if this is a good plan or not, but it smells funny to me.

Has anyone ever seen a situation similar to this, or have experience in this area? I'm looking for reassurance that this is not a crazy idea.

答:
Databases are meant to store data that is rarely changed. That's the whole point.

Caches are meant to store data that is frequently used, to make access to it faster than the database would provide on its own.

Unless the data to be cached is very frequently used, or your company has a lot of money that it needs to waste, it makes little sense to cache it.

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Michael Hampton


答:
As with many things it depends.

Moving data that changes rarely to a different place may make sense if the data is getting in the way. If it's not getting in the way, why would you do it?

From your description I see that some people think the data gets in the way and you think that moving it out makes your life harder. We can't really weigh these against each other, only you and your other engineers can.

Title: Senior team members want to move query-relevant persistent data from DB to cache. Does this make sense?

Body:
I am a young engineer recently employed at a small company that sells products to the general public. We use Ruby On Rails and MySQL. Our database has a lot of customer data, but a great deal more of "static" persistent data. This data is so rarely changed that some of the more senior engineers have begun to talk about moving it to a cache data store. One of the touted benefits of this plan is that it would make deployments easier, since we would no longer have to bootstrap the database; instead, a lot of data would have permanent IDs, and we could just backup the cache and deploy the backup.

My query is related to the operational aspects of running the site once the change is done, not the change itself. We have persistent data that is used for database queries in response to user activities, which is used on a day basis. Putting it in a cache would remove our abilities to run SQL queries, instead querying the cache from RoR code. I don't have enough experience to judge if this is a good plan or not, but it smells funny to me.

Has anyone ever seen a situation similar to this, or have experience in this area? I'm looking for reassurance that this is not a crazy idea.

OwnerDisplayName: Dennis Kaarsemaker


问:
Which HTTP status codes are really OK?
I am writing an application to report to the user(devs) when their website fails. And what I mean by fails which is unfunctional or needs to report the problem to devs.
 I do understand that status code 2XX means 'Success' according to wiki. But does that really do? I have access my website once and returned 204 'No-Content', which is unfunctional to me. So the question is, what are the list of status codes return should It be considered "website is functional"?

答: The error codes which are meant to indicate that there is something wrong with the web service itself are the 5xx errors. Those and only those. Returning anything else should indicate that the web service is  working correctly. 4xx errors are indication of error in the request, not on the server.

Title: Which HTTP status codes are really OK?


问:
Are side-effects in Array's "every", or "some" bad?
I've always been taught that having side-effects in an if condition are bad. What I mean is;

```<code>if (conditionThenHandle()) {
    // do effectively nothing
}
</code>```

... as opposed to;

```<code>if (condition()) {
    handle();
}
</code>```

... and I understand that, and my collegues are happy because I don't do it, and we all go home at 17:00 on a Friday and everyone has a merry weekend.

Now, ECMAScript5 introduced methods like every() and some() to Array, and I find them very useful. They're cleaner than for (;;;)'s, give you another scope, and make the element accessible by a variable.

However when validating input, I more-often-than-not find myself using every/some in the condition to validate the input, then use every/some again in the body to convert the input into a usable model;

```<code>if (input.every(function (that) {
    return typeof that === "number";
})) {
    input.every(function (that) {
        // Model.findById(that); etc
    }
} else {
    return;
}
</code>```

... when what I want to be doing is;

```<code>if (!input.every(function (that) {
    var res = typeof that === "number";

    if (res) {
        // Model.findById(that); etc.
    }

    return res;
})) {
    return;
}
</code>```

... which gives me side-effects in an if, condition, which is bad.

In comparison, this is the code would look with with an old for (;;;);

```<code>for (var i=0;i<input.length;i++) {
    var curr = input[i];

    if (typeof curr === "number") {
        return;
    }

    // Model.findById(curr); etc.
}
</code>```

My questions are:

Is this definitely a bad practice?

Am I (mis|ab)using some and every (should I be using a for(;;;) for this?)

Is there a better approach?

答: The side effects are not in the if condition, they are in the if's body. You have only determined whether or not to execute that body in the actual condition. There is nothing wrong with your approach here.</p>


问:
Erlang/Haskell web service to server files
I have across a thread mentioning that Erlang would not be suited for a web application serving files.

I was curious whether anyone had any experience building such webservice with erlang? Would Haskell be more suited for this, if so how ?

答:
I don't have much experience with Erlang, but I know that Haskell is very well suited to making a simple web server. Take a look at Warp[PDF], a Haskell web server. It has very good performance, and should be easy to configure for serving static files. There is already a package called warp-static that is set up for serving files already; you can look at the source to get a good idea of what it takes.

I think Haskell will likely have better performance than Erlang for this sort of task, especially with Haskell's new (as of GHC 7.0) IO manager. Then it has the usual other advantages over Erlang like the type system, nice syntax, functional purity and so on.

As an aside, if you want Erlang-like distributed concurrency, take a look at Cloud Haskell. It's a system for writing distributed programs in Haskell that is very heavily influenced by Erlang.


问:
Why does the backing store of an array bind to the smallest type?
In C# it is legal to write

```<code>Animal[] a = new Giraffe[4]; //with obvious relationships
</code>```

Because arrays are covariant.  However, this is a breaking relationship.  It's a runtime exception to then apply a different type of Animal to this array because the backing store is a Giraffe.

```<code>a[0] = new Cat(); //KABOOM
</code>```

Why doesn't the language create a covariant backing store?  This doesn't appear to be a limitation of the language because I can create this type of data structure myself:

```<code>class Program
{
    static void Main(string[] args)
    {
        A[] a = new B[2];
        a[0] = new B();
        a[1] = new C();//runtime exception

        var containerLegal = new Container<B, A>();
        containerLegal.Add(new B());
        containerLegal.Add(new C());//works fine
    }
}

class A { }

class B : A { }

class C : A { }

class Container<T,S> where T: class, S
{
    S[] s = new S[4];
    int currentIndex = 0;

    public void Add(S t)
    {
        s[currentIndex] = t;
        currentIndex++;
    }
}
</code>```

I'm cheating a little bit cause I'm not using T in Container<>...but I think its a fair relationship anyhow.

答:
The problem isn't that you couldn't store a reference to a C in that array (though I'm pretty sure it's nontrivial to implement). The problem is, if you permit that, code like this (note that this can be spread out over several unrelated methods, due to arrays being reference types) becomes wrong:

```<code>B[] bs = new B[1];
A[] as = bs;
as[0] = new C();
B b = bs[0]; /* It's a C, but we use it as a B, and a C is not a B! */
</code>```

How does it go wrong? Well, if it doesn't notice and assumes a wrong object layout, you get all kinds of fun usually reserved for C, C++, and unsafe code:

Re-interpreting an int as a float (or a reference to T as a reference to U, for recursive instances of such fun).

Accessing uninitialized memory (or another object's memory)

Calling a method with the wrong type or number of arguments.

Using padding bytes as if they has any meaning.

Overwriting metadata the GC/memory management system needs to operate.

Alternatively, you could restore safety by making all code reading from arrays do run-time type checks (as opposed to doing that check when writing to the array, as it currently does) and throwing an exception when an item has an unexpected type. That's slow and you'd just get the same exception in a different place (when you access the reference vs. when you store it), so you didn't "fix" anything.
That's because you can't fix it, such code is inherently broken. Your Container would exhibit the same problem if it permitted getting references back from the S[] (e.g., an indexer) unless it always returns the most general type (an S, not a T; otherwise you run into the same problem).

Body:
The problem isn't that you couldn't store a reference to a C in that array (though I'm pretty sure it's nontrivial to implement). The problem is, if you permit that, code like this (note that this can be spread out over several unrelated methods, due to arrays being reference types) becomes wrong:

B[] bs = new B[1];
A[] as = bs;
as[0] = new C();
B b = bs[0]; /* It's a C, but we use it as a B, and a C is not a B! */

How does it go wrong? Well, if it doesn't notice and assumes a wrong object layout, you get all kinds of fun usually reserved for C, C++, and unsafe code:

Re-interpreting an int as a float (or a reference to T as a reference to U, for recursive instances of such fun).

Accessing uninitialized memory (or another object's memory)

Calling a method with the wrong type or number of arguments.

Using padding bytes as if they has any meaning.

Overwriting metadata the GC/memory management system needs to operate.

Alternatively, you could restore safety by making all code reading from arrays do run-time type checks (as opposed to doing that check when writing to the array, as it currently does) and throwing an exception when an item has an unexpected type. That's slow and you'd just get the same exception in a different place (when you access the reference vs. when you store it), so you didn't "fix" anything.
That's because you can't fix it, such code is inherently broken. Your Container would exhibit the same problem if it permitted getting references back from the S[] (e.g., an indexer) unless it always returns the most general type (an S, not a T; otherwise you run into the same problem).


答:
Because that's what you told it to do.  That is the equvalient of:

```<code>Girafe[] g = new Girafe[4];
Animal[] a = g;  // girafe array has been created by this time;
</code>```

Your statement is clear about all types, if you let the left side determine the type of the right, you'd run into some problems.  Consider..

```<code>Girafe[] g = GetGArray():
Animal[] a = GetGArray();
</code>```

Does a equal g? If it doesn't then a NEW backing store would have to be created, if it does, then the compiler would have to be determining what happens based upon whether it was a new or a function call.  But then there is inlining...

Simpiliest to just do exactly what the line says.

Title: Why does the backing store of an array bind to the smallest type?

Body:
In C# it is legal to write

```<code>Animal[] a = new Giraffe[4]; //with obvious relationships
</code>```

Because arrays are covariant.  However, this is a breaking relationship.  It's a runtime exception to then apply a different type of Animal to this array because the backing store is a Giraffe.

```<code>a[0] = new Cat(); //KABOOM
</code>```

Why doesn't the language create a covariant backing store?  This doesn't appear to be a limitation of the language because I can create this type of data structure myself:

```<code>class Program
{
    static void Main(string[] args)
    {
        A[] a = new B[2];
        a[0] = new B();
        a[1] = new C();//runtime exception

        var containerLegal = new Container<B, A>();
        containerLegal.Add(new B());
        containerLegal.Add(new C());//works fine
    }
}

class A { }

class B : A { }

class C : A { }

class Container<T,S> where T: class, S
{
    S[] s = new S[4];
    int currentIndex = 0;

    public void Add(S t)
    {
        s[currentIndex] = t;
        currentIndex++;
    }
}
</code>```

I'm cheating a little bit cause I'm not using T in Container<>...but I think its a fair relationship anyhow.

Body:
Because that's what you told it to do.  That is the equvalient of:

Girafe[] g = new Girafe[4];
Animal[] a = g;  // girafe array has been created by this time;

Your statement is clear about all types, if you let the left side determine the type of the right, you'd run into some problems.  Consider..

Girafe[] g = GetGArray():
Animal[] a = GetGArray();

Does a equal g? If it doesn't then a NEW backing store would have to be created, if it does, then the compiler would have to be determining what happens based upon whether it was a new or a function call.  But then there is inlining...

Simpiliest to just do exactly what the line says.


问:
How do you interview someone with more experience than you?
The company I'm working for is looking to hire a senior developer with more experience than me, and they expect me to do the technical part of the interview. I've only been programming a few years and am not sure I have the knowledge needed to evaluate the coding skills of someone who has greater understanding/experience than I do.

Can anyone recommend some technical interview questions to ask that are a good means for evaluating higher-level programming skills, but still be ones I can understand?

I would say I'm past the jr. programmer level, but nowhere near senior. Most of what I've done is built small apps (web and desktop), some of them fairly complicated, but all of them have been meant to be used by no more then a handful of users. I feel I have a decent understanding of most programming concepts and am capable of learning/teaching myself just about anything, however I lack experience. As my boss is fond of telling me, "You don't know what you don't know".

In particular, things we'd like the person we hire to have experience with (that I don't have) is: Multi-tier development, multi-user environment, large-scale application development, two-way messaging, shared sessions, and Multi-threading/BackgroundWorkers.

UPDATE:

In response to Thor's comment below, we hired someone a few months ago and I think it has been working out great. I am learning a lot, not just about coding but also about things like design patterns, software architecture, documentation, and how other larger programming teams get stuff done. Its not always easy having someone come in and point out better ways to do things you have done, but if you can swallow your pride and be willing to try out new things you can learn a lot.

The interview process went better than I expected. I started asking questions about things I was familiar with, then asked some questions about some things I was struggling with. Whenever the interviewee said something I didn't understand, I'd ask them to explain it to me and then write it down so I could look it up later on. Overall, I felt I was able to get a pretty good idea of the applicant's skill level, intelligence, and what they'd be like to work with.

答:
In terms of the actual interview process, fundamentally you treat them the same as any other person you're hiring. There should be a similar hiring process:

Selection, by CV or agency recommendation.

Aptitude test (combining things like FizzBuzz, strdup()/isAlpha(), OOD, etc)

Telephone interview (for quick elimination if they don't communicate well)

Face-to-face interview

Written coding exercise

Meet some of the team members.

For an experienced person, which implies higher risk and higher costs, additional rounds of interviews are acceptable but you should clearly communicate to them where they are in the process (i.e. this is 1 of 3 interview rounds).

There are many other posts on this site which cover general topics of discussion that you should cover in the interview process - here's my answer to one of them.

At all points in the interview process, an experienced person should demonstrate an excellent understanding of their advertised specialities. You can probe them, in a lot of depth, on any topic that you cover during the discussions. Take questions to the limits of your experience/comfort level and see if they can continue without worry. If you need to go off the deep-end with something you haven't got much experience with, do a web search for some sample questions (get a selection of them), read and understand the answers before the interview, and then ask the candidate any of these questions. Don't expect them to know all the answers, so have a selection of questions.

There are two types of experienced engineer you could hire:

1) Relevant Industry Experience

This is the person that you can take your list of current problems to and talk through how they might approach those problems. You should be gauging their level of understanding of each of the domain-specific topics in your industry. As you're in that industry, you can tell a 'dumb' answer from a 'good' answer and can probably spot an 'experienced' answer too. In contrast to other answers, I wouldn't expect them to actually solve your current problems - that will happen when you hire them - but you need them to convince you that they could once they got started.

2) No relevant Industry Experience

So this candidate is possibly changing industry but has good experience in the foundation technologies/platforms/skills you need. Go deep on those items, but don't expect them to be able to come up with solutions for domain-specific problems, although you could just talk around them. For example, if your company is Facebook, and the person you're interviewing is hot with PHP and C++, it would be unrealistic to expect them to know all the pitfalls of massive server farms (unless they claim it on their CV).

ContentLicense: CC BY-SA 2.5


问:
Demonstrate bad code to client?
A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case.

This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly.

My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long.

How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand?

Update

Thanks for all the responses.
The SQL injection attack demonstration makes sense and I will demo this in a test environment.
That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer)
would need to be replaced with better practices in order for the html and css update to take place.
There are many good suggestions here which I'll piece together when I talk with my client.

答:
It's noob sauce to come in to a project and suggest a rewrite first thing, perform some small subset of the modifications and use those to illustrate how much simpler and cheaper it could have been. Then you have a demonstrable case on why the increased cost of cleaner development will lead to lower maintenance costs and faster development over the long term given a little font side cost.

Never forget that fundamentally you are asking for them to pay you to make your own life easier, in their mind the just need to find 'the guy' who can X features at Y cost and magnifying the complexity of your project may just eliminate the opportunity for you. It's a hard road when you're a month into the rewrite and you have meeting with the original developer only to realize the entire app was written in an extremely contracted window by a developer who fully understood all the compromises that were made. If the app internally looks horrible but externally functions well, as you say, it is very likely this will be the case. Often the technical debt within a codebase is a product of the resource constraints the code was developed in and if they aren't building a team and are instead contracting things out... they are probably still not serious about maintenance.

I'm just sayin'

Title: Demonstrate bad code to client?


问:
Do changes in performance violate the Liskov Substitution Principle?
Say I have:

```<code>interface Thing
{
    GetThing();
}

class FastThing : Thing
{
    public int GetThing()
    {
        return 1;
    }
}

class SlowThing : Thing
{
    public int GetThing()
    {
        return GetThingFromDatabase();
    }
}
</code>```

Is this a violation of the Liskov Substitution Principle?

答:
That really depends. Some interfaces have, for example, complexity constraints (these obviously can't be programmatically enforced). The most basic case is "GetThing() gives an int- i.e., it halts", in which case, the answer would be "No"- both versions of GetThing() halt and return an int.

But many interfaces have implied or expressly stated performance guarantees, either in complexity or in flat time. For example, in the C++ Standard, it's illegal to implement the library with a blocking call except where the Standard expressly permits.


答:
TL;DR: No

According to the "Behavioral Subtyping Using Invariants and Constraints" (the formalization of the principle) it is primarily concerned with "safety" properties of an objects type.  Properties which govern substitutability only within the context of type information.  An objects type is orthogonal to it's performance.  Therefore a difference in performance is not a violation of the Liskov Substitution Principle.

Title: Do changes in performance violate the Liskov Substitution Principle?

Body:
Say I have:

```<code>interface Thing
{
    GetThing();
}

class FastThing : Thing
{
    public int GetThing()
    {
        return 1;
    }
}

class SlowThing : Thing
{
    public int GetThing()
    {
        return GetThingFromDatabase();
    }
}
</code>```

Is this a violation of the Liskov Substitution Principle?


答:
The performance of the software has nothing to do with the Liskov Substitution Principle.

The principle has to do with substitution of subtypes, and the behavioral impact of substituting that object in OOP terms only.

The input and output of getThing() remain the same for both cases, and both slow and fast likely put the objects into the same state.


问:
Possible Designs for code block editor
I have started a project where I need to design an application that will work as a code-block editor, much like lego mindstorms and this google project. http://code.google.com/p/blockly/

What are the possible approaches for designing such an application in Java?

More specifically, assuming I have one block A, how can I define which other blocks can be connected with it? What I think of is using subclasses and checking the hierarchy, or another possible solution could be some kind of 2D table that will verify a connection is valid(although I think it might get too big?).

p.s: I need to force correct structure of code, and not check it with parser at the end. So only blocks that fit together  should be connected.

答:
Like any programming language, it's just a representation of an Abstract Syntax Tree.

Any approach that you can use to represent a tree can be used to represent a program. Interconnecting blocks like you see at Blockly are simply a syntax a human-readable view of an AST. The way the blocks connect make it easier for you to visualise the possible flows for any given item in the tree, and easier to validate on the fly.

I think once you look at it in those terms, the rest is fairly obvious, no? Just code it like you would any tree of classes that can only fit together in particular ways.

Title: Possible Designs for code block editor


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答: Several times I witnessed management bringing in consultants for the sole purpose of spending money. Most of the time this happened at the end of the year when they were under-budget frantically trying to spend the money. Usually these consultants would be paid hundreds of dollars an hour and they would spend weeks on a PowerPoint presentation that would never be used.


答:
What guarantees does the interface make? Since GetThing makes no guarantees then subtypes need not respect it.

If the interface was something like GetThingInLinearTime or if the base type is virtual and the default implementation is one complexity, then making that algorithmic complexity worse would violate LSP.


答:
Does it matter what the Liskov Substitution Principle itself says specifically? If a subtype violates the expectations of the consumer of the supertype, that seems like a bad thing regardless of whether LSP is more restrictive.

So in my view, whether all reasonable expectations of the consumer of an abstraction are fulfilled by the subtype seems to be a good generalization of LSP.

However, in the example you have posted and with Java interfaces in general, it's not clear that the consumer of the Thing interface has any reasonable expectation of whether it should be fast or slow. If the interface's javadocs were to include language about what operations are promised to be fast, then there might be an argument for a problem on performance grounds. But the Java convention is certainly for various implementations to have different performance characteristics.


问:
In MVP, should presenters instantiate and control other presenters?
I've implemented an application using MVP with GWT, which is working out very nicely for views that have a single purpose.  Now, it has evolved into views that are achieving multiple purposes in a single window.  So now I have a view of views with each view having its own presenter.  I used this example as my model for building out the application, take a look.

The "view of views" also has its own presenter, which instantiates (or receives) the presenters for each of the other views it needs to fulfill its purpose.  I reveal event interfaces through those presenters for the "view of views" presenter to hook into and listen and react to what's going on inside those other presenters & views.

My questions are:

Am I still following MVP principles or have I violated the separation of concerns somewhere by having presenters create/receive and control other presenters?  aka Should I be doing this?

What are some other design patterns for creating interfaces that are also composed of other complex interfaces?

Update

In response to Robert Harvey's question, there is difficulty with passing objects from a presenter of a view to the presenter of the "view of views" when an event is triggered.  For instance, a button will flag a ClickEvent and the handler attached to this will need to pick up the data object related to the ClickEvent through another method revealed by the view's presenter.  So this works, but do feel it will cause more problems later on as this kind of object handling grows in complexity.

答:
In order to make it easier for the presenter at the lowest level to interact with the views of other presenters, I just added a method to the interface of the various presenters to return the view they are controlling.  This way I can hook my presenter at the lowest level into the events of those views.

If anyone can point out any problems this will cause down the line, I am all ears.  Thanks!


问:
"To code quickly, you must quit coding"
First off, not my phrase: http://www.whattofix.com/blog/archives/2010/11/to-code-quickly.php Props to Mr. Markham.

BUT, it got me to thinking about a lot of questions I have seen about being able to get things done.

The approach advocated (setting a timer for a set period, in this case 50 minutes, but I've seen people talk about breaking procrastination by setting times as short as five minutes on tasks that you just cannot bring yourself to do, and then taking a short break) seems to be common sense, but lots of people advocate getting into the "zone" and staying there as long as possible, maybe many hours, rather than break their groove.

I keep trying different approaches and find that each has its own strengths and weaknesses.

What kind of technique do you use to be more EFFECTIVE (i.e., getting work done to the quality level demanded by your client / boss / etc. in the time frame allowed) in your software development and not just to spend more time at the keyboard?

答:
I use that technique daily. My timer is 45 minutes of work for 10 minutes of rest.

I also maximize the time on the computer to 4 hours per day. I understand this is not possible when your main task is coding. The rest of the time, I do any task that doesn't require a computer.

The tool I use is a WorkRave. The author wrote it because he started to have physical problems due to its inability to stop coding for long hours.

I'm less stressed and it affected positively my productivity.

Since a few weeks, I also try some mindfulness techniques during the pause times. Delicious.

Now regarding anti-procrastination techniques, I have one that beat everything I tried before:

I manage a single task list, prioritized by importance. I pick the first in the list.

I maintain the list (and calendar) with a combination of GTD and 7 Habits.

To enhance the list effectiveness, write your tasks as next actions instead of descriptions (see the chapter Actions, Contexts & Projects in this Blog Post)

Title: "To code quickly, you must quit coding"


问:
Interview puzzle on traveling on a line segment
On a number line of length M, where 0 < M <= 1,000,000,000, you given N (1 < N <= 100,000) integer pairs of points. In each pair, the first point represents where an object is currently located, and the second point represents where an object should be moved. (Keep in mind the second point may be smaller than the first).

Now, assume you start at the point 0 and have a cart that can hold 1 object. You want to move all objects from their initial positions to their respective final positions while traveling the least distance along the number line (not displacement). You have to end up on point M.

Now, I've been trying to reduce this problem to a simpler problem. To be honest I can't even think of a brute force (possibly greedy) solution. However, my first thought was to degenerate a backwards movement to two forward movements, but that doesn't seem to work in all cases.

I drew out these 3 sample test cases in here:

The answer to the first testcase is 12. First, you pick up the red item at point 0. Then you move to point 6 (distance = 6), drop the red item temporarily, then pick up the green item. Then you move to point 5 (distance = 1) and drop the green item. Then you move back to point 6 (distance = 1) and pick up the red item you dropped, move to point 9 (distance = 3), then move to point 10 (distance = 1) to finish off the sequence.

The total distance traveled was 6 + 1 + 1 + 3 + 1 = 12, which is the minimum possible distance.

The other two cases have answers of 12, I believe. However, I can't find a general rule to solve it.

Anyone got any ideas?

答:
May be I am missunderstanding the problem but what about the following:

Sort the pairs by the first number of the pair which is the current
location

Move along the line swapping elements to their proper location (you
have a temp variable)

The fact that it is sorted guarantees that you don't go back and forth the elements to place them in the proper location (regardless if the line is represented as an array or list)

Update after @templatetypedef comment:

Use a HashTable to store all the pairs. Use the current location of each pair as index key.

Use a second index over the pairs.

```<code> 1. Get next pair according to index from the line.
 2. If current pair exists in hashtable then place element to its target location.
    2.a Remove pair from hashtable.
    2.b Make current pair the target location. Then go to step 1
 ELSE
        Increment current index until you get a pair present in the hashtable. Go to step 2
</code>```

Body:
May be I am missunderstanding the problem but what about the following:

Sort the pairs by the first number of the pair which is the current
location

Move along the line swapping elements to their proper location (you
have a temp variable)

The fact that it is sorted guarantees that you don't go back and forth the elements to place them in the proper location (regardless if the line is represented as an array or list)

Update after @templatetypedef comment:

Use a HashTable to store all the pairs. Use the current location of each pair as index key.

Use a second index over the pairs.

 1. Get next pair according to index from the line.
 2. If current pair exists in hashtable then place element to its target location.
    2.a Remove pair from hashtable.
    2.b Make current pair the target location. Then go to step 1
 ELSE
        Increment current index until you get a pair present in the hashtable. Go to step 2


答:
Suppose you are given these moves (a, b), (c, d), (e, f), ... then the minimum distance you have to travel is abs(b - a) + abs(d - c) + abs(f - e) + ... and the actual distance you travel is abs(b - a) + abs(c - b) + abs(d - c) + abs(e - d) + ....

Basically, given an array of moves the point is to minimize the "travel distance" function by swapping elements around. If you consider a particular combination as a node and all the combinations you can reach from it as edges you can use one of the many graph search algorithms around which make use of an  heuristic. One example is the beam search.

Title: Interview puzzle on traveling on a line segment

Body:
On a number line of length M, where 0 < M <= 1,000,000,000, you given N (1 < N <= 100,000) integer pairs of points. In each pair, the first point represents where an object is currently located, and the second point represents where an object should be moved. (Keep in mind the second point may be smaller than the first).

Now, assume you start at the point 0 and have a cart that can hold 1 object. You want to move all objects from their initial positions to their respective final positions while traveling the least distance along the number line (not displacement). You have to end up on point M.

Now, I've been trying to reduce this problem to a simpler problem. To be honest I can't even think of a brute force (possibly greedy) solution. However, my first thought was to degenerate a backwards movement to two forward movements, but that doesn't seem to work in all cases.

I drew out these 3 sample test cases in here:

The answer to the first testcase is 12. First, you pick up the red item at point 0. Then you move to point 6 (distance = 6), drop the red item temporarily, then pick up the green item. Then you move to point 5 (distance = 1) and drop the green item. Then you move back to point 6 (distance = 1) and pick up the red item you dropped, move to point 9 (distance = 3), then move to point 10 (distance = 1) to finish off the sequence.

The total distance traveled was 6 + 1 + 1 + 3 + 1 = 12, which is the minimum possible distance.

The other two cases have answers of 12, I believe. However, I can't find a general rule to solve it.

Anyone got any ideas?

OwnerDisplayName: BlackBear


答:
This is the asymmetric traveling salesman problem. You can think of this as a graph. The edges will be each (start, finish) pair, one for each (0, start), and all other pairs of (finish, start).

Assuming NP!=P, it will have an exponential expected running time.

OwnerDisplayName: MSN


问:
When would you need "hundreds of thousands" of threads?
Erlang, Go, and Rust all claim in one way or another that they support concurrent programming with cheap "threads"/coroutines.  The Go FAQ states:

It is practical to create hundreds of thousands of goroutines in the same address space.

The Rust Tutorial says:

Because tasks are significantly cheaper to create than traditional threads, Rust can create hundreds of thousands of concurrent tasks on a typical 32-bit system.

Erlang's documentation says:

The default initial heap size of 233 words is quite conservative in order to support Erlang systems with hundreds of thousands or even millions of processes.

My question: what sort of application requires so many concurrent threads of execution?  Only the busiest of web servers receive even thousands of simultaneous visitors.  Boss-worker/job-dispatching type applications I've written hit diminishing returns when the number of threads/processes is much greater than the number of physical cores.  I suppose it might make sense for numerical applications, but in reality most people delegates parallelism to third party libraries written in Fortran/C/C++, not these newer generation languages.

答:
It might help to think of what Erlang was originally designed to do, which was to manage telecommunications. Activities like routing, switching, sensor collection/aggregation, etc.

Bringing this into the web world - consider a system like Twitter. The system probably wouldn't use microthreads in generating web pages, but it could use them in its collection/caching/distribution of tweets.

ContentLicense: CC BY-SA 4.0


答:
If I understand your point correctly, you seem to be mis-using or abusing every and some but it's a little unavoidable if you want to change the elements of your arrays directly.  Correct me if I'm wrong, but what you're trying to do is find out if some or every element in your sequence exhibits a certain condition then modify those elements.  Also, your code seems to be applying something to all items until you find one that doesn't pass the predicate and I don't think that's what you mean to be doing.  Anyways.

Let's take your first example (slightly modified)

```<code>if (input.every(function (that) {
    return typeof that === "number";
})) {
    input.every(function (that) {
        that.foo();
    }
} else {
    return;
}
</code>```

What you're doing here actually goes a little against the spirit of the some/every/map/reduce/filter/etc concepts.  Every isn't meant to be used to affect every item that conforms to something, rather it should only be used to tell you if every item in a collection does.  If you want to apply a function to all items for which a predicate evaluates to true, the "good" way to do it is

```<code>var filtered = array.filter(function(item) {
    return typeof item === "number";
});

var mapped = filtered.map(function(item) {
    return item.foo(); //provided foo() has no side effects and returns a new object of item's type instead.  See note about foreach below.
});
</code>```

Alternatively, you could use foreach instead of map to modify the items in-place.

The same logic applies to some, basically:

You use every to test if all elements in an array pass some test.

You use some to test if at least one element in an array passes some
test.

You use map to return a new array containing 1 element (which
is the result of a function of your choice) for every element in an
input array.

You use filter to return an array of length 0 < length < initial array length elements, all contained in the original array    and all
passing the supplied predicate test.

You use foreach if you want map but in-place

You use reduce if you want to combine the results of an array in a single object result (which could be an array but doesn't have to).

The more you use them (and the more you write LISP code), the more you realize how they are related and how it's even possible to emulate/implement one with the others.  What's powerful with these queries and what's really interesting is their semantics, and how they really push you towards eliminating harmful side-effects in your code.

EDIT (in light of comments):
So let's say you want to validate that every element is an object and convert them to an Application Model if they're all valid.  One way to do this in a single pass would be:

```<code>var dirty = false;
var app_domain_objects = input.map(function(item) {
    if(validate(item)) {
        return new Model(item);
    } else {
        dirty = true; //dirty is captured by the function passed to map, but you know that :)
    }
});
if(dirty) {
    //your validation test failed, do w/e you need to
} else {
    //You can use app_domain_objects
}
</code>```

This way, when an object doesn't pass validation, you still keep iterating through the entire array, which would be slower than just validating with every.  However, most of the time your array will be valid (or I should hope so), so in most cases you'll perform a single pass over your array and end up with a usable array of Application Model objects.  Semantics will be respected, side-effects avoided and everyone will be happy!

Note that you could also write your own query, similar to foreach, which would apply a function to all members of an array  and returns true/false if they all pass a predicate test.  Something like:

```<code>function apply_to_every(arr, predicate, func) {
    var passed = true;
    for(var i = 0; i < array.length; ++i) {
        if(predicate(arr[i])) {
            func(arr[i]);
        } else {
            passed = false;
            break;
        }
    }
    return passed;
}
</code>```

Although that would modify the array in place.

I hope this helps, it was very fun to write.  Cheers!

Title: Are side-effects in Array's "every", or "some" bad?

Body:
I've always been taught that having side-effects in an if condition are bad. What I mean is;

```<code>if (conditionThenHandle()) {
    // do effectively nothing
}
</code>```

... as opposed to;

```<code>if (condition()) {
    handle();
}
</code>```

... and I understand that, and my collegues are happy because I don't do it, and we all go home at 17:00 on a Friday and everyone has a merry weekend.

Now, ECMAScript5 introduced methods like every() and some() to Array, and I find them very useful. They're cleaner than for (;;;)'s, give you another scope, and make the element accessible by a variable.

However when validating input, I more-often-than-not find myself using every/some in the condition to validate the input, then use every/some again in the body to convert the input into a usable model;

```<code>if (input.every(function (that) {
    return typeof that === "number";
})) {
    input.every(function (that) {
        // Model.findById(that); etc
    }
} else {
    return;
}
</code>```

... when what I want to be doing is;

```<code>if (!input.every(function (that) {
    var res = typeof that === "number";

    if (res) {
        // Model.findById(that); etc.
    }

    return res;
})) {
    return;
}
</code>```

... which gives me side-effects in an if, condition, which is bad.

In comparison, this is the code would look with with an old for (;;;);

```<code>for (var i=0;i<input.length;i++) {
    var curr = input[i];

    if (typeof curr === "number") {
        return;
    }

    // Model.findById(curr); etc.
}
</code>```

My questions are:

Is this definitely a bad practice?

Am I (mis|ab)using some and every (should I be using a for(;;;) for this?)

Is there a better approach?

Body:
If I understand your point correctly, you seem to be mis-using or abusing every and some but it's a little unavoidable if you want to change the elements of your arrays directly.  Correct me if I'm wrong, but what you're trying to do is find out if some or every element in your sequence exhibits a certain condition then modify those elements.  Also, your code seems to be applying something to all items until you find one that doesn't pass the predicate and I don't think that's what you mean to be doing.  Anyways.

Let's take your first example (slightly modified)

if (input.every(function (that) {
    return typeof that === "number";
})) {
    input.every(function (that) {
        that.foo();
    }
} else {
    return;
}

What you're doing here actually goes a little against the spirit of the some/every/map/reduce/filter/etc concepts.  Every isn't meant to be used to affect every item that conforms to something, rather it should only be used to tell you if every item in a collection does.  If you want to apply a function to all items for which a predicate evaluates to true, the "good" way to do it is

var filtered = array.filter(function(item) {
    return typeof item === "number";
});

var mapped = filtered.map(function(item) {
    return item.foo(); //provided foo() has no side effects and returns a new object of item's type instead.  See note about foreach below.
});

Alternatively, you could use foreach instead of map to modify the items in-place.

The same logic applies to some, basically:

You use every to test if all elements in an array pass some test.

You use some to test if at least one element in an array passes some
test.

You use map to return a new array containing 1 element (which
is the result of a function of your choice) for every element in an
input array.

You use filter to return an array of length 0 < length < initial array length elements, all contained in the original array    and all
passing the supplied predicate test.

You use foreach if you want map but in-place

You use reduce if you want to combine the results of an array in a single object result (which could be an array but doesn't have to).

The more you use them (and the more you write LISP code), the more you realize how they are related and how it's even possible to emulate/implement one with the others.  What's powerful with these queries and what's really interesting is their semantics, and how they really push you towards eliminating harmful side-effects in your code.

EDIT (in light of comments):
So let's say you want to validate that every element is an object and convert them to an Application Model if they're all valid.  One way to do this in a single pass would be:

var dirty = false;
var app_domain_objects = input.map(function(item) {
    if(validate(item)) {
        return new Model(item);
    } else {
        dirty = true; //dirty is captured by the function passed to map, but you know that :)
    }
});
if(dirty) {
    //your validation test failed, do w/e you need to
} else {
    //You can use app_domain_objects
}

This way, when an object doesn't pass validation, you still keep iterating through the entire array, which would be slower than just validating with every.  However, most of the time your array will be valid (or I should hope so), so in most cases you'll perform a single pass over your array and end up with a usable array of Application Model objects.  Semantics will be respected, side-effects avoided and everyone will be happy!

Note that you could also write your own query, similar to foreach, which would apply a function to all members of an array  and returns true/false if they all pass a predicate test.  Something like:

function apply_to_every(arr, predicate, func) {
    var passed = true;
    for(var i = 0; i < array.length; ++i) {
        if(predicate(arr[i])) {
            func(arr[i]);
        } else {
            passed = false;
            break;
        }
    }
    return passed;
}

Although that would modify the array in place.

I hope this helps, it was very fun to write.  Cheers!


答:
one use case - websockets:

as websockets are long-lived compared to simple requests, on a busy server a lot of websockets will accumulate over time. microthreads give you a good conceptual modelling and also an relatively easy implementation.

more in general, cases in which numerous more or less autonomous units are waiting for certain events to occur should be good use-cases.

Title: When would you need "hundreds of thousands" of threads?

Body:
Erlang, Go, and Rust all claim in one way or another that they support concurrent programming with cheap "threads"/coroutines.  The Go FAQ states:

It is practical to create hundreds of thousands of goroutines in the same address space.

The Rust Tutorial says:

Because tasks are significantly cheaper to create than traditional threads, Rust can create hundreds of thousands of concurrent tasks on a typical 32-bit system.

Erlang's documentation says:

The default initial heap size of 233 words is quite conservative in order to support Erlang systems with hundreds of thousands or even millions of processes.

My question: what sort of application requires so many concurrent threads of execution?  Only the busiest of web servers receive even thousands of simultaneous visitors.  Boss-worker/job-dispatching type applications I've written hit diminishing returns when the number of threads/processes is much greater than the number of physical cores.  I suppose it might make sense for numerical applications, but in reality most people delegates parallelism to third party libraries written in Fortran/C/C++, not these newer generation languages.


答:
My inclination as to an algorithm which is basically greedy:

Build a list of points that need to be moved.  Since optimizing this isn't part of the required problem I'm not going to worry about organizing it.

```<code>while !Done
    if CartIsEmpty()
        FindClosestObjectToMove()
        MoveToObject()
       LoadCart()
    else
        Destination = Cart.Contains.Target
        CurrentMove = [Location, Destination]
        SubList = List.Where(Move.Within(CurrentMove))
        if !SubList.Empty
            Destination = SubList.FindSmallest(Location, Move.Origin)
        MoveTo(Destination)
        if !Destination.Empty
            SwapCart()
            UpdateTaskList()
        else
            EmptyCart()
            DeleteTask()
</code>```

I think this covers all cases.  In a sense it's recursive but through updating it's list rather than calling itself.

Body:
My inclination as to an algorithm which is basically greedy:

Build a list of points that need to be moved.  Since optimizing this isn't part of the required problem I'm not going to worry about organizing it.

while !Done
    if CartIsEmpty()
        FindClosestObjectToMove()
        MoveToObject()
       LoadCart()
    else
        Destination = Cart.Contains.Target
        CurrentMove = [Location, Destination]
        SubList = List.Where(Move.Within(CurrentMove))
        if !SubList.Empty
            Destination = SubList.FindSmallest(Location, Move.Origin)
        MoveTo(Destination)
        if !Destination.Empty
            SwapCart()
            UpdateTaskList()
        else
            EmptyCart()
            DeleteTask()

I think this covers all cases.  In a sense it's recursive but through updating it's list rather than calling itself.


问:
Effective ways to make your OSS project popular?
After writing a few (relatively obscure) OSS frameworks, I've learned the hard way that writing a good framework isn't enough--there has to be some time spent marketing your framework as much as the time you spend coding it. So here's my question: What are some effective ways for making your OSS project become well-known? Aside from blogging, how do I gain the most market attention for my code with the least amount of effort as humanly possible?

(EDIT: I'm a lazy programmer and I hate documentation, but I'm biting the bullet. I want to be famous)

答:
Write something awesome.

Package it for as many distros as possible.

Document, document, document.

Lower the barrier to entry for new contributors as much as possible.  (Make sure anonymous users can file bugs, make your source tree easy to find, etc.)

Do a talk at a local user group (quick overview followed by a how-to seems most effective) or two.

In general, new open source toys spread like wildfire once a handful of people are convinced they are awesome.

Frameworks and libraries are a bit slower on the uptake, though, because once one chooses something as a dependency, one has something to lose if it becomes unmaintained or goes in an icky direction.  Forking costs time and attention that most devs would rather spend on their project than their project's dependencies.

In my experience, the fastest way to build trust for a library, framework, or other things that have value primarily as dependencies rather than stand-alone projects is:

Have great DX (dev experience).  We're a lazy bunch, and we take the easiest-to-use tool whenever possible.

Create and use something that depends on the library/framework.  This shows that you are invested in keeping it healthy over time.

Have more than one maintainer.  In the open source world, anyone can fork if you lose interest or get hit by a bus. However, if either no one is prepared to take the hand-off, or multiple forks appear while the rest of us are attending your funeral, there's chaos and upheaval that will be a giant PITA for anyone relying on your framework.  There should be more than one maintainer, and there should be a public note somewhere re: continuity, along the lines of "if I appear to be dead, MIA, abducted by aliens, or otherwise permanently unavailable, Joe Schmoe (Schmoe@example.com) is to succeed me as the BDFL of Project Foo".

Create a space dedicated to showcasing awesome things that have been done with your framework.

In other words: show potential users that your framework will still be around tomorrow.  This means demonstrating not just its usefulness, but that you and others are invested in continuing to develop and use it.


问:
Difference between functional test and integration test
I am deeply confused the difference. I've read so many definitions and they always explain functional test as testing the requirement is satisfied. Well, that's just rephrasing the name functional test. That doesn't clarify the difference.

I am interested in some real code to demonstrate the difference.

Suppose we have a function in a library performs hashing:

```<code>def custom_hasher(scheme, val):
    # use many hashing libraries...

def hasher(inlist, scheme):
    """ Take a list and outputs the hashed values of a list. """

    output = list()
    for val in inlist:
        output.append(custom_hasher(scheme, val))
    return output
</code>```

Now for a functional test, I am guessing we want to test ['a', 'b'] is returned as something like ['jask34sdasdas', 'asasjdk234sjdk'] given some scheme.

But that's just about what an integration test can do! I know exactly what type input I want (I want good execution so I pass in a list), or I want it to raise Object has no append method exception if I pass in a dictionary.

I can do that in both. Where's the distinction?

Another example is some web app:

```<code>@logged_in   # only logged in user can do this
@route("/invite", method=['POST'])
def send_invite(request):
   recp_email = request.data['recp_email']

   # now do a bunch of logics before and after sending an email
</code>```

So in my integration test, I will definitely do this over a network (have the server running). Send some request to this url. Same for functional test.

How to draw a line? For this case, I can write a functional test that tests to find an email is sent by looking at the send log in some table. But that's a different function than what I am testing (the view send_invite).

So I don't see how to differentiate the two. They both assert something.

Please help.

答:
Functional tests are generally used as a synonym for integration tests. You may be confusing the unit tests with functional tests if I understood your question correctly.

In unit tests, aim to test the function itself in isolation, by mocking/stubbing other components.

In integration tests, test different systems working together, to see if they work together correctly to produce the correct output.

For your example send_invite, in unit tests, you can mock the email and other framework components, and just test if the send invite function correctly calls the email component with correct arguments. For the integration tests, you can set up a testing server and see if the function correctly sends emails and does everything it supposed to do, including the other components.

Unit tests are the smallest testing block, followed by the integration tests.

EDIT:

Let's leave the words aside and approach the problem as why we need tests. We need tests to ensure our code is working correctly.

In the send_email example, first we need to test the function in isolation to see it does what it supposed to do. We do this by isolating the function from other components by mocking/stubbing to test the function itself. Assuming we have a different component that is responsible for sending emails, and our function is calling this component to send emails, if our email component is broken, we won't want this to affect the test of send_email, it's not directly related to this function. We just want to make sure the code in the send_email function is working correctly. That is generally called unit testing.

After we are sure the function is working correctly in isolation, we need to test if the invitation system is working correctly, with all of it's components. This time we do it by testing the function without mocks/stubs. This is generally called integration tests.

In some places, there are functional tests with side effects and functional tests without side effects, which means calling the function with predefined arguments in tests without mocking/stubbing to see it produces the correct output, and calling the function with predefined arguments in tests with mocking/stubbing other components, respectively. This can translates into unit tests and integration tests.

The language can be confusing, and different cultures/communities sometimes call these tests with different words. What needs to be done in testing is, starting testing with the smallest meaningful unit possible, and work from there to whole system.(This can be done in reverse order too, but it's out of the scope of this answer)


答:
For Erlang it is common to have one process per connection or other task. So for example a streaming audio server might have 1 process per connected user.

The Erlang VM is optimised to handle thousands or even hundreds of thousands of processes by making context switches very cheap.


问:
Secure silverlight WCF calls
I have a Silverlight application that uses Entity Framework.

The application are protected with a login made in ASP, so only valid users get the xap file.

Have do I secure the WCF calls to the Entity Framework? I have to make the calls over https, but have can i make sure that only valid users can get data from the WCF service?

Thanks
Jakob

答:
It's not easy. Ultimately, you're distributing the Silverlight application to users, and if those users want to examine its communications, they can do so.

If you do nothing to secure it, that's as simple as running a proxy such as Fiddler and just looking at what URLs it hits and what parameters it passes.

If you do take steps to secure it, bear in mind that since the users have the executable, they can reverse-engineer it. I've not disassembled a Silverlight app but I assume that like other .NET assemblies, it's not a particularly difficult process.

But if you want to put up a barrier to entry that will at least ensure that only people willing to make a genuine effort can reverse-engineer it, do something like this:

Public/private key pair; public key is in the app, private key on your server

All WCF calls include a parameter which is the other parameters concatenated and then encrypted with the public key

Server verifies this parameter on all calls

If you want to take one more step to protect against replay attacks, add a timestamp parameter to all service calls. This timestamp (which is concatenated along with the other parameters before encrypting) is also checked; allow some leeway for clocks being out of sync, but if it's more than a few minutes different to the server clock, reject the call.

But before spending too much time doing all this, once again, don't expect it to be foolproof.

Title: Secure silverlight WCF calls


问:
Committing https certificates to Github...is there ever a good reason for this?
If a server certificate is published to Github, a la:

```<code>-----BEGIN CERTIFICATE-----
</code>```

is that necessarily a bad thing? Is there ever a legitimate reason to do this?

I ask because of a recent wave of attention Github has gotten since allowing users to search for certain things as .ssh/id.rsa and the like in public repositories.

Also, server certificates are involved in the https protocol, but honestly I'm having trouble determining if they are generally regarded as sensitive information.

答: If its just a certificate there is not problem, as these only contain the public key. The problem is if the private key is publicised as is the case with for example id.rsa</p>


问:
Single-Tenant Databases - creating and updating new tenants via PHP
We've built a single-tenant webapp in PHP and as it stands each hosted 'site' has its own database.

However we need to be able to run a script to create their database, assign a mysql user, and insert the default sql.

Now, we've got the database and user stuff working fine, its just the importing of the SQL. From what I can tell, PHP quite simply sucks when it comes to handling sql files, so storing a 'template' sql file seems to be out of the question.

My next thought was maybe storing a live database which is then cloned, giving the site its pre-populated database, however I cant see how this would work.

At the same time, I'd rather not 'hard code' the table creations into PHP as if we perform any updates we want to be able to update the SQL direct from our backend control panel.

Surely there has to be a logical way of handling creations and updates on a multi-tenant SaaS?

答:
I think I would connect to the database you want to take this from, and query the information_schema database in you MySQL server that holds info on all databases. Then loop it, then use what ever is in it to make a new database by running querys. If you change some fields or table names you don't need to worry about anything beeing hardcoded, because all names are taken from the information_schema and not an existing database that you might change:

```<code>select * from SCHEMATA  where SCHEMA_NAME = 'dateabase_to_clone'
</code>```

You can pass in the name with a variable, so when you start this cloning script nothing at all is hard coded. This gets you the specifics on the database, caracterset, colarion, path. You can now create an identical database dynamically.

```<code>select * from TABLES where TABLE_SCHEMA = 'database_to_clone'
</code>```

gives you a list off all the tables in this database. You loop it and get the rest and so on.

Body:
I think I would connect to the database you want to take this from, and query the information_schema database in you MySQL server that holds info on all databases. Then loop it, then use what ever is in it to make a new database by running querys. If you change some fields or table names you don't need to worry about anything beeing hardcoded, because all names are taken from the information_schema and not an existing database that you might change:

select * from SCHEMATA  where SCHEMA_NAME = 'dateabase_to_clone'

You can pass in the name with a variable, so when you start this cloning script nothing at all is hard coded. This gets you the specifics on the database, caracterset, colarion, path. You can now create an identical database dynamically.

select * from TABLES where TABLE_SCHEMA = 'database_to_clone'

gives you a list off all the tables in this database. You loop it and get the rest and so on.


问:
How to extract operators from the grammar productions for conflict resolution in LALR parser?
Is there some standardized or widely accepted algorithm for picking up operators in shift/reduce conflicts in LALR parser? The question is naive, my problem is not with implementing my solution, but implementing the solution is already widely used.

For shift the operator is the next input token, for reduce, it depends -- I consider all already read symbols (for given production) declared as operators:

if there is one -- it is the operator

if there are more than one -- I report grammar error

if there is none I use the input token as operator

So for example:

```<code>E ::= E + E
E ::= E * E
E ::= num
</code>```

in case of

```<code>E + E | * num
</code>```

Considering first production I read +, and since it is the only one operator read I pick this one for reduce operator. * is the first token in input so it servers as shift operator.

But is my algorithm correct (i.e. the same as normally used for LALR parsers)? I am especially worried for the point when I have more than 1 operator in the read tokens.

Update

What I NOT am asking here

I don't ask how to resolve shift/reduce conflict once you have the operators. I don't ask how to set the precedence for operators.

What I am asking here

I ask how to extract operators from the "stream" of tokens. Let's say user set some precedence rules for +, - and *. The stack is: - E + E and input is E. Or the stack is E and input is *.

What is the operator for reduce in first case? And in the second? Why?

The stack is really entire right hand side of production.

答:
Converted from a comment, first, a rephrasing of your question:

Suppose we have the following ambiguous grammar:

```<code>E ::= E + E
E ::= E * E
E ::= num
</code>```

In the LR automaton, we will have the following shift-reduce conflict (among others):

```<code>E ::= E * E •, +
E ::= E • + E
</code>```

As is common knowledge, reducing here will make '*' bind more tightly as '+' (as normal), while shifting will make '+' bind more tightly.

Parser generators such as Yacc and Bison allow the user to mark tokens as binding more tightly than other tokens. As normal, we say that '* > +'.

However, there seems to be a mismatch somewhere: the '>' we use above is an operator between two tokens, but the shift-reduce conflict is a conflict between a token and a production.

In Yacc and Bison, not just tokens but productions also have a priority. The user can mark tokens with priorities (as is normally done), and productions (that have not been given an explicit priority) have their priority inferred. The priority of a production is equal to the priority of the rightmost token in the production.

In "E ::= E * E", the rightmost token is '*', so in the shift reduce conflict above the priority of the reduction is '*', and the priority of the shift is '+', and as the priority of '*' is higher than '+', we decide to reduce rather than shift. As another example, the rightmost token of "A ::= a b B c d C D E" is 'd' (with only capitalized letters being nonterminals).

Adding "A ::= a b B c d C D E %prec a" to a production in Yacc and Bison explicitly gives that production the priority of 'a', but this is not normally done. Note that some productions may not have a rightmost token, or the priority between tokens is not defined, in which cases Yacc and Bison fall back to always shifting to resolve conflicts (Yacc and Bison always create a fully deterministic table, unless in GLR mode).

For completeness: the action with higher priority wins, so if the production has a higher priority than the token, we reduce instead of shifting. If priorities are equal, we look at associativity: left associativity means reducing, right associativity means shifting. 'nonassoc' is the third type of 'associativity', and it means an error: the shift/reduce conflict is resolved by removing both entries in the table, so the parser rejects inputs entering that state with that lookahead.

Body:
Converted from a comment, first, a rephrasing of your question:

Suppose we have the following ambiguous grammar:

E ::= E + E
E ::= E * E
E ::= num

In the LR automaton, we will have the following shift-reduce conflict (among others):

E ::= E * E •, +
E ::= E • + E

As is common knowledge, reducing here will make '*' bind more tightly as '+' (as normal), while shifting will make '+' bind more tightly.

Parser generators such as Yacc and Bison allow the user to mark tokens as binding more tightly than other tokens. As normal, we say that '* > +'.

However, there seems to be a mismatch somewhere: the '>' we use above is an operator between two tokens, but the shift-reduce conflict is a conflict between a token and a production.

In Yacc and Bison, not just tokens but productions also have a priority. The user can mark tokens with priorities (as is normally done), and productions (that have not been given an explicit priority) have their priority inferred. The priority of a production is equal to the priority of the rightmost token in the production.

In "E ::= E * E", the rightmost token is '*', so in the shift reduce conflict above the priority of the reduction is '*', and the priority of the shift is '+', and as the priority of '*' is higher than '+', we decide to reduce rather than shift. As another example, the rightmost token of "A ::= a b B c d C D E" is 'd' (with only capitalized letters being nonterminals).

Adding "A ::= a b B c d C D E %prec a" to a production in Yacc and Bison explicitly gives that production the priority of 'a', but this is not normally done. Note that some productions may not have a rightmost token, or the priority between tokens is not defined, in which cases Yacc and Bison fall back to always shifting to resolve conflicts (Yacc and Bison always create a fully deterministic table, unless in GLR mode).

For completeness: the action with higher priority wins, so if the production has a higher priority than the token, we reduce instead of shifting. If priorities are equal, we look at associativity: left associativity means reducing, right associativity means shifting. 'nonassoc' is the third type of 'associativity', and it means an error: the shift/reduce conflict is resolved by removing both entries in the table, so the parser rejects inputs entering that state with that lookahead.


问:
Would it be bad design to abstract a graphics library and wrap it in a single class?
I'm starting a game project in C++ using the SFML.

It provides various classes for handling graphics, input, etc, but I would like to wrap it all up in a single Media class.

I believe that by doing so, I could simplify my effort and have the class take care of the details, limiting the amount of code I have to write and therefor limiting chances for a bug to sneak past my eyes.

However, I have read several times that monolithic, do-it-all classes such as this might not be a good idea.

Why is that?

答:
Would it be bad design to abstract a graphics library and wrap it in a
  single class?

The answer is: Not necessarily!
But in your case: Probably!

I guess what you are trying to do also has a name: It's called the facade pattern and is used to simplify complex routines and sequential dependencies for the user.

It provides various classes for handling graphics, input, etc, but I
  would like to wrap it all up in a single Media class.

I smell bad OO Design here because you give a class multiple responsibilities. Input Handling should not share code with the graphics routines. This class could very well add up to something unmaintainable eventually.

However, I have read several times that monolithic, do-it-all classes
  such as this might not be a good idea.

Why is that?

It's all about maintainability. You're coupling things which do not belong together, and every part of your system that uses it then has a strong coupling to these things as well. Let me give you a quick example of code I saw recently:

```<code>//bad! This is in a data access class! I have effectively coupled it to web libraries by using HttpServletRequest
public List<Reason> getReasons(HttpServletRequest request, String filter) {
    Locale locale = request.getLocale();
    //get reasons and process according to locale
}

//much much better: No coupling/dependencies to web environment
public List<Reason> getReasons(Locale locale, String filter) {
    //get reasons and process according to locale
}
</code>```

Think about this example: If I'd use that class in Desktop-Application, I'd still have all the web stuff in there, just because someone decided to use HttpServletRequest. It'd be an unecessary dependency.

You might ask how this is directly related to your question, and the answer is: It's all about dependencies/coupling. The more dependencies, the stronger your couplings, the harder your code will be to reuse or to enhance or to maintain without carrying around a lot of garbage or using ugly hacks.

Body:
Would it be bad design to abstract a graphics library and wrap it in a
  single class?

The answer is: Not necessarily!
But in your case: Probably!

I guess what you are trying to do also has a name: It's called the facade pattern and is used to simplify complex routines and sequential dependencies for the user.

It provides various classes for handling graphics, input, etc, but I
  would like to wrap it all up in a single Media class.

I smell bad OO Design here because you give a class multiple responsibilities. Input Handling should not share code with the graphics routines. This class could very well add up to something unmaintainable eventually.

However, I have read several times that monolithic, do-it-all classes
  such as this might not be a good idea.

Why is that?

It's all about maintainability. You're coupling things which do not belong together, and every part of your system that uses it then has a strong coupling to these things as well. Let me give you a quick example of code I saw recently:

//bad! This is in a data access class! I have effectively coupled it to web libraries by using HttpServletRequest
public List<Reason> getReasons(HttpServletRequest request, String filter) {
    Locale locale = request.getLocale();
    //get reasons and process according to locale
}

//much much better: No coupling/dependencies to web environment
public List<Reason> getReasons(Locale locale, String filter) {
    //get reasons and process according to locale
}

Think about this example: If I'd use that class in Desktop-Application, I'd still have all the web stuff in there, just because someone decided to use HttpServletRequest. It'd be an unecessary dependency.

You might ask how this is directly related to your question, and the answer is: It's all about dependencies/coupling. The more dependencies, the stronger your couplings, the harder your code will be to reuse or to enhance or to maintain without carrying around a lot of garbage or using ugly hacks.


答: Because any time you have to change anything, you'll find it has impacts on everything. In addition, one class can only have one lifetime, whereas in reality you want to have several lifetimes for several different components- for example, you want each sprite to live a different length of time.

Title: Would it be bad design to abstract a graphics library and wrap it in a single class?

Body:
I'm starting a game project in C++ using the SFML.

It provides various classes for handling graphics, input, etc, but I would like to wrap it all up in a single Media class.

I believe that by doing so, I could simplify my effort and have the class take care of the details, limiting the amount of code I have to write and therefor limiting chances for a bug to sneak past my eyes.

However, I have read several times that monolithic, do-it-all classes such as this might not be a good idea.

Why is that?


答: Some rendering tasks spring to mind here.  If you're doing a long chain of ops on every pixel of an image, and if those ops are parallelizable, then even a relatively small 1024x768 image is right into the "hundreds of thousands" bracket.</p>


问:
How can I work on different projects without losing focus?
I'm doing a full-time job (developer) and at the end of the day, I work on my part-time job (developer).

How do you work, with different projects, without loosing focus?  Often, my focus on the full-time job still remains at my head when working on my part-time job or the other way around.

答:
IMO, the best recipe is to make a habit out of always leaving your projects in a state that allows you to drop them on a moment's notice and pick them up six months later, with very little delay. This means:

Work in super-short iterations - not months, not weeks, not even work days, but hours or even less. Aim for a working, bug-free, useful build after each such iteration (even if this may mean that the code you wrote in the current session is inaccessible to anything but your unit tests right now: the important thing is that it compiles, passes the tests, and doesn't break anything).

Document everything you do, while you do it.

Don't leave uncommitted changes around: commit early, commit often.

If you have to work on different features in parallel, use feature branches.

Always leave your code in a readable state. Refactor early, refactor often.

Write automated tests right now. Automated tests are an integral part of the development cycle, not a separate feature.

Be consistent. The more consistent you are, the less you have to remember - if, for example, all the getter methods in your project follow the naming convention getFieldName, and you know you can be 100% sure that there are no exceptions, you never have to look up the name of a getter.

Be religious about readability.

Design your internal APIs and libraries according to the principle of least surprise. Less exceptions means less time required to consult the documentation.

Use a bug tracker, wiki, ticket system, or even a plain old text file, anything that helps you organize and prioritize your thoughts. It doesn't need a lot of bells and whistles, as long as you can easily throw random pieces of information at it and retrieve them quickly and efficiently.

The central idea is "fire-and-forget": Make it so that each project requires minimum brain resources for any given task, and that as much information as possible can be outsourced to your tools - a wiki, source control, and of course the source code itself. That way, the amount of thoughts in your brain that you need to swap out when switching between projects is minimal; ideally, all you need to do is point your development environment (whether this is an IDE or a command line doesn't really matter) to the current project, maybe issue one or two commands, and you'll have all the hints you need to dive back in.


问:
Possible with PHP MVC Framework? A better solution to client 'override' of core functionality?
Background / The Problem

I need to make a (large) application with a certain set of core functionality, and certain functionality for multiple clients within it. Each client has different requirements and while they may share some functionality, I need to separate the code for each client, so a change to one won't affect others. Each client section of the application should also inherit some features from the core application. Ideally I would like to separate the databases for each client too. In terms of a user system, core users should be able to have access to each client's functionality, but client users should only be able to interact with their specific client section of the site.

Current Solution

Each client has its own subdomain and the MVC can override the core's MVC files IF they exist. In a nutshell, my custom MVC's autoloader checks the client directory for the matching M,V, or C file when a subdomain is present in the URL and loads that particular client's file INSTEAD OF the core file. It's an override ability in a sense.

Questions

Am I solving this problem in a way that would be considered good practice in terms of software design?

If I were to use an existing PHP Framework (I would like to), how might I go about setting it up to solve this problem? Specifically I have been looking at Yii and CodeIgniter.

Thanks in advance!

Update:
I have discovered a design pattern called HMVC (Hierarchical MVC) and it seems to be essentially what I have described. I see that Kohana 3 is built using it and that Codeigniter has an extension that allows it.

答:
This may or may not be of any use to you, but look at Symfony 2's "Bundle Inheritance". It allows you to override functionality from distributed bundles on an application level.

If you developed your core functionality in a bundle, you could deploy multiple applications and do the overrides there. Keep the core bundle in sync with via version control and a Composer repository, and the only things that would differ between these applications would be the client-specific modifications.

The downfall with this approach is that you're managing N deployed applications, which isn't exactly friendly. Perhaps you could fork Symfony 2 and alter the class loader to be client-aware so you can have multiple client folders in your application deployment. It should be a relatively simple fork, so keeping Symfony updated would be trivial.


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
I find the statement that 99% of the programmers are unable to program or to solve a simple coding test highly exaggerated. In the case of the FizzBuzz test, either you have encountered this problem before and can easily solve it with the modulo operator or you have not encountered it before and will struggle with it. It tells the interviewer nothing about your programming skills.

I think the problem with many programmers apparently leaving a bad impression at an interview lie in the nature of technical interviewing methods. Interviewers expect applicants to memorize and instantly reproduce language syntax, details and computational complexity of data structures, hardware architectures, design patterns, etc, etc. The area of computer science/software engineering is vast. It is impossible and insensible to try to memorize everything.

In the real world, the key is to be able to understand the programming/design problem assigned to you and to know where to find information(your IDE, man pages, books, google, etc) how to solve your problem. This is something however that interviewers never test for.

Title: FizzBuzz - really?


问:
Should code-behind in WPF be considered part of the view?
I've read plenty of articles around different patterns in use with WPF and this is something I've yet to understand: should a code-behind file be considered part of the view? As a consequence, should code-behind files be allowed utilise knowledge of specific elements in the markup?

I have a number of scenarios where the controls which are present in a view are influenced by data in the view model (eg a button for each list item). Currently, I handle these kinds of scenarios in the relevant code-behind file. To me, this feels like an implementation detail of the view and thus part of it; another view of the same view model might choose a list box of list items for example).

答:
The XAML and the code behind together represent the view, i.e. the visual representation of the ViewModel. A lot of the time the tools and methods available in XAML (i.e. data-binding declarations with formatters and whatever templates you need) are sufficient to control the layout to your satisfaction, and so the code behind is not needed or can be empty.

However, I've come across situations before where presenting the data how I want using just XAML and no code is a real hastle. In these situations, if it's more natural to generate the UI controls in the code behind, then do it. It's essentially only a different way of defining your view (i.e. in procedural code rather than declarative XAML).

I have a number of scenarios where the controls which are present in a view are influenced by data in the view model (eg a button for each list item). Currently, I handle these kinds of scenarios in the relevant code-behind file.

If I understand the situation correctly, then I think in WPF this can and should be done with DataTemplates and DataBinding in XAML, so there's no need to use the code behind file.


答:
I can think of an easy legitimate reason: suppose I write a program to do an offline version of the SSL Labs server test. A good test suite for that program would include various certificates with different problems and some configuration to use them for testing. E.g. it checks for the Debian weak key problem, so you'd want a certificate with a Debian weak key (perhaps for the domain weakkey.example.com).

Of course, test certificates are not the same as real signed certs from a proper CA. (For testing purposes you'd use a testing CA). I would imagine that the major CAs have revoked the certificates whose private keys were available on github.

(Incidentally, if anyone knows of a repository of test certs, feel free to leave a comment...)

Title: Committing https certificates to Github...is there ever a good reason for this?

Body:
If a server certificate is published to Github, a la:

```<code>-----BEGIN CERTIFICATE-----
</code>```

is that necessarily a bad thing? Is there ever a legitimate reason to do this?

I ask because of a recent wave of attention Github has gotten since allowing users to search for certain things as .ssh/id.rsa and the like in public repositories.

Also, server certificates are involved in the https protocol, but honestly I'm having trouble determining if they are generally regarded as sensitive information.


问:
Is a pair of two tightly coupled classes any better than a single, larger class?
I'm rewriting somebody else's code at the minute, and I came across two classes which reference each other directly and call methods on each other. Like so (example in C#):

```<code>class A {
  B otherClass;
  public A() {
    this.otherClass = new B(this);
  }
  // Other methods here call methods on B
}

class B {
  A otherClass;
  public B(A otherClass) {
    this.otherClass = otherClass;
  }
  // Other methods here call methods on A
}
</code>```

Reading through his code and trying to understand it, I'm having to move between the two classes as they call each other.

These classes are not independently reusable without using the other. I'm aware it's considered best practice to avoid circular references (and it's straight up not allowed between C# projects in Visual Studio), but is this, or could this be, in your experience any better than having a single - larger - class?

答:
It's usually not about the two classes being independent as logical modules, but their lifetimes being independent. An excellent example is if A is a LinkedList and B is a Node. Conceptually, they're just one thing, a LinkedList, but B has to be separate so that it can be created and destroyed independently.

If that does not apply, you may wish to consider creating a single larger class.


问:
How to Model a simple file-system by UML class diagram
I want to model a file system which contains both files and directories, and directories can contain either files or other directories.

This is what I have reached so far:

In OOSE book, however, a similar model is presented:

Now I have two questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

答: It is called the Composite Pattern and as such does not possess an Association between the Composite (Directory) and the Leaf (File). I think that was a diagramming mishap in the first picture, although technically it does not suggest an assocation between them two - it just looks like one.</p>


答:
While is it probably not the best setup, there could be some advantages to a pair of tightly coupled classes over one large class.

While working with the Google Web Toolkit in Java, I have run across this pattern often as a part of the MVP pattern. Class A is the view and Class B is the presenter. The view has dependencies on the browser DOM, making it difficult to test, while the presenter contains all of the logic. By injecting a mocked version of the view into the presenter, the application becomes much more testable.

If the classes have not been split for testability via mocking, then I would argue that this split, while perhaps a step in the right direction, is not entirely useful. Sure, it may help to separate the code by what it does (like if class A was managing database connections while B was managing querying), but the code could be reengineered to not have the circular dependency.

Title: Is a pair of two tightly coupled classes any better than a single, larger class?

Body:
I'm rewriting somebody else's code at the minute, and I came across two classes which reference each other directly and call methods on each other. Like so (example in C#):

```<code>class A {
  B otherClass;
  public A() {
    this.otherClass = new B(this);
  }
  // Other methods here call methods on B
}

class B {
  A otherClass;
  public B(A otherClass) {
    this.otherClass = otherClass;
  }
  // Other methods here call methods on A
}
</code>```

Reading through his code and trying to understand it, I'm having to move between the two classes as they call each other.

These classes are not independently reusable without using the other. I'm aware it's considered best practice to avoid circular references (and it's straight up not allowed between C# projects in Visual Studio), but is this, or could this be, in your experience any better than having a single - larger - class?


答:
It's less about where you post, more about what you post.

People fear that trying out an unknown framework will be a massive waste of their time.  Reassure them.  Use screenshots to show them that it will be easy.  Give a step by step guide that shows promise of being able to do your 'hello new-framework-world' within moments of downloading.  Show that any pain will be worthwhile by killer examples.  If you can run a space station with five lines of code using your framework, show them the code to do it.

Once people know it will be worthwhile they'll do the download.

Title: Effective ways to make your OSS project popular?

Body:
After writing a few (relatively obscure) OSS frameworks, I've learned the hard way that writing a good framework isn't enough--there has to be some time spent marketing your framework as much as the time you spend coding it. So here's my question: What are some effective ways for making your OSS project become well-known? Aside from blogging, how do I gain the most market attention for my code with the least amount of effort as humanly possible?

(EDIT: I'm a lazy programmer and I hate documentation, but I'm biting the bullet. I want to be famous)


问:
When to import names into the global namespace? (using x::y, from x import y etc.)
I've been programming in various languages for about 10 years now. And I still haven't figured out when it is a good idea to import something into the global namespace (using x::y in C++, from x import y in Python etc.), so I hardly ever do it.

It almost always seems like a bad idea to me, if only because it limits the set of variable names I can use. For example: Where I to use using namespace std; or using std::string;in C++, I couldn't use stringas a variable name anymore, which I occasionally do (e.g. for string utility functions).

But I'm wondering: Are there some situations where importing a name into the global namespace really makes sense? Any rules of thumb?

答: In C++, it's generally frowned upon- especially using namespace std. That std namespace has so many names, many of which are very generic algorithms, you can get some extremely nasty surprises when using namespace std. Something like using std::cout; isn't so bad. But never, ever, using anything into the global namespace in a header file. That's a firing-squad offence.


答:
As you've described the classes, I think it's fine. It's not really a circular reference. A is dependant on an instance B & B cannot exist without an instance of A. You cannot create an instance of B with an A.

The only thing that I'd be looking at is if the functionality within each class is appropriate.

ie think of each as a black box. Could you create a new derived class from B and use that in A? Could you do that without knowing what A was doing? Could you do the same with A without knowing what B was doing?