问:
Should a User class only contain attributes and no methods apart from getters/setters?
I'm trying to improve my OOP code and I think my User class is becoming way too fat.

In my program a user has rights over "lists". Read, Write, Update, Delete.
So I made a User class

```<code>class User
{
protected $_id;
protected $_email;
protected $_username;
protected $_hashedPassword;

//...Various setters/getters

public function canRead(List $list){
    //Database query verifies if user has READ rights
}

public function canUpdate(List $list){
    //Database query verifies if user has UPDATE rights
}
//etc...
}
</code>```

Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?

If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?

答:
I like the idea of putting business logic in model classes like User.  In fact, I have done exactly that before with privilege methods like canDoBlah().

It makes for easy-to-read code when one uses the object in the UI layer:

```<code>public void processList(User user, List list) {
    if (user.canReadList(list)) {
        // do some work
    }
}
</code>```

I suppose you could put the logic in the List class like you suggested with listCanBeReadByUser(), which for all intents and purposes is the same, but I think it's easier to read on the User object.

The only suggestion that I would make is to avoid putting SQL in the model class.  That belongs in the persistence layer, perhaps in a DAO.

Body:
I like the idea of putting business logic in model classes like User.  In fact, I have done exactly that before with privilege methods like canDoBlah().

It makes for easy-to-read code when one uses the object in the UI layer:

public void processList(User user, List list) {
    if (user.canReadList(list)) {
        // do some work
    }
}

I suppose you could put the logic in the List class like you suggested with listCanBeReadByUser(), which for all intents and purposes is the same, but I think it's easier to read on the User object.

The only suggestion that I would make is to avoid putting SQL in the model class.  That belongs in the persistence layer, perhaps in a DAO.


答:
A class should have only one purpose to exist.

Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?

Yes, these methods should be put in separate classes.

ContentLicense: CC BY-SA 3.0

Title: Should a User class only contain attributes and no methods apart from getters/setters?

Body:
I'm trying to improve my OOP code and I think my User class is becoming way too fat.

In my program a user has rights over "lists". Read, Write, Update, Delete.
So I made a User class

```<code>class User
{
protected $_id;
protected $_email;
protected $_username;
protected $_hashedPassword;

//...Various setters/getters

public function canRead(List $list){
    //Database query verifies if user has READ rights
}

public function canUpdate(List $list){
    //Database query verifies if user has UPDATE rights
}
//etc...
}
</code>```

Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?

If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?


问:
How to close a bug that is no longer relevant
I'm currently on a medium-sized team of web developers. We're using jira for bug tracking.

We're working on a product with frequent layout changes. A lot of times bugs are filed about a bug in the layout in some browser. Sometimes, by the time we get around to dealing with a low priority bug, the layout has already changed and it is no longer relevant.

What should we close it as?

What I mean is how we should treat these issues? While Jira is the bug tracking software we use, I'm more interested in how to handle these sort of issues in general.

Does it even matter? (We might return to the layout later, but it's very unlikely)

答:
Nuances like that matter if you consider issue tracker as a means to communicate the status of problems that were reported in the project. For that purpose, it makes sense to invest some effort into ensuring that bug report is easy to read and understand.

This situation gets much less confusing if you look at it from a perspective of a tester. If your team doesn't have a tester, imagine one (or better yet, hire one 1, 2, 3).

Okay, so there was a bug once upon a time, tester can reproduce it using older releases of your application (side note in unlikely case that you don't keep copies of older releases, then you've got much much harder problems in your team than obsolete bugs). Tester can see it and can tell what's wrong, what is it that makes it a bug.

Now you say, "layout has already changed and it is no longer relevant" - the high-brow no longer relevant turns in tester mind into much simpler statement: the problem has gone.

It is important to note here that professional tester should be comfortable thinking of the system as a black box. From that perspective, it doesn't matter much how exactly it happened that problem has gone, it could be layout change or black magic or total redesign, or concrete code change, whatever.

From black box perspective, your situation is pretty simple. There was a problem, it's still reproducible in older release, now you claim that newer release has no such problem anymore. For a tester, this boils down to a claim that bug is fixed and, respectively, to the need to verify whether the claim is true.

Professional tester would take your older release, look at how problem is present there, then take newer release and check if it is gone or still there.

From above, the most accurate way to handle bugs like you describe, would be to close these as resolved, fixed. Of course it wouldn't hurt if you clarify in the comments that the fix occurred as an unintended side effect of layout change.

One of customized JIRAs I used to work with in a past project had resolution "Fixed By Design" to communicate rather profound changes having lots of consequences, some intentional, some not. For case like you describe, that could be also considered instead of plain "Fixed", since it hints ticket reader on that it's more of a side effect rather than intentional code change.


答:
What you are doing is putting together a mechanism for access control (lists) or ACL.  In general, as Ritesh says, it's a bad idea to do that all in one class.

This answer on SO has a nicer, OO way of dealing with access control.

Rather than extending your User class, you should wrap your User class inside a SecureContainer. See the linked-to answer for details, but then the overall call would be:

```<code>// assuming that you have two objects already: $currentUser and $controller
$acl = new AccessControlList( $currentUser );

$controller = new SecureContainer( $controller, $acl );
// you can execute all the methods you had in previous controller
// only now they will be checked against ACL
$controller->actionIndex();
</code>```

This allows the User class to focus on what it needs to do, and allows the AccessControlList class to focus on what it needs to do.

Body:
What you are doing is putting together a mechanism for access control (lists) or ACL.  In general, as Ritesh says, it's a bad idea to do that all in one class.

This answer on SO has a nicer, OO way of dealing with access control.

Rather than extending your User class, you should wrap your User class inside a SecureContainer. See the linked-to answer for details, but then the overall call would be:

// assuming that you have two objects already: $currentUser and $controller
$acl = new AccessControlList( $currentUser );

$controller = new SecureContainer( $controller, $acl );
// you can execute all the methods you had in previous controller
// only now they will be checked against ACL
$controller->actionIndex();

This allows the User class to focus on what it needs to do, and allows the AccessControlList class to focus on what it needs to do.


答:
if the permission is in some sense a property of the user, that's the natural place for it to store the data

if the permission is a property of the list, that's the natural place to store it

if the test for permission is naturally an action on the user (ie, that syntax fits best with your usage pattern), that's the natural place to put the method

if the list shouldn't know about the user, and the user shouldn't know about the list, but some separate ACL should know about both and their relationships, maybe that is where the data and/or method should go

etc. etc.

In general, there seem to be three separate (or separable) concerns: describing a User, storing a List, and managing the Access of one to the other.

If you choose to combine two of those concerns into the same class (and if so, which), it should either be because this arrangement emerges naturally from your model (... is a property of ...), or because it's more convenient or efficient. You haven't told us enough to make that choice for you.


问:
How do you store "fuzzy dates" into a database?
This is a problem I've run into a few times. Imagine you have a record that you want to store into a database table. This table has a DateTime column called "date_created". This one particular record was created a long time ago, and you're not really sure about the exact date, but you know the year and month. Other records you know just the year. Other records you know the day, month and year.

You can't use a DateTime field, because "May 1978" isn't a valid date. If you split it up into multiple columns, you lose the ability to query. Has anyone else run into this, if so how did you handle it?

To clarify the system I'm building, it is a system that tracks archives. Some content was produced a long time ago, and all that we know is "May 1978". I could store it as May 1 1978, but only with some way to denote that this date is only accurate to the month. That way some years later when I'm retrieving that archive, I'm not confused when the dates don't match up.

For my purposes, it is important to differentiate "unknown day in May 1978" with "May 1st, 1978". Also, I would not want to store the unknowns as 0, like "May 0, 1978" because most database systems will reject that as an invalid date value.

答: I really like James Anderson's solution - Accurately bounding the dates is the way to get the most flexible query structure. Another way of achieving the same is to use a start, end or even center date plus an interval (available at least in PostgreSQL, Oracle and SQLAlchemy).


问:
What is the difference between Quantum annealing and simulated annealing?
In both algorithms objective functions, that will be executed with non quantum computers, are used. Both algorithms are methods for finding the global minimum of a given objective function.

From wikipedia:

Quantum annealing can be compared to simulated annealing (SA), whose "temperature" parameter plays a similar role to QA's tunneling field strength.

What is meant by "tunneling field strength"?

The choice of next candidate state seems to be the only difference between the algorithms, is that correct?

Finally, what are the advantages of Quantum annealing? Is it faster, or is it just better at handling local minima?

答:
what is "tunneling field strength"?

The distance in which you randomly select the next candidate.

Choosing of next candidate state the only difference between algorithms, is it?

No. Normal simulated annealing works with fixed parameter, but quantum annealing always works with gradually decreasing parameter more like adaptive simulated annealing.

What advantage of Quantum annealing? Is it faster, or is it just better handle local minima?

It can handle wider, but slightly different set of problems. Simulated annealing only works when the barriers separating minima are relatively low, but they can be any wide. The adaptive version compensates a bit, but it remains inefficient when the barriers are high.

Quantum annealing is not limited by barrier heights and because it starts with the parameter equal to diameter of the problem space it is not limited by their widths either. However it will have problems finding global minimum surrounded by large area of high values, because if it does not hit the small low area early, it won't get there after the parameter decreases.

So quantum annealing will usually give better results, but it might not depending on the specific problem.


问:
How REST is used outside of the web
I was recently reading the Wikipedia article for Resource-Oriented Architectures (ROA) and stumbled across an article that made the assertion that, although REST is a technology that is very-well suited for web applications and web services, that it is nevertheless a standalone technology that can be used in non-web applications.

This is the first I've ever heard of such a thing! I thought REST was a SOAP competitor, but that the two were strictly web service solutions.

My question: can someone provide an example for how REST is used in something that isn't a web app? Like a Swing client, or a command line tool, or an EJB.

答:
I'm not aware of a good non-HTTP-based protocol example that fits the "many resources, few verbs; transfer all state" aspects of REST.

However, plain ROA/HTTP-style REST is used in plenty places outside the web itself. For example, I've been involved in the development of software for an industrial LED production machine, where the various components communicated with one another (within the same computer, and over an internal network between controllers inside the machine) via plain common HTTP-ish REST.

The non-realtime parts of the controller code were written in C#, and I believe one of Microsoft's WCF incarnations was used to make RESTful endpoints. Using plain HTTP and resources made debugging and message logging a charm, since all web-enabled tools (curl, browser, Fiddler2, http logs) were at our disposal.

Title: How REST is used outside of the web


答:
Abstraction is the idea.

Map all actions you want to achieve in the user class

Any action not relevant to that object should be removed.


答:
We use FogBugz, but I'm sure the same (or similar) applies here:

We just use "Resolved (Fixed)" and comment in the resolution edit something like "Fixed by case 12345".

FogBugz matches "case \d+" and links the two together under Related Cases, but if Jira doesn't do that, it should be simple to just add a link.

This is IMO better than a "Too Localized" variant because it was an actual bug, and better than just "Obsolete" because it was fixed, that feature wasn't just removed.

Title: How to close a bug that is no longer relevant

Body:
I'm currently on a medium-sized team of web developers. We're using jira for bug tracking.

We're working on a product with frequent layout changes. A lot of times bugs are filed about a bug in the layout in some browser. Sometimes, by the time we get around to dealing with a low priority bug, the layout has already changed and it is no longer relevant.

What should we close it as?

What I mean is how we should treat these issues? While Jira is the bug tracking software we use, I'm more interested in how to handle these sort of issues in general.

Does it even matter? (We might return to the layout later, but it's very unlikely)


问:
A design decision in composition or aggregation
I've recently had doubts about some design decisions that I frequently make, so this time I decided to take some time and try to analyze it to find the best solution. I will describe a simple scenario where the design decision can be easily understood. :)

Suppose we are developing a game in Java where players can have any number of many different types of items.

```<code>/** Class that represent an item type existing in the game */
// you may prefer to call this ItemType,
// but for me appending the word "Type" is not necessary
class Item {
    private String descrip;
    private Image icon;
}
</code>```

In this situation I need to keep track of how many of each item the player has in his bag, so I keep a collection of them, in each element of which I have item type and quantity. Additionally one can think of other attributes that belong to that relation (perhaps a max capacity), but the question is: how do I model this scenario in general but with a practical implementation in Java? Here are two approaches I've come up with:

Using a List

```<code>class Slot {
    private Item item;
    private int quantity;

    /** Auto generated */
    public int hashCode()
    {
        int hash = 7;
        hash = 13 * hash + (this.item != null ? this.item.hashCode() : 0);
        return hash;
    }

    /** This method is also auto generated and just compares the Item,
        independent of quantity */
    public boolean equals(Object object)
    {
        if (!(object instanceof Slot))
        {
            return false;
        }
        Slot other = (Slot) object;
        if ((this.item == null && other.item != null)
             || (this.item != null && !this.item.equals(other.item)))
        {
            return false;
        }

        return true;
    }
}
</code>```

The above class relates one item with a quantity, and a collection of Slots is the primary attribute of the Inventory class. The disadvantages of this appear as soon I design the Inventory interface to not expose Slot to the client (making Slot private or hiding it in some other way): in creating a simple interface but providing access to all the standard collection methods. In my humble opinion there is nothing wrong with this:

```<code>/** Class that represent the bag that holds the player's items */
class Inventory {
   // this collection holds only one element for each type of item
   private ArrayList<Slot> slots;

    public Inventory()
    {
        slots = new ArrayList<Slot>(10);
    }

    public void add(Item item, int quantity)
    {
        Slot slot = new Slot(item, quantity);
        // if we don't already have a Slot for the added Item, add it
        if (!slots.contains(slot))
        {
            slots.addElement(slot);
        }
        // if we already have a Slot for the added Item, increase the quantity
        else
        {
            Slot _slot = slots.elementAt(slots.indexOf(slot));
            _slot.addQuantity(quantity);
        }
    }

    public void subtract(Item item, int quantity)
    {
        Slot slot = new Slot(item, 0);
        int index = slots.indexOf(slot);

        // only if we actually have this item
        if (index != -1)
        {
            Slot _slot = (Slot) slots.elementAt(index);
            _slot.quantity -= quantity;

            // if we have fewer of the Item than the number to remove,
            // remove the slot from the collection
            if (_slot.quantity <= 0)
            {
                slots.removeElementAt(index);
            }
        }
    }

    public void remove(Item item)
    {
        Slot slot = new Slot(item,0);
        slots.removeElement(slot);
    }

    public boolean hasItem(Item item)
    {
        Slot slot = new Slot(item,0);
        return slots.contains(slot);
    }
}
</code>```

As you see, we have to jump through some hoops to implement certain collection methods: in hasItem we have to create a Slot element just for that operation. In the add and subtract methods, we have to create the Slot object just to check if it's there.
I wonder if this really necessary. I suppose that it is if we desire to provide an interface to the standard collection methods. Perhaps we can move all this logic to another class (for example: Slots), exposing a cleaner interface that lets us search by item without the need of creating a Slot, but we are just moving the same problem to another class. We will face the same problem there, besides the fact that Inventory is basically a set of Slots, we're really just creating another class to be exactly the same thing, which doesn't make a lot of sense to me.

Would it be more correct to change the interface of this class to work directly with Slot class instead? This implies moving from composition (having Slots created within Inventory) to an aggregation (having Slot creation outside of Inventory). The result might look like:

```<code>/** Class that represent the bag that holds the player's items */
class Inventory {
   private ArrayList<Slot> slots;

    public Inventory()
    {
        slots = new ArrayList<Slot>(10);
    }

    public void add(Slot slot)
    {
        if (!slots.contains(slot))
        {
            slots.addElement(slot);
        }
        else
        {
            Slot _slot = slots.elementAt(slots.indexOf(slot));
            _slot.addQuantity(slot.getQuantity());
        }
    }

    public void subtract(Slot slot, int quantity) // how would the client get the Slot?
    {
        int index = slots.indexOf(slot);

        // only if we actually have this item
        if (index != -1)
        {
            Slot _slot = (Slot) slots.elementAt(index);
            _slot.quantity -= quantity;

            // if we have fewer of the Item than the number to remove,
            // remove the slot from the collection
            if (_slot.quantity <= 0)
            {
                slots.removeElementAt(index);
            }
        }
    }

    public void remove(Slot slot) // again, how would the client get the Slot?
    {
        slots.removeElement(slot);
    }

    // Hard to change a parameter type here. This strongly suggest there is
    // a flaw in the design. I only keep this here to communicate the observation
    public boolean hasItem(Item item)
    {
        Slot slot = new Slot(item, 0); // here we have no choice but to create it
        return slots.contains(slot);
    }
}
</code>```

But again, is this convenient? I don't often put this approach into practice, so I'm not sure.

Using a lookup

Another approach is to use something like a Hashtable with Item objects as keys quantities as values, so only quantity is associated with Items, without the need for a Slot class. An Inventory implementation using Hashtable might look like:

```<code>public class Inventory
{
    private Hashtable items;

    public Inventory()
    {
        items = new Hashtable(10);
    }

    public void add(Item item, int amount)
    {
        int stock = amount;
        if (items.containsKey(item))
        {
            stock += ((Integer) items.get(item)).intValue();
        }
        items.put(item, new Integer(stock));
    }

    public void subtract(Item item, int amount)
    {
        if (items.containsKey(item))
        {
            int stock = ((Integer) items.get(item)).intValue();
            stock -= amount;
            if (stock > 0)
            {
                items.put(item, new Integer(stock));
            }
            else
            {
                items.remove(item);
            }
        }
    }

    public void remove(Item item)
    {
        this.items.remove(item);
    }

    public boolean hasItem(Item item)
    {
        return this.items.containsKey(item);
    }
}
</code>```

To me this seems much better than using a List because there is no need of the Slot class, and all interactions with the Item collection are much simpler, but I'm not sure if I'm right.

The same type of problem is also evident in this scenario:
Suppose that we are implementing an order application for a pizza shop; every order consists of types of pizzas and quantities.

```<code>/** Type of pizza */
class Pizza {
    private String descrip;
    private Image icon;
}

/** Customer request for pizza */
class Request {
    // for each type of pizza we have to keep a count of how many the customer ordered
}

/** A pizza order */
class Order {
    private Pizza pizza;
    private int   amount;
    privete BigDecimal price;
}
</code>```

Knowing how to solve the first problem, I have a pattern to use for this similar situation; so the question is, what solution is best?

I try to convince myself that I'm not the only person with this concern, that ordinary people like me face this problem on a regular basis, so I hope to find how other people solve this problem. On the other hand, I know that this question is quite big and maybe a little elaborate, so maybe I need to split it into several more specific questions. Maybe the answer to this problem is simple I'm over-complicating things, or even worse, my doubts about how to handle this situation arise because I really don't understand some basic design principle, like a captain on a ship using a spyglass in order to sight land but doesn't realize that his ship has been beached on solid ground that was close at the moment he draw his spyglass to look. Okay, enough cheap poetry (but it was hard to describe my feelings without it hehehe).

I apologize for the length of the question, and would very much appreciate anyone's help with this problem.

答:
There's a lot to say here.

Inventory's api looks like a value object (since it has no identity, on its own, I suppose that it belongs to a Player). If so, it should be immutable, returning a new instance each time you add or remove an Item.

Your Item class looks like a shared identifier, thus it should override equals and hashcode and (strictly speaking, in DDD term) it should not hold any reference to the icon since it's not useful for its own invariants. You should use a domain service that take the Item and provide the proper icon instead (probably wrapping a statically defined Hashtable). However, be pragmatic with this: if you measure actual performance issues with such (formally correct) approach, keep the field there.

The Slot, as it stands, cannot be considered a domain object, because it does not implement equality in a domain relevant way (it ignores the quantity). This is perfecly correct for a private class internally used by the Inventory, but should not be exposed to clients (as in the second Inventory's implementation of the first solution you proposed). This because the clients could compare for equality two Slots from two different players, obtaining unreliable results.

To get rid of most boilerplate code, I would code

a supporting functor interface like ItemQuantityChanger (below)

a "functional" immutable collection, say ItemsSet, with a metod of signature ItemsSet set(Item item, ItemQuantityChanger transformation) that iterates over a simple array for the item to change. Such method would always create a new ItemsSet to return, without the Item (if the trasformation returns zero), with a new Item if the item is not found (with the quantity returned by applying the transformation to zero) or simply with the previous item coupled with the result of the trasformation.

However, concretely, I would just use an ImmutableList.Builder, since the functional design described in 4 adds few value in this case. A single if, in a method, is not that huge smell.

```<code>public interface ItemQuantityChanger {
   /**
    * Accept the current quantity of an Item and return the new one.
    */
   int applyTo(int currentQuantity);
}
</code>```

OwnerDisplayName: Victor

Body:
There's a lot to say here.

Inventory's api looks like a value object (since it has no identity, on its own, I suppose that it belongs to a Player). If so, it should be immutable, returning a new instance each time you add or remove an Item.

Your Item class looks like a shared identifier, thus it should override equals and hashcode and (strictly speaking, in DDD term) it should not hold any reference to the icon since it's not useful for its own invariants. You should use a domain service that take the Item and provide the proper icon instead (probably wrapping a statically defined Hashtable). However, be pragmatic with this: if you measure actual performance issues with such (formally correct) approach, keep the field there.

The Slot, as it stands, cannot be considered a domain object, because it does not implement equality in a domain relevant way (it ignores the quantity). This is perfecly correct for a private class internally used by the Inventory, but should not be exposed to clients (as in the second Inventory's implementation of the first solution you proposed). This because the clients could compare for equality two Slots from two different players, obtaining unreliable results.

To get rid of most boilerplate code, I would code

a supporting functor interface like ItemQuantityChanger (below)

a "functional" immutable collection, say ItemsSet, with a metod of signature ItemsSet set(Item item, ItemQuantityChanger transformation) that iterates over a simple array for the item to change. Such method would always create a new ItemsSet to return, without the Item (if the trasformation returns zero), with a new Item if the item is not found (with the quantity returned by applying the transformation to zero) or simply with the previous item coupled with the result of the trasformation.

However, concretely, I would just use an ImmutableList.Builder, since the functional design described in 4 adds few value in this case. A single if, in a method, is not that huge smell.

public interface ItemQuantityChanger {
   /**
    * Accept the current quantity of an Item and return the new one.
    */
   int applyTo(int currentQuantity);
}

OwnerDisplayName: Giacomo Tesio


问:
Best practices for remotely resetting a mobile app's content/settings
What would be the best approach to resetting a mobile app's content/settings?

Let's say the app is cross platform: iOS/android using javascript/phonegap.  The current way this is designed is to have an admin area that can see mobile devices (users which have logged in).  The admin has the ability to flag a device for reset.

The app regularly polls the server to see if it should be reset.  Resetting will be rare, but the polling is not.  The polling doesn't cause any performance issues but it seems off to constantly be asking the server whether or not to blow up the app.

A push rather than a pull method would be nice but I'm not sure what this would look like.

Does anyone have any alternative design suggestions? Are there any drawbacks to the current design?

答:
Both Android and iOS support some form of push notifications. You should absolutely take advantage of those to deliver your reset messages rather than polling. Running radios unnecessarily can be a huge battery drain, and shifting the responsibility for delivering the reset message to the operating system will be a significant improvement.

For Android, you should be looking at Google Cloud Messaging for Android.

For iOS, you shoud be looking at Apple Push Notification Service (a.k.a. APNS).

If you aren't able or don't want to set up the necessary server side of the push notification equation, there are third parties like Urban Airship and OpenMarket that will be happy to do it for you (for a fee, naturally).

ContentLicense: CC BY-SA 4.0


问:
Best practices concerning exit in Delphi
A co-worker and myself are having a debate on whats best. Both concepts work and work well but is there a general consensus on not making a call to exit?

Whats better?

To call exit within a procedure to avoid doing the rest of the code as in ...

```<code>if Staging.Current = nil then exit

DoSomethingA(FileNameA);
DoSomethingB(FileNameB);
Staging.DeleteCurrent;
</code>```

or to not call exit and instead wrap it in a begin and end

```<code>if Staging.Current <> nil then
begin
  DoSomethingA(FileNameA);
  DoSomethingB(FileNameB);
  Staging.DeleteCurrent;
end;
</code>```

Both work. I prefer to use the exit statement since it results in fewer lines of code and looks cleaner to me, but is there any reason or any consensus among programmers to avoid using exit to leave a procedure?

答:
I would not consider it as good or bad.
Like all answers are showing, it might be hardly depending on the case.

Personally I like the simple "guard condition" with no return value,
but I would want to use it in complex functional structure or with class return values.

Maybe some best practices could be extracted from the answers above, and could lead to a simple checklist,
when its safe and useful to use "Exit", and also when to better avoid it.


问:
Transforming A Physical Algorithm into a Computerized One
I have realized that its possible to create algorithms that operate physically to solve problems much more efficiently than in a computer itself. Consider the following:

Finding the shortest path between 2 points in a connected graph. If one were to physically create the graph with the edge weights correspond to length of physical connectors and the nodes something corresponding ex: wooden balls and yarn both labeled, then it is possible to generate the graph from data in O(N) time and then determining the shortest path between 2 nodes would simply involve grabbing both those nodes and pulling them so a straight line forms between them (or multiple straight lines!) and the rest hanging. That straight line(s) would be the shortest path for obvious reasons.

How exactly does one take this physical method of solving the problem and implement it in a computer?

答:
How exactly does one take this physical method of solving the problem
  and implement it in a computer?

The sequential nature of digital computers prevents them from perfectly mimicking many physical operations, so there's not always a useful way to implement physical algorithms in software.

Spaghetti sort is a classic example of a physical operation that can't be implemented in software with the same performance. The idea is that you represent a set of numbers by cutting pieces of dry spaghetti to lengths that correspond to each number in the set. You then gather the spaghetti in your hand and lower the bundle against a surface so that the ends are all aligned. It's then a simple matter to remove pieces from the bundle one at a time, starting with the longest. Performance is O(n) because time to cut the spaghetti strands and time to remove all the strands from the bundle are both O(n).

The software version of the spaghetti sort is selection sort, which has O(n2) performance. The reason for this is that a sequential machine like a computer is unable to evaluate all the numbers at once. Instead, it has to run through the list of numbers looking for the largest, which is itself an O(n) operation, and it has to pick the largest number n times. In the real world, we can evaluate all the spaghetti strands at once, so the selection is O(1) instead of O(n).

So, the answer to your question is that it's not always possible to convert a physical method into software and while preserving the advantages of the physical method.


问:
How can I cope with every increasing/changing number of frameworks?
I started coding with php, mysql, html, and javascript back in 2002 and heck that is all you basically needed to create any type of website. Over the years I picked up other languages, but what turned me off were all of the frameworks and JQuery that was popping up every few months and clients (if freelancing) or employers expected you to be an expert on some crap a geek released recently.

Because of this I got out of programming since I don't know if I can constantly throw away all of my previous knowledge and replace it with some new hip fad that does the exact same thing but just uses different function names. I miss knowing the core knowledge of PHP and being able to code from scratch and I'm afraid the skill of mastering a technology to completion is obsolescent.

Is it right to feel this way, and can any of us feel secure about our programming career in the future?

答:
You overestimate the importance of frameworks.

Yes, there are trillions of frameworks, often doing more or less the same thing. My typical solution is to ignore them, until I have a big incentive to learn one of them, or until I notice that one of them is praised repeatedly by many people for a long time.

For example, JQuery is too important to be ignored. Too many people use it, it survived a few years, so I gave it my attention and realized that it really it cool. To give you an idea: You can do in one line of JQuery what you do in 10 lines of JavaScript and you don't have to worry about the cross-browser compatibility.

But the essence of programming is somewhere else.

It is not about learning JQuery or some other library. It is about having skills that would allow you to design a new cool library, or even a new programming language. I am not saying that you should be doing any of this; just that when you become good, you will have the ability to do it. Then when you look at a new library, or even a new programming language, it will only take an hour or two of exploration, and you will say: "Yeah, I understand the problem the author was trying to solve, I see why he chose this solution, and it will obviously have these advantages and disadvantages." It could take 10 years of learning to get there, assuming you focus on learning the important things.

How to learn programming?

Starting with "php, mysql, html, and javascript" is one of the worst possible choices. But unfortunately, many people do it. And then I assume many of them feel as frustrated as you do. I wish there was a way to tell all people on this planet to do it some other way.

Why is it a bad choice? First, you have to learn many things at the same time. Learning is easy if you divide the knowledge into small pieces, learn them gradually, practice each of them separately, then put it together. But with web development you try to learn databases, markup language, and two programming languages at the same time. (And then there are dozen frameworks out there.) It's like trying to swallow the whole elephant, instead of just having a steak. Second, PHP is a horribly designed programming language; worst of those which are used frequently.

My advice: Forget PHP completely and get some decent computer science education. Find out what universities teach, and then find some free videos on the internet. Become comfortable using pseudocode; it helps you to forget the details and focus on the essence. You can translate the pseudocode to any specific programming language later. (Knowing how to translate the pseudocode to a given language = understanding the language. Writing elegant pseudocode = understanding programming.)

By the way, JavaScript is a decent language. Not perfect, but one of the best out there. I am speaking about JavaScript itself (how to use variables, functions, objects, prototypes), not about the HTML objects in browser. Think about JavaScript as great language mostly used for a dirty work by people who don't understand it. The beauty of the language is that it allowed creating JQuery, which almost feels like another programming language, but in fact it only shows what JavaScript is capable of when used by people who really get it.

A more down-to-earth advice would be to learn Python. At a Udacity online course. Give it two weekends, forget all you know and just follow the lessons, and then see the difference. (Part of the difference is Python versus PHP, but a greater part is having things explained properly, as opposed to reading an average online tutorial.)


问:
Using one repository for the foundation of another
I have an existing website theme that I have built. I've been using github to maintain this theme, let's call it dragon. We are changing the theme entirely but we're using the existing theme as a foundation. Should I create a new github repository for the new theme? Or should I just continue pushing to the dragon repo?

If I do create a new repo should I use clone dragon and use that as the base for the new repo?

答:
Firstly, can you simply library-ize your old repo and freeze or nearly freeze work on it?  This factorization may work much better and help defend against spaghetti code in the first place.

If not you want the same repo.  You will want the history of all the stuff you hardly remember writing right underneath you, so you can do things like git blame when you can't remember what a quirky line of code is doing there.  Anyway don't simply copy files; all that's doing is 1) copying which is already wrong and 2) throwing out history that you won't need any less than you do now.

That leaves the question what to do with the old repo?  If it has a ton of valuable meta-data (tags, branches like "production" that need to be preserved without interfering with new repo), then simply back it up as an old repo.  This is somewhat meta-version control but reasonable to do once per repo every several years without it becoming unmaintainable.

If I do create a new repo should I use clone dragon and use that as the base for the new repo?

Be careful - there is going to be the .git folder as well as many .gitattributes files.  I am unaware of other metadata git adds.


答:
If you're creating a completely new theme, and only using the dragon repo to save yourself some typing then I would create a completely new repo for the new theme. Just copy the files, delete the .git directory and then git init and push to github as a brand new repo.

If, on the other hand, you're creating a theme that is in some way derivative of the dragon theme, or think that elements of what you develop for the new theme might be useful to the original dragon theme then you should fork the github repo and develop the new theme on that fork.

Title: Using one repository for the foundation of another

Body:
I have an existing website theme that I have built. I've been using github to maintain this theme, let's call it dragon. We are changing the theme entirely but we're using the existing theme as a foundation. Should I create a new github repository for the new theme? Or should I just continue pushing to the dragon repo?

If I do create a new repo should I use clone dragon and use that as the base for the new repo?


答:
As far as I can tell, your question boils down to (in the context of your example):

What kind of interface should Inventory have?

How should Inventory track its Item collection?

What kind of interface should Inventory have?

Inventory is an abstraction that simplifies how the Player class deals with its items, so the interface should be defined so that Player knows nothing about the implementation of that collection. This allows you to completely change how Inventory tracks items - maybe you want to start tracking total capacity by Item weight instead of size, etc - without requiring any changes in the Player code. Besides that, managing the collection of Items is the responsibility of Inventory, so the logic to do so doesn't belong anywhere else.

Just a note: max capacity doesn't seem to belong where you described it. Ideally your Inventory would have a max capacity, say 100, and different Items would contribue a certain value to that capacity; for example, a health potion would contribute 5 units, a pair of boots would contribute 20 units, etc.

How should Inventory track its Item collection?

A List is preferable if you want to hold multiple copies of the same item, and since in this case you want only distinct items, use a lookup. Hashtable is synchronized, but naively (see one of the comments to this SO question), so HashMap would probably serve better. Of course since we should always program to interfaces rather than implementations, it would be:

```<code>Map<Item, Integer> items = new HashMap<Item, Integer>();
</code>```

Another note: you don't generally need to specify initial collection capacity unless you're optimizing, and in any case, Hashtable's initial capacity is 11, and HashMap's is 16.

To get a better handle on design principles, read up on SOLID principles, and if you want to go in-depth in all aspects of software development, buy a copy of Code Complete, and read it. :-)

Title: A design decision in composition or aggregation

Body:
I've recently had doubts about some design decisions that I frequently make, so this time I decided to take some time and try to analyze it to find the best solution. I will describe a simple scenario where the design decision can be easily understood. :)

Suppose we are developing a game in Java where players can have any number of many different types of items.

```<code>/** Class that represent an item type existing in the game */
// you may prefer to call this ItemType,
// but for me appending the word "Type" is not necessary
class Item {
    private String descrip;
    private Image icon;
}
</code>```

In this situation I need to keep track of how many of each item the player has in his bag, so I keep a collection of them, in each element of which I have item type and quantity. Additionally one can think of other attributes that belong to that relation (perhaps a max capacity), but the question is: how do I model this scenario in general but with a practical implementation in Java? Here are two approaches I've come up with:

Using a List

```<code>class Slot {
    private Item item;
    private int quantity;

    /** Auto generated */
    public int hashCode()
    {
        int hash = 7;
        hash = 13 * hash + (this.item != null ? this.item.hashCode() : 0);
        return hash;
    }

    /** This method is also auto generated and just compares the Item,
        independent of quantity */
    public boolean equals(Object object)
    {
        if (!(object instanceof Slot))
        {
            return false;
        }
        Slot other = (Slot) object;
        if ((this.item == null && other.item != null)
             || (this.item != null && !this.item.equals(other.item)))
        {
            return false;
        }

        return true;
    }
}
</code>```

The above class relates one item with a quantity, and a collection of Slots is the primary attribute of the Inventory class. The disadvantages of this appear as soon I design the Inventory interface to not expose Slot to the client (making Slot private or hiding it in some other way): in creating a simple interface but providing access to all the standard collection methods. In my humble opinion there is nothing wrong with this:

```<code>/** Class that represent the bag that holds the player's items */
class Inventory {
   // this collection holds only one element for each type of item
   private ArrayList<Slot> slots;

    public Inventory()
    {
        slots = new ArrayList<Slot>(10);
    }

    public void add(Item item, int quantity)
    {
        Slot slot = new Slot(item, quantity);
        // if we don't already have a Slot for the added Item, add it
        if (!slots.contains(slot))
        {
            slots.addElement(slot);
        }
        // if we already have a Slot for the added Item, increase the quantity
        else
        {
            Slot _slot = slots.elementAt(slots.indexOf(slot));
            _slot.addQuantity(quantity);
        }
    }

    public void subtract(Item item, int quantity)
    {
        Slot slot = new Slot(item, 0);
        int index = slots.indexOf(slot);

        // only if we actually have this item
        if (index != -1)
        {
            Slot _slot = (Slot) slots.elementAt(index);
            _slot.quantity -= quantity;

            // if we have fewer of the Item than the number to remove,
            // remove the slot from the collection
            if (_slot.quantity <= 0)
            {
                slots.removeElementAt(index);
            }
        }
    }

    public void remove(Item item)
    {
        Slot slot = new Slot(item,0);
        slots.removeElement(slot);
    }

    public boolean hasItem(Item item)
    {
        Slot slot = new Slot(item,0);
        return slots.contains(slot);
    }
}
</code>```

As you see, we have to jump through some hoops to implement certain collection methods: in hasItem we have to create a Slot element just for that operation. In the add and subtract methods, we have to create the Slot object just to check if it's there.
I wonder if this really necessary. I suppose that it is if we desire to provide an interface to the standard collection methods. Perhaps we can move all this logic to another class (for example: Slots), exposing a cleaner interface that lets us search by item without the need of creating a Slot, but we are just moving the same problem to another class. We will face the same problem there, besides the fact that Inventory is basically a set of Slots, we're really just creating another class to be exactly the same thing, which doesn't make a lot of sense to me.

Would it be more correct to change the interface of this class to work directly with Slot class instead? This implies moving from composition (having Slots created within Inventory) to an aggregation (having Slot creation outside of Inventory). The result might look like:

```<code>/** Class that represent the bag that holds the player's items */
class Inventory {
   private ArrayList<Slot> slots;

    public Inventory()
    {
        slots = new ArrayList<Slot>(10);
    }

    public void add(Slot slot)
    {
        if (!slots.contains(slot))
        {
            slots.addElement(slot);
        }
        else
        {
            Slot _slot = slots.elementAt(slots.indexOf(slot));
            _slot.addQuantity(slot.getQuantity());
        }
    }

    public void subtract(Slot slot, int quantity) // how would the client get the Slot?
    {
        int index = slots.indexOf(slot);

        // only if we actually have this item
        if (index != -1)
        {
            Slot _slot = (Slot) slots.elementAt(index);
            _slot.quantity -= quantity;

            // if we have fewer of the Item than the number to remove,
            // remove the slot from the collection
            if (_slot.quantity <= 0)
            {
                slots.removeElementAt(index);
            }
        }
    }

    public void remove(Slot slot) // again, how would the client get the Slot?
    {
        slots.removeElement(slot);
    }

    // Hard to change a parameter type here. This strongly suggest there is
    // a flaw in the design. I only keep this here to communicate the observation
    public boolean hasItem(Item item)
    {
        Slot slot = new Slot(item, 0); // here we have no choice but to create it
        return slots.contains(slot);
    }
}
</code>```

But again, is this convenient? I don't often put this approach into practice, so I'm not sure.

Using a lookup

Another approach is to use something like a Hashtable with Item objects as keys quantities as values, so only quantity is associated with Items, without the need for a Slot class. An Inventory implementation using Hashtable might look like:

```<code>public class Inventory
{
    private Hashtable items;

    public Inventory()
    {
        items = new Hashtable(10);
    }

    public void add(Item item, int amount)
    {
        int stock = amount;
        if (items.containsKey(item))
        {
            stock += ((Integer) items.get(item)).intValue();
        }
        items.put(item, new Integer(stock));
    }

    public void subtract(Item item, int amount)
    {
        if (items.containsKey(item))
        {
            int stock = ((Integer) items.get(item)).intValue();
            stock -= amount;
            if (stock > 0)
            {
                items.put(item, new Integer(stock));
            }
            else
            {
                items.remove(item);
            }
        }
    }

    public void remove(Item item)
    {
        this.items.remove(item);
    }

    public boolean hasItem(Item item)
    {
        return this.items.containsKey(item);
    }
}
</code>```

To me this seems much better than using a List because there is no need of the Slot class, and all interactions with the Item collection are much simpler, but I'm not sure if I'm right.

The same type of problem is also evident in this scenario:
Suppose that we are implementing an order application for a pizza shop; every order consists of types of pizzas and quantities.

```<code>/** Type of pizza */
class Pizza {
    private String descrip;
    private Image icon;
}

/** Customer request for pizza */
class Request {
    // for each type of pizza we have to keep a count of how many the customer ordered
}

/** A pizza order */
class Order {
    private Pizza pizza;
    private int   amount;
    privete BigDecimal price;
}
</code>```

Knowing how to solve the first problem, I have a pattern to use for this similar situation; so the question is, what solution is best?

I try to convince myself that I'm not the only person with this concern, that ordinary people like me face this problem on a regular basis, so I hope to find how other people solve this problem. On the other hand, I know that this question is quite big and maybe a little elaborate, so maybe I need to split it into several more specific questions. Maybe the answer to this problem is simple I'm over-complicating things, or even worse, my doubts about how to handle this situation arise because I really don't understand some basic design principle, like a captain on a ship using a spyglass in order to sight land but doesn't realize that his ship has been beached on solid ground that was close at the moment he draw his spyglass to look. Okay, enough cheap poetry (but it was hard to describe my feelings without it hehehe).

I apologize for the length of the question, and would very much appreciate anyone's help with this problem.

Body:
As far as I can tell, your question boils down to (in the context of your example):

What kind of interface should Inventory have?

How should Inventory track its Item collection?

What kind of interface should Inventory have?

Inventory is an abstraction that simplifies how the Player class deals with its items, so the interface should be defined so that Player knows nothing about the implementation of that collection. This allows you to completely change how Inventory tracks items - maybe you want to start tracking total capacity by Item weight instead of size, etc - without requiring any changes in the Player code. Besides that, managing the collection of Items is the responsibility of Inventory, so the logic to do so doesn't belong anywhere else.

Just a note: max capacity doesn't seem to belong where you described it. Ideally your Inventory would have a max capacity, say 100, and different Items would contribue a certain value to that capacity; for example, a health potion would contribute 5 units, a pair of boots would contribute 20 units, etc.

How should Inventory track its Item collection?

A List is preferable if you want to hold multiple copies of the same item, and since in this case you want only distinct items, use a lookup. Hashtable is synchronized, but naively (see one of the comments to this SO question), so HashMap would probably serve better. Of course since we should always program to interfaces rather than implementations, it would be:

Map<Item, Integer> items = new HashMap<Item, Integer>();

Another note: you don't generally need to specify initial collection capacity unless you're optimizing, and in any case, Hashtable's initial capacity is 11, and HashMap's is 16.

To get a better handle on design principles, read up on SOLID principles, and if you want to go in-depth in all aspects of software development, buy a copy of Code Complete, and read it. :-)


问:
Do system background services affect languages benchmarking?
Today I was looking at some blogs on Ruby and Python. A Python loyalist wrote a few lines of code with a loop to show how Python is faster than Ruby, with a similar code. I also found a blog of a Ruby disciple who says that it is wrong and he too submitted a code sample and benchmarking results.

I am wondering whether background programs or background processes may sometime hinder the results and we may not get exact benchmarking scenario.

Please correct me if I am wrong.

答:
It's possible.

But if that's the case, running the benchmark again would almost certainly produce different results.  That's why benchmarks are always run multiple times, to make sure that there are no background processes that are skewing the results.

ContentLicense: CC BY-SA 2.5


问:
How does Javascript code become asynchronous when using callbacks?
I've been doing a lot of reading online trying to figure out how to write asynchronous JavaScript code. One of the techniques that has come up a lot in my research is to use callbacks. While I understand the process of how to write and execute a callback function, I'm confused why callbacks seem to automagically make the JavaScript execution asynchronous. So, my question is: how does adding in callback functions to my JavaScript code make said code automagically async?</p>

答:
The secret of the "magic" is that the events that you are assigning the callbacks to are asynchronous.  They're implemented "under the hood" to take care of whatever they're doing (such as retrieving something from a remote server) in the background, outside of the JS sandbox.  And then once they're done with their work, they give the JS engine a message to call an event.  When the JS engine is finished with whatever it's currently doing, it will call any events that are queued up (or wait for a new message) and then your callback is "magically" invoked asynchronously!

(NOTE: This is a very high-level, conceptual overview of the topic that doesn't go into details, because different JS engines are going to implement things in different ways.  But this is the general idea of how it works.)


问:
Factory Method: does the Product have to be a different class than the Creator?
I want to build three sites in PHP. I'm doing this as slowly, thoughtfully and carefully as I can, to learn as much about things like OOP and software architecture as possible.

From past experience I already know there will be a time when I will be glad to have logging functionality. I probably want to have different types of logs, by which I mean that in a .ini file, I want to be able to specify if logging should go to a text file (perhaps a tab-delimited or CSV file), a database table, or smoke signals. I'd have (let's say) a Logger class, which would define, for example, an AddEntry() method. For each log type, I'd make a subclass that knows how to log to CSV file, write to a database or kindle a fire, respectively.

Since I know I will want to have an instance of a subclass, but I won't know which subclass to instantiate until runtime, I figured I'd use the Factory Method pattern. However, When I look at its Wikipedia article I'm noticing that the Creator and ConcreteCreator have a different type than the Product, if I'm reading the UML correctly. My question comes down to this:

I want to have the factory method as a static method of the Logger base class itself. If I do that, am I setting myself up for a trap that I'm not seeing yet? Is there a reason why the Creator and ConcreteCreator should be of a different type than the Product?

答:
They should be of different types because one is a Factory, the other is the type of object that the Factory produces.

In your case you can have a LoggerFactory and distinct subclasses of the Logger base class.  The factory class will generate one of the subclasses of Logger based on the arguments given

Let me attempt to clarify: from the wikipedia page: "Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns"

In essence, you're using the factory object to remove alot of the bootstrapping code from the constructor of the type of objects that the factory will create.

Having the factory and it's constructed objects share the same class does not solve the separation of concerns issue since the code would be in the same class.

OwnerDisplayName: Marcos Savoury


问:
How can one measure contributions to a project?
Has anyone ever come across this problem?
When you have a team of developers working on a project, how can you measure their contributions to said project? Is there a "formal" way of doing it? Number of commits? Number of bug fixes? Lines committed? Or maybe on a ticket basis?

I'm trying to think of a workflow where a group of developers can work seamlessly interchanging tasks and at the end of the month, getting paid for they contributions (or merit if you will).

I hope this question is not entirely out of place here, if it is, feel free to close it.

答:
There's no way to accurately do this. For example, who contributes more: someone who commits 1000 lines of code in a month, or someone who spent most of his time thinking really hard, and then committing 100 lines of code that replace the 1000 lines of code? Or how about somebody that goofed off most of the month, then found those same 100 lines of code in a blog?

Who contributes more: someone who generated 100 image assets, or someone who spent weeks thinking about usability, and eventually checked in just a half dozen wireframes for a highly usable application?

In other words, how do you measure the amount of intangible work that most high performers do on a regular basis?


答:
It doesn't have to be, no.

One example I can think of is in the .NET Framework in System.Net.WebRequest.Create(). It will return an object of a class derived from WebRequest, based on the protocol part of the URL passed to it.

However, there are problems with this.

You cannot inject a factory, if it's a static method of the type being generated. (Well, in .NET, you can inject it as a Func<WebRequest>, but this still isn't as ideal as injecting a factory object.)

It's also not as neat, when you come to extend the factory with your own class. If there were a standard WebClientFactory class, with an interface exposing a Create method, I would be able to wrap that up in a CustomWebClientFactory, using the same interface and the calling code would never know the difference.

These are fairly trivial concerns, but your question is a fairly trivial one. Turn it around and ask yourself this: Why shouldn't you use a Factory class for the Factory method?

Title: Factory Method: does the Product have to be a different class than the Creator?

Body:
I want to build three sites in PHP. I'm doing this as slowly, thoughtfully and carefully as I can, to learn as much about things like OOP and software architecture as possible.

From past experience I already know there will be a time when I will be glad to have logging functionality. I probably want to have different types of logs, by which I mean that in a .ini file, I want to be able to specify if logging should go to a text file (perhaps a tab-delimited or CSV file), a database table, or smoke signals. I'd have (let's say) a Logger class, which would define, for example, an AddEntry() method. For each log type, I'd make a subclass that knows how to log to CSV file, write to a database or kindle a fire, respectively.

Since I know I will want to have an instance of a subclass, but I won't know which subclass to instantiate until runtime, I figured I'd use the Factory Method pattern. However, When I look at its Wikipedia article I'm noticing that the Creator and ConcreteCreator have a different type than the Product, if I'm reading the UML correctly. My question comes down to this:

I want to have the factory method as a static method of the Logger base class itself. If I do that, am I setting myself up for a trap that I'm not seeing yet? Is there a reason why the Creator and ConcreteCreator should be of a different type than the Product?


问:
What does Microsoft Public License (Ms-PL) clause 3 section (A) actually limit?
I've been looking at the Ms-PL license that ASP.NET MVC and DotNetOpenAuth are published under and 3A says this:

```<code>3 Conditions and Limitations

(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
</code>```

Does this mean that I cannot name my project ASP.NET MVC DotNetOpenAuth Sample Project and publish it if I use these two technologies or does it just mean that I cannot use the author's name to promote this project?

答:
Trademarks are a business thing, so a personal name isn't a trademark unless that person uses it as such in a business or similar enterprise.  Such things as Microsoft Windows and ASP.NET are trademarks.  I could trademark "David Thornley" software if I were to write and distribute it (remember Peter Norton and the Norton Utilities?), but since I'm not actually in that business my name isn't a trademark.

Also, pay attention to the wording.  The license doesn't grant any rights to a trademark, but it doesn't restrict any ability you already have.  You can't call your project Microsoft software, but you can advertise that it runs on Microsoft Windows.  The guiding rule (at least in the US) is if you're trying to create any confusion about who produces the software, or if a reasonable person could be confused.  You'd probably be safe calling it "Project Gligoran, using ASP.NET and running on Microsoft Windows", but if you're worried consult a trademark lawyer.

Also, in the US, trademarks work on a "protect it or lose it" basis.  If you use a trademark improperly, and the owner of the trademark finds out about it, the owner is legally required to take some sort of action against you or risk losing the trademark.


答:
It doesn't. Just taking a callback or passing a callback doesn't mean it's asynchronous.

For example, the .forEach function takes a callback but is synchronous.

```<code>var available = false;
[1,2,3].forEach( function(){
    available = true;
});
//code here runs after the whole .forEach has run,
//so available === true here
</code>```

The setTimeout takes a callback too and is asynchronous.

```<code>function myFunction( fn ) {
    setTimeout( function() {
        fn(1,2,3);
    }, 0 );
}

var available = false;
myFunction( function() {
    available = true;
});
//available is never true here
</code>```

Hooking to any asynchronous event in Javascript always requires a callback but that doesn't
mean calling functions or passing them around is always asynchronous.

Title: How does Javascript code become asynchronous when using callbacks?

Body: I've been doing a lot of reading online trying to figure out how to write asynchronous JavaScript code. One of the techniques that has come up a lot in my research is to use callbacks. While I understand the process of how to write and execute a callback function, I'm confused why callbacks seem to automagically make the JavaScript execution asynchronous. So, my question is: how does adding in callback functions to my JavaScript code make said code automagically async?</p>

Body:
It doesn't. Just taking a callback or passing a callback doesn't mean it's asynchronous.

For example, the .forEach function takes a callback but is synchronous.

var available = false;
[1,2,3].forEach( function(){
    available = true;
});
//code here runs after the whole .forEach has run,
//so available === true here

The setTimeout takes a callback too and is asynchronous.

function myFunction( fn ) {
    setTimeout( function() {
        fn(1,2,3);
    }, 0 );
}

var available = false;
myFunction( function() {
    available = true;
});
//available is never true here

Hooking to any asynchronous event in Javascript always requires a callback but that doesn't
mean calling functions or passing them around is always asynchronous.


问:
Function that modifies an argument, should I return the modified object?
We have a function that modifies a JS object, by adding some custom properties to it. The function doesn't return antyhing

```<code>addTransaction: function (obj) {
     obj.transactionId = this.getTransactionId;
     obj.id = this.recordId;
},
</code>```

Somebody said they preferred that addTransaction return the obj.

Here's what I thought

If I don't return anything (and document that the object is going to be modified), it's kind of clear that the object is going to be modified, as if the name were addTransactionToObj

If I do want to add a return value, I shouldn't modify the incoming object, I should clone the given object, add my properties to the clone and return the clone.

Having a return value that just returns one of the (modified) parameter just sounds wrong

Does anybody have a preference in this matter?

答:
If I don't return anything, it's kind of clear that the object is going to be modified

Not necessarily.  It could be a method that causes side effects, like a logger.

If I do want to add a return value, I shouldn't modify the incoming object, I should clone the given object, add my properties to the clone and return the clone.

In general, I would agree with that.  But returning the original object is a valid technique, especially if you're building a Fluent Interface.

As Florian points out, a better approach might be to add the function to the object itself, as in DoSomethingToThis().


答: It allows you to do method chaining, which a lot of people feel improves readability.  It's a very common idiom in JavaScript, which means a lot of people expect it, especially if the rest of the code base is similar.  Your second point about cloning the object also has merit, if used to make your object immutable.  How beneficial that is depends on your specific application.

Title: Function that modifies an argument, should I return the modified object?

Body:
We have a function that modifies a JS object, by adding some custom properties to it. The function doesn't return antyhing

```<code>addTransaction: function (obj) {
     obj.transactionId = this.getTransactionId;
     obj.id = this.recordId;
},
</code>```

Somebody said they preferred that addTransaction return the obj.

Here's what I thought

If I don't return anything (and document that the object is going to be modified), it's kind of clear that the object is going to be modified, as if the name were addTransactionToObj

If I do want to add a return value, I shouldn't modify the incoming object, I should clone the given object, add my properties to the clone and return the clone.

Having a return value that just returns one of the (modified) parameter just sounds wrong

Does anybody have a preference in this matter?


答:
First of all, I think this function is strange... I mean that I expected the addTransaction to add a transaction to this, not the other way around. But maybe it's just me (edit: apparently not). If this is really what you want to do, then I suggest reading from "naming your function".

Secondly, I think that the main problem lies within the "add" part of "addTransaction". For me, it means that an object is going to be modified in order to have a "transaction".

Thirdly, there are multiple ways you can do that. You can:

return a copy, which means your original object is immutable

return the object to which the transaction is attached, so you're kinda following the fluent interface paradigm.

return nothing, the object is modified

There is no "best" way, just be consistent and KISS when choosing for a given application.

Naming your function

Robert C. Martin's in (Clean Code tips on naming functions) states that the smaller the scope the more precise the name of the function should be. I suggest to name it to  something along the lines of "attachTransactionIdAndRecordIdToObject" if you want to keep both setters in the same function. Again, whether you return the object itself or not is your choice.


答:
I don't think you can do this, at least in the sense you suggest. Bryan's answer, and several answers in the question linked by gnat discuss several intangible (perhaps we should call them "immeasurable" in this context) productive activities.

Specifically, this:

I'm trying to think of a workflow where a group of developers can work seamlessly interchanging tasks

seems like it will set up a perverse incentive for the developers not to focus their efforts where they're most productive, but instead to pretend to be interchangeable resource units to fit your measurement scheme.

One approach would be to simply ask everyone to estimate everyone else's work, and average it into some kind of rough productivity consensus. This might just lead to (some) people talking up the complexity of their bugs or features around the water cooler though.

A more manageable way would be to just use peer reviews once or twice a year, where team members give ratings for each others' relative productivity.

because this isn't done every week, or per fixed number of stories, it's harder to game

because everyone on the team is already equipped with a large squishy computer  which is carefully calibrated to assess group relationships, you can use these as a proxy

everyone knows the value of favours done or received, even if they're hard to quantify

if team members review each others' code, they'll have a feeling for who is storing up the most technical debt for the future

this allows developers to play to their strengths (ignoring personal development and team-building in this context, this should be the most productive)

Title: How can one measure contributions to a project?

Body:
Has anyone ever come across this problem?
When you have a team of developers working on a project, how can you measure their contributions to said project? Is there a "formal" way of doing it? Number of commits? Number of bug fixes? Lines committed? Or maybe on a ticket basis?

I'm trying to think of a workflow where a group of developers can work seamlessly interchanging tasks and at the end of the month, getting paid for they contributions (or merit if you will).

I hope this question is not entirely out of place here, if it is, feel free to close it.


答:
I came up with something trying to incorporate all the suggestions. Make a class out of the object you're going to send with the AJAX request.

```<code>function MyAjaxParams() {
    this.obj = {};
}

/**
 * @param {MyDocument} doc
 */
MyAjaxParams.prototype.addTransaction = function(doc) {
     this.transactionId = doc.getTransactionId();
     this.id = this.getRecordId();
}

MyAjaxParams.prototype.getParamsObject = function() {
    return this.obj;
}

// Many other methods to insert all required AJAX parameters
</code>```

Then my existing code would do the following

```<code>MyDocument.prototype.save = function () {
    var ajaxParams = new MyAjaxParams();
    ajaxParams.addTransactionParams(this);
    ...
    Ext.Ajax.request.send({
      url: '/here/we/go',
      params: ajaxParams.getParamsObject()
    });
}
</code>```

Body:
I came up with something trying to incorporate all the suggestions. Make a class out of the object you're going to send with the AJAX request.

function MyAjaxParams() {
    this.obj = {};
}

/**
 * @param {MyDocument} doc
 */
MyAjaxParams.prototype.addTransaction = function(doc) {
     this.transactionId = doc.getTransactionId();
     this.id = this.getRecordId();
}

MyAjaxParams.prototype.getParamsObject = function() {
    return this.obj;
}

// Many other methods to insert all required AJAX parameters

Then my existing code would do the following

MyDocument.prototype.save = function () {
    var ajaxParams = new MyAjaxParams();
    ajaxParams.addTransactionParams(this);
    ...
    Ext.Ajax.request.send({
      url: '/here/we/go',
      params: ajaxParams.getParamsObject()
    });
}


问:
Implementing base-10 floating point division
I'm implementing floating-point arithmetic, for a micro-controller which does not support floating point numbers, in either hardware or software.
(Software being "written" in a sort of electrical diagram program.)
I've finished encoding/decoding from/to integers, adding, subtracting, and multiplication.
My "floats" are represented as C * 10^E, where:

C, the coefficient, is a 32-bit signed integer in the range 100000000-999999999, or 0.

(Nine digits of precision, plus the special case of zero.)

E, the exponent, is a 32-bit signed integer covering the whole 32-bit range.

(Yes, it's overkill.)

I chose round base-10 numbers to make the verification of the math easy.
My strategy for the multiplication was to split up the two numbers AaaBbbCcc and DddEeeFff into three pieces each (millions, thousands, and ones) and compute the multiplication as

```<code>(ABC * 10^Y) * (DEF * 10^Z) =
  ((AD * 10^12) +
   ((AE + BD) * 10^9) +
   ((AF + BE + CD) * 10^6) +
   ((BF + CE) * 10^3) +
   (CF * 10^0))
  * 10^Y+Z
</code>```

Each * and + representing a normal multiplication or addition, and 10^N being faked with me hard-coding in a 1000, 1000000, etc.
Also note that this neither recurses or loops, and any answer cannot recurse or loop.
I've got access to integer addition, subtraction, division, multiplication, modulo, cos/sin/tan/arccos/arcsin/arctan, absolute value, and square root.

Main Question:

I can/will eventually figure out how to do division with a similar approach of splitting the coefficients into smaller numbers which will be better for 32-bit division.
I haven't done my algebra in a long time, so multiplication took me about a day and a half.
Since I presume division to be more complicated conceptually, it would be super handy if somebody on SE could do the hard math for me.
So, how do I do this?

答:
Given the division:
AAABBBCCC / X
it can be rewritten to the form:
(AAA * 10^6 / X) + (BBB * 10^3 / X) + (CCC / X).

These algebraic formulae, plus or minus some division or multiplication by powers of 10, will get the answer.


问:
Should I use a CMS for a new large application with a lot of common features (login, profile edit, blog etc)?
I'm currently planning a new ASP.NET MVC3 project which will be quite bespoke. However, there will be a lot of common features (login, profile edit, blog etc).

Initially I was planning on building this all from scratch, however I'm tempted by CMS so that I'm not reinventing the wheel, and don't waste time building standard features which will need a lot of testing.

I've been looking into using Orchard Project CMS, and installed this the other night so that I could have a play around. The CMS seems great, however it seems restrictive in terms of wanting to add new sections.

I was hoping that the CMS would basically be an ASP.NET MVC3 solution, with login features etc, which I can then build on. However I feel bound to having to write "widgets" for my application.

I understand CMS's are great for simple blog sites etc, but would it seems too restrictive to be able to build a social network for example.

Is there such a thing as an open-source MVC3 solution with pre-built login functionality etc, which isn't bound by an interface? Or if I'm planning to build a large application, are CMS's the wrong path to take?

答:
CMS is for Content Management System. It is sensible not to reinvent the wheel and build around it, but don't think for a minute to build on top of it because you will be limiting yourself to its limitations. What you'll want to do is write mvc portions independent of it (they can sit on a subdomain) and then iframe those pages into the CMS. It'll look completely transparent but you get all of the flexibility of an independent app while still being able to hook into the CMS's apis.

As far as login and other common features, ASP.NET itself has a lot of simple providers which can be stood up with minimal effort


问:
How does a USB device whether know to draw 500mA, 1A or 2.1A from a computer USB port?
I'm having some issues with my Nexus 7 drawing just 500mA from a USB port able to supply 2.1A (test with my iPad). Details in this question. However, there is a comment posted "The Nexus obviously detects the 'data' pin connected, and assumes it is not permitted to draw more than 500mA (which is the proper USB spec)."

That got me thinking, how does a device really know how much it's allowed to draw from the USB port? It can't be just via wiring of the D+/D- pins because then you wouldn't be able to communicate over the USB port (eg. Sync'ing or transferring over the USB port). The iPhone and iPad clearly are able to draw higher power from the USB port even during a sync/data operation. So I was thinking, the power it might be officially dictated within the USB comm. protocol itself, perhaps some packet/header.

So, how does a USB device know whether to draw 500mA, 1A or 2.1A from a computer USB port?

Does the answer change if the USB port is on a "dumb" wall charger? Or is it a wild west where each device/charger does it's own thing for high current situations?

答:
Automatic Detection of USB Port vs Wall Adapter Power

When a device is connected to an actual USB port, the system  detects
  a USB host ID and can then set the battery charge  controller to a
  level at or below 500 mA to match the current  capacity available from
  most USB ports

Using a USB controller to detect and set the charger I/C for USB
  charging works well for devices that possess such capabilities.
  However, for low-cost products that do not contain a USB
  interface controller or do not have a requirement for data transfer,
  detecting the presence of a USB port versus a higher power wall
  adapter can be problematic.

The AAT3685 can solve this dilemma with the addition of a simple
  external circuit using just two resistors and a general purpose
  NPN bi-polar transistor.


答:
the minimum a port needs to provide is 100mA so all usb devices can assume that is available

if the device needs anything more than that it needs to negotiate it with the port, the standard 2.0 port can handle 500 mA

there is an exception with dedicated charging ports which don't have any electronics to negotiate the draw and are recognizable by a shorted D+ and D- line

Title: How does a USB device whether know to draw 500mA, 1A or 2.1A from a computer USB port?

Body:
I'm having some issues with my Nexus 7 drawing just 500mA from a USB port able to supply 2.1A (test with my iPad). Details in this question. However, there is a comment posted "The Nexus obviously detects the 'data' pin connected, and assumes it is not permitted to draw more than 500mA (which is the proper USB spec)."

That got me thinking, how does a device really know how much it's allowed to draw from the USB port? It can't be just via wiring of the D+/D- pins because then you wouldn't be able to communicate over the USB port (eg. Sync'ing or transferring over the USB port). The iPhone and iPad clearly are able to draw higher power from the USB port even during a sync/data operation. So I was thinking, the power it might be officially dictated within the USB comm. protocol itself, perhaps some packet/header.

So, how does a USB device know whether to draw 500mA, 1A or 2.1A from a computer USB port?

Does the answer change if the USB port is on a "dumb" wall charger? Or is it a wild west where each device/charger does it's own thing for high current situations?


问:
How do you unit test private methods?
I am working on a java project. I am new to  unit testing. What is the best way to unit test private methods in java classes?</p>

答:
You can test private methods easily if you put your unit tests in an inner class on the class you are testing. Using TestNG your unit tests must be public static inner classes annotated with @Test, like this:

```<code>@Test
public static class UserEditorTest {
    public void test_private_method() {
       assertEquals(new UserEditor().somePrivateMethod(), "success");
    }
}
</code>```

Since it's an inner class, the private method can be called.

My tests are run from maven and it automatically finds these test cases. If you just want to test one class you can do

```<code>$ mvn test -Dtest=*UserEditorTest
</code>```

Source: https://rogerkeays.com/how-to-unit-test-private-methods

Title: How do you unit test private methods?

Body:
You can test private methods easily if you put your unit tests in an inner class on the class you are testing. Using TestNG your unit tests must be public static inner classes annotated with @Test, like this:

@Test
public static class UserEditorTest {
    public void test_private_method() {
       assertEquals(new UserEditor().somePrivateMethod(), "success");
    }
}

Since it's an inner class, the private method can be called.

My tests are run from maven and it automatically finds these test cases. If you just want to test one class you can do

$ mvn test -Dtest=*UserEditorTest

Source: https://rogerkeays.com/how-to-unit-test-private-methods


问:
Path of Replication
I'm currently developing a replication system to keep data in-synch between an arbitrary number of servers.

Some of these servers exist in one cluster on one LAN. Others exist somewhere else in the world.

I'm wondering what are the pros/cons of different paths that we choose to flow replicated data on between servers?

In other words, what are the different strategies to load balance the replication process ?

答:
Paxos is an algorithm that can be used for active-active replication between multiple masters. In the (patented) version we use, it has been enhanced to work well in a WAN environment.

A nice feature is the entirely of failure conditions are contained within the algorithm, so the issues of data loss or packet loss are not a threat to data safety. The amount of data you can afford to lose can be zero. (Assuming the entire universe isn't blown up at once.)

OwnerDisplayName: geeko

Title: Path of Replication


问:
Android game loop in separate thread
I am about to port a game that was initially written for iOs and I am having some doubts how certain things should be done.

I have been looking many of the examples of the game loops for android, and almost everywhere the game loop is designed to run in separate thread and not in main UI thread which seems fine and logical to me.
However, my game scene is combination of OpenGL graphics and standard android views (buttons, labels, etc...) and by design, the primary game logic and OpenGL drawing would be done in separate thread and rest of the standard stuff would be done in main UI thread.

In many situations, I will need to call functions that should run in game thread from main UI thread and vice versa. As a very basic, simple example, when user performs touch (which is detected in UI thread) the event should propagated and be processed by the game thread.

Do you know some good mechanisms or patterns on how to such cross thread interaction?
Is there a simpler solution to a game loop, maybe by not running loop in a separate thread?

答:
If you run the loop in a separate thread you will need to keep it synchronized with everything else that will be going on. This should provide you with insight though: https://gamedev.stackexchange.com/questions/651/tips-for-writing-the-main-game-loop

I've not programmed on Android, but I have programmed in Java. If you want to see an example of my game loop you can get the code here: https://github.com/moorej/RetroPlexjava

Title: Android game loop in separate thread


问:
How to comply with the Java ASM License?
I am designing an open source Java library that I will likely release with an MIT license, and its sole dependency is the ASM dynamic bytecode injection library.

According to their license:

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

What does this mean, exactly? Does it mean that in all my Developer Guide (which will be a PDF that will be distributed in the same ZIP file as my JAR)? Or does it mean something else?

I guess I'm asking for an example of a correct way of honoring this stipulation in the license. Thanks in advance!

答:
That's basically the 3-clause BSD license.

It means exactly what it says.  If you redistribute the binary, you must reproduce the copyright notice, list of conditions and the disclaimer in your documentation.  In practice, this means you're going to be reproducing the license in its entirety in your Developer Guide, on its own page titled "License," and listed in the Table of Contents as "License."


问:
How meaningful is the Big-O time complexity of an algorithm?
Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).

Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.

Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.

Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.

Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?

答:
What's important isn't the value that O bounds but the rate of growth of the value that O bounds. This is where Calculus comes in.

If you take the derivative of log(n) for instance, you get 1/n as the rate of change. This means that the time taken by a log(n) algorithm grows as a rate of 1/n meaning that as you add more and more values to the set, you get a smaller value for f(1/n). The same hold true over n'= 1, n^c' where c is some constant = cn and c^n' = c^n(log(c)). Thus you have a much, much slower rate of growth for time taken for the lower orders than for the higher ones. Once you hit exponential, the rate of growth begins to grow at a rate greater than the base function.

Thus understanding Big O allows you to easily compare algorithms time per input even if the input is never 'infinite'. Incidentally, infinite in software development or CS often means "Arbitrarily Large" rather than the technical, mathematical infinity since computers in practice are finite devices.


答:
With small n Big O it is just about useless and it's the hidden constants or even actual implementation that will more likely be the deciding factor for which algorithm is better. This is why most sorting functions in standard libraries will switch to a faster insertion sort for those last 5 elements. The only way to figure out which one will be better is benchmarking with realistic data sets.

Big O is good for large data sets and discussing on how an algorithm will scale, it's better to have a O(n log n) algorithm than a O(n^2) when you expect the data to grow in the future, but if the O(n^2) works fine the way it is and the input sizes will likely remain constant, just make note that you can upgrade it but leave it as is, there are likely other things you need to worry about right now.

(Note all "large" and "smalls" in the previous paragraphs are meant to be taken relatively; small can be a few million and big can be a hundred it all depends on each specific case)

Often times there will be a trade-off between time and space: for example quicksort requires O(log n) extra memory while heapsort can use O(1) extra memory, however the hidden constants in heapsort makes it less attractive (there's also the stability issue which make mergesort more attractive if you don't mind payign the extra memory costs).

Another thing to consider is database indexes, these are additional tables that require log(n) time to update when a record is added, removed or modified, but lets lookups happen much faster (O(log n) instead of O(n)). deciding on whether to add one is a constant headache for most database admins: will I have enough lookups on the index compared to the amount of time I spend updating the index?

One last thing to keep in mind: the more efficient algorithms are nearly always more complicated than the naive straight-forward one (otherwise it would be the one you would have used from the start). This means a larger surface area for bugs and code that is harder to follow, both are non-trivial issues to deal with.

Title: How meaningful is the Big-O time complexity of an algorithm?

Body:
Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).

Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.

Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.

Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.

Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?


问:
Distributed Issue Tracking
Distributed issue tracking seems like a belting idea to me, but it has never really taken off in a big way. Is there a good reason for that?

I am aware of:

bugz everywhere

too complex to set up

too many requirements

reasonably successful, used by some large projects

fossil

tries to integrate too many things, and ends up being a slightly worse version of all of them - except maybe for the distributed issue tracking part, which is decent (probably best I have seen)

several other smaller projects

none of which have gained any traction

I am thinking about making my own, but before I begin, I would like to know why none of the others have taken off in a big way.

Anticipated issues: (I think they can all be overcome)

merging distributed issues as they are updated is complex, as is merging any code files

conversation continuity can be destroyed, as comments can come in at any time, perhaps not in the correct flow

expectation of central server with issues up-to-date

答:
I'm going to be real specific about actual products.  Some will probably like this and others perhaps not, but here goes:

I've used a bunch of tools over the years for issue, task and project tracking.  Microsoft Project, Trello and Jira have all had their place.

Now I use Pivotal Tracker.  I love it's sophistication yet simplicity of use and I really like the way that as other people edit and update tickets those changes get made and highlighted in your window too, so its far and away the best 'network' style of these tools that I've tried.

Not totally sure if that's what you mean by distributed, but there you go.

If it is, I would get used to and then look at the deficiencies of Pivotal Tracker (if any) for you before developing an alternative.

Title: Distributed Issue Tracking


问:
How to end my dependency on .NET?
I have been developing Windows GUI applications since many years and jumped into .NET in early 2005. .NET is a undoubtedly a remarkable platform and I am still using it, but with a variety of technologies out there, I don't want to remain dedicated to this camp. I want to learn new languages with which I can develop GUI applications.

I am learning Ruby and just installed Python. I read about WxRuby, a framework for developing Windows GUI app. in Ruby. I am searching for a similar framework for Python.

Apart from that I want to know which language is more suitable for a production-level GUI app. I doubt that Ruby is more focused on Web platform with it's glamor, Ruby on Rails.

I know that I may not get those rich .NET classes and that impressive Visual Studio IDE, but still I want to follow the road less traveled. I don't want to go with IronPython and IronRuby, however sometime later, I may dip hands to explore them.

答:
I'm not sure if your question is limited to determining if Ruby or Python is better or if you're asking which other languages you might want to learn to develop Windows GUI apps in general. I'm assuming the latter.

There are also Java, Delphi, or native Win32 programming. Any of those are suitable for developing GUI apps on Windows. Native Win32 code can (must?) still be written through Visual Studio, but there's no .NET dependency.

Title: How to end my dependency on .NET?


问:
Using one repository for the foundation of another
I have an existing website theme that I have built. I've been using github to maintain this theme, let's call it dragon. We are changing the theme entirely but we're using the existing theme as a foundation. Should I create a new github repository for the new theme? Or should I just continue pushing to the dragon repo?

If I do create a new repo should I use clone dragon and use that as the base for the new repo?

答:
I would:

Create a new repo.

Copy the files in as needed.

This will help cleanup the old cruft that accumulates.  You won't be doing them one by one, e.g. you might copy the entire images folder in one operation.  But just like an oil change, you should do it periodically anyway and any such move operation is an ideal opportunity for such a clean.  If you're intimidated by the number of files and not sure what many of them do, that's even more impetus for it :)


答:
Very meaningful in my experience.
At the root of many performance problems I often find these causes...

Failure to consider the range of n for which the algorithm will be used.

Failure to consider time complexity of the algorithm used.

Failure to consider memory requirements of the alogrithm for the likely range of n.

Failure to consider latency differences between RAM, Disk, Network, etc.

(and not least) Failure to test with realistic sized data.

This comes up in routine places in development of business software. Such as...

Why does my SQL query run so slowly?

Why does my HTML+CSS+js UI run so slowly? I'm just doing a few jquery operations on the DOM?

Why is my .Net  app running so slowly? I'm just using datasets to massage some data and put it in a grid.

In most cases where n is known to be small it's not worth spending a lot of time on complexity.

Thinking about the expected range of n and evaluating complexity is a proven way to know when it is worthwhile to question algorithms and architectures. I use this primarily as an intuitive tool for 'in my head' or 'back of cocktail napkin' level calculation. It saves me a lot of time.

It's an essential tool for software design.


问:
Why aren't macros included in most modern programming languages?
I know that they are implemented extremely unsafely in C/C++. Can't they be implemented in a safer way? Are the disadvantages of macros really bad enough to outweigh the massive power they provide?</p>

答:
Lest start by noting that MACROs in C/C++ are very limited, error prone, and not really that useful.

MACROs as implemented in say LISP, or z/OS assembler language can be reliable and incredibly useful.

But because of the abuse of the limited functionality in C they have a gathered a bad reputation. So nobody implements macros any more, instead you get things like Templates which do some of the simple stuff macros used to do and things like Java's annotations which do some of the more complex stuff macro's used to do.


答:
I would say big-O analysis is not something you rely on, it's rather a kind of performance warnings.

If something is O(2^n), it doesn't mean it's slow, but it does mean that you should pay some attention to it.

If you optimise some algorithm, big-O analysis may show you which places should be measured first, because they are more likely to be bottleneck.