问:
Mercurial Branching from a branch
We are in a situation where the customer has requested an urgent deployment of the current features we are working on.
These features are being developed in a mercurial branch named 'sprint 1' for arguments sake.

We also need to start working on the next sprint whilst the customer undertakes UAT. If they report any issues, we need to fix them on the 'sprint 1' branch and eventually redeploy them. Meanwhile, the rest of the team is supposed to be working on the 'sprint 2' features.

Would I just start a 'sprint 2' branch from the tip of the 'sprint 1' branch as soon as we go in to UAT?

答:
Functionally mercurial will love as many heads to your repo as you can give it, even without using unique branch names -- you can use multiple anonymous heads for fun and profit at times.

Now, from a code and data management perspective you have to take a few things into consideration. Functionally you really don't want a lot of divergence between the sprints.

There is no reason not to just branch off of the sprint branch.

Title: Mercurial Branching from a branch


问:
One commit in two branches: what happened?
I work on a project using maven and svn.

Today after a svn update, the maven build was failing on the svn trunk. When I looked in the svn logs, I saw something strange: a commit affecting two branches. Few files were commited on the foo branch - the expected result of this commit - and one were commited on the trunk (the reason of the maven fail), all of this in one commit.

This commit was made on Eclipse using a SVN plugin (I don't know which one). Merges between this two branches had already been made few days ago, and the developer had an up to date working copy.

This was fixed easily by reverting the delictuous file, but I don't understand what happend and I would like to understand it. Is this the result of an unfixed conflict, or an auto-commited unstaged file from a switched branch ? On svn, isn't a working copy "linked" to one branch ?

答:
Just share some interesting thing about this.

I personally run into this myself before, and at the time I believed I committed only once for one branch, but it changed files in two branches.

I spent quite a long time figured out why, I'm having a habit to reuse same local folder for different branches, by keep using svn switch. But I always switch on the root level of the folder, and I never switch individual file or directory like @Brandon mentioned in the comment.

I figured out why as again when I tried to switch that folder to a different branch, the switch was faster and it changed part of the folders rather than all of them, I noticed the difference and stopped the switch, and then check on sub folders and found some of those pointing to new one and some pointing to old one. And also it didn't raise any problem. If I do the switch again it would switch the rest of it.

My best guess was at the time I switch there might be a network blip stopped the process but I didn't notice it's not done. Which lead to commit into both branches as I changed a lot files.

I have never try to recreate it again after, and I suspect that individual issue I run into might be gone as that time the local svn folder structure was like every folder has it's own ".svn" folder, now with new svn working folder structure, ".svn" only exists in root so I guess it can't easily happen again.

ContentLicense: CC BY-SA 3.0


问:
Why is the minus sign, '-', generally not overloaded in the same way as the plus sign?
The plus sign + is used for addition and for string concatenation, but its companion: the minus sign, -, is generally not seen for trimming of strings or some other case other than subtraction. What could be the reason or limitations for that?

Consider the following example in JavaScript:

var a = "abcdefg";
var b = "efg";

a-b == NaN
// but
a+b == "abcdefgefg"
```

答:
The plus sign probably contextually makes sense in more cases, but a counter-example (perhaps an exception that proves the rule) in Python is the set object, which provides for - but not +:

```<code>>>> set('abc') - set('bcd')
set(['a'])
>>> set('abc') + set('bcd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'set' and 'set'
</code>```

It doesn't make sense to use the + sign because the intention could be ambiguous - does it mean set intersection or union? Instead, it uses | for union and & for intersection:

```<code>>>> set('abc') | set('bcd')
set(['a', 'c', 'b', 'd'])
>>> set('abc') & set('bcd')
set(['c', 'b'])
</code>```

Body:
The plus sign probably contextually makes sense in more cases, but a counter-example (perhaps an exception that proves the rule) in Python is the set object, which provides for - but not +:

>>> set('abc') - set('bcd')
set(['a'])
>>> set('abc') + set('bcd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'set' and 'set'

It doesn't make sense to use the + sign because the intention could be ambiguous - does it mean set intersection or union? Instead, it uses | for union and & for intersection:

>>> set('abc') | set('bcd')
set(['a', 'c', 'b', 'd'])
>>> set('abc') & set('bcd')
set(['c', 'b'])


问:
Does Akka obsolesce JMS/AMQP message brokers?
I spent the last week deep diving into the Akka docs and finally understand what actor systems are, and the problems that they solve.

My understanding (and experience with) traditional JMS/AMQP message brokers is that they exist to provide the following:

Asynchronous processing between producer and consumer; and

Message delivery guarantee, included persistence, retries and fallbacks

But doesn't Akka provide this, without all the required infrastructure and operational overhead?

In Akka, all Actor communication is asynchronous and non-blocking; and

In Akka, SupervisorStrategies exist to accomplish retry, fallback and escalation. Actors can be configured to persist to virtually any type of store, if this is a requirement too.

So this has me wondering: if my app uses Akka, do I ever have a need to bring JMS/AMQP brokers (e.g. ActiveMQ, RabbitMQ, Kafka) into the picture? In other words, is there ever a use case where a new Akka-based app would then also warrant the introduction of a new JMS/AMQP broker cluster? Why or why not?

The only argument would be that perhaps my Akka app has to integrate with another system. But in that case, the Akka-Camel module allows Akka to tap into Camel's exhaustive, almost infinite list of integration capabilities (TCP, FTP, ZeroMQ, the list goes on and on...).

Thoughts?

答:
Actor Model

The actor model is computer science strategy for building applications that handle lots of concurrent computation and stateful processing. It's not the only strategy but it's a very well tested, simple, and reliable approach that moves computation into actors, which communicate through messages that they process one-at-a-time and in order.

Akka is a framework that implements the actor model and allows you to build actor systems with all the infrastructure and features already built (like using JQuery instead of javascript).

Messaging

Message systems are applications that can send and retrieve messages. There are many varieties from basic queues to big enterprise software with topics, pub/sub, persistence and other features but the end goal is the same. Save some bytes somewhere and retrieve them again later, with some kind of ordering. The primary use case today is to decouple systems and allow for asynchronous processing at different schedules or speed. RabbitMQ, NATS, Kafka, etc are all examples of message systems.

Comparison

The Actor model and the Akka framework are low-level tools that are a great way to build applications, like message queues.

Can you use Akka instead of a message queue? Sure. If you're building software that already uses the actor model then you probably don't need an external message queue, especially for sending messages within the same thread or application. You can use Akka Remoting capabilities to even send messages to other actor systems running on other machines.

However, does this make messaging systems obsolete? Absolutely not. Just because you can code all this stuff yourself doesn't mean you need to, especially when an actor model isn't a good for your problem or you need different languages, applications, external APIs, operating systems, databases, etc. to communicate with each other (whether they are actor systems or not).

If you just need to pass some messages between two systems, use a message queue. If you need scalable stateful processing and low-latency messaging within the same application, then use the actor model. They both exist at completely different levels and how you use them depends on the solution you're building.

There's a great answer on SO about this same actor model vs messaging: https://stackoverflow.com/questions/5693346/when-to-use-actors-instead-of-messaging-solutions-such-as-websphere-mq-or-tibco

ContentLicense: CC BY-SA 4.0


问:
What do I choose if I use the source code from a GPL2 project, and another source code from MIT?
Some scenarios:

If I have a project that uses source code from a GPL 2 licensed project, and another set of source code from an MIT licensed project, what do I license my whole project as?

What if I have a project with multiple modules where one module uses source code from a GPL2 project and another uses source code from MIT (or another license that states the whole project must be under the same license), but neither modules "interact" with one another?

What should my project uses if I modify MIT licensed source code to use the source code of a GPL 2 licensed project (or let's say it's two licenses that state that both state the whole project must be under the same license)?

答:
TLDR; assuming you are going to release it, you release your code under GPL.

When mixing licenses the first question is generally, are they compatible - in this case (IIRC), yes they are. So using code from MIT and GPL are allowed in the same project.

The second point is what duties do you have w.r.t. acknowledging the code being used - given the licenses in question, this is generally attribution and inclusion of the original license text.

The third issue is what license can be the code be released under. Given the GPL, the code needs to be release under the same GPL license. The GPL is pretty clear on this. I believe this was also one of the original intents of the GPL - make sure code using the GPL remains GPL.


答:
If I have a project that uses source code from a GPL 2 licensed project, and another set of source code from an MIT licensed project, what do I license my whole project as?

Derived works from GPL code must be under GPL as well "as a whole". Adding MIT license code does not change this (what makes you believe it should)? MIT requires you to mention the original copyright and license text for the part you are reusing, which is not contradictory to the GPL.

What if I have a project with multiple modules where one module uses source code from a GPL2 project and another uses source code from MIT (or another license that states the whole project must be under the same license), but neither modules "interact" with one another?

Module 1 must be under GPL as well, module 2 under any license you like as long as it is compatible with MIT. If those two modules are not linked together and do not interact, they are two separate products. Just putting them on the same data storage medium or selling them both together does not imply you need the GPL for both (as stated in the FSF's GPL FAQ). If you want, however, create a combined product which uses the two modules, and link them both, see 1.

What should my project uses if I modify MIT licensed source code to use the source code of a GPL 2 licensed project (or let's say it's two licenses that state that both state the whole project must be under the same license)?

That depends on what you mean by "to use the source code of a GPL 2 licensed project". If you modify the MIT licensed source to link the GPL code together with it, allowing in-process communication, the combined work must be under GPL, same as in 1.

Please, before asking further question here on SO, read the license texts by yourself, and when anything is unclear, read the GPL FAQ. When there still remain questions, search here on Programmers first if someone has asked already a similar question in the past (I am sure we had dozens of very similar questions to yours). And only if you did not find an answer, ask a new question here.

Title: What do I choose if I use the source code from a GPL2 project, and another source code from MIT?

Body:
Some scenarios:

If I have a project that uses source code from a GPL 2 licensed project, and another set of source code from an MIT licensed project, what do I license my whole project as?

What if I have a project with multiple modules where one module uses source code from a GPL2 project and another uses source code from MIT (or another license that states the whole project must be under the same license), but neither modules "interact" with one another?

What should my project uses if I modify MIT licensed source code to use the source code of a GPL 2 licensed project (or let's say it's two licenses that state that both state the whole project must be under the same license)?


问:
What is a vanilla version, and what should software have to distinguish it from a vanilla version?
I have seen the term "vanilla version" used seeral times. For example, I have seen the term on the Lasagna-users google group, where a user mentions the term:  vanilla CNN package.

So, when is a software called a vanilla version, and what should it have for it to be called it (or distinguish it from being a vanilla version)?

Explanation can be done by taking a software/library in mind.

答:
In context, software is "vanilla" when it's ordinary: that is, it isn't customized or expanded upon. It comes from the ice cream flavor "vanilla" which to some is considered to be ice cream's "default" flavor.

Some examples of "vanilla" in software:

Consider a customizable text editor like Sublime Text: "vanilla" Sublime would be running it without any plug-ins.

Take a video game like World of Warcraft: "vanilla" World of Warcraft is the game as it was prior to the release of its expansion sets.

Consequently, software stops being "vanilla" when it's been customized or expanded upon to suit a specific purpose.

So, a vanilla library may be one that does the absolute minimum to implement a specification, while a non-vanilla library would be one that takes it one or more steps further and does something above and beyond what the vanilla counterpart does.


答:
What is a Vanilla version?

The "vanilla version" is generally the version that has no customisation applied - it is the "regular", "ordinary" or "plain old" version.

For a lot of consumer based software - this would be the only version. You would not build custom versions for every user.

If the software includes extension or customisation points such as plugins, then as installed it would be the vanilla version, but once the user gets hold of it and adds and configures things as they like it, it would no longer be "vanilla."

For bespoke based software - the vanilla version is often the demo version. The bespoke software really comes into its own because it can be customised, so it almost always is.

And what should a software have, for graduating from a vanilla version? (before the edit)

Well, it won't be graduating (when compared to the move from alpha to beta). The move from vanilla to non-vanilla is the addition of customisations that essentially make it unique. The customisations differentiate or distinguish it from the regular version.

Title: What is a vanilla version, and what should software have to distinguish it from a vanilla version?

Body:
I have seen the term "vanilla version" used seeral times. For example, I have seen the term on the Lasagna-users google group, where a user mentions the term:  vanilla CNN package.

So, when is a software called a vanilla version, and what should it have for it to be called it (or distinguish it from being a vanilla version)?

Explanation can be done by taking a software/library in mind.


问:
UML: Should an asynchronous request-response message exchange be modelled as two ports/interfaces or one
I want to model an asynchronous request-response message exchange in UML.

The request is sent from a client to a server. The server responses asynchronously.

This can be modelled in a component model in two ways:

Option 1

Request and response are two different interfaces with one method each. The server provides the request interface while the client provides the reponse interface. The interfaces are required vice versa. In UML I would model the server and the client as components having one port each. Both ports expose two interfaces: a provided one and a required one which are linked from client to server (request) and from server to client (response).

Option 2

Request and response is one interface with one method. The response is simply the return value of this method. The server provides and the client requires this interface. The message exchange is modelled as link from the client to the server.

I think option (1) is more appropriated for asynchronous exchanges while option (2) is the preferred way for synchronous ones. However, making such a distinction would expose a detail in the component model which actually belongs to the behavioural diagrams.

Is there any standard or "best practice" to model an asynchronous message exchange in component models?

If option (2) is the "right" way to do it: how should one specifiy that the client must comply with an interface contract in order to receive a response?

答:
I believe you are correct in the assessment that option 2 is better for synchronous messages and option 1 for asynchronous messages.

By their very nature asynchronous messaging schemes (even if it is solicited) are more complicated to model. Option 1 would be the better option to model the messaging you describe.

I appreciate your concern that using option 1 would include a fair level of detail that may be too much for the diagram in question.

You could model a custom relationship or association (named appropriately, e.g.: <<CustomRqRs>>) and use that to link the components. This simplifies the diagram, better describes the interaction and offers better modelling of the message and response itself.

When modelling it is always important to bear in mind that it is primarily there to communicate intent; design, usage, possible implementation, function etc. Simpler is almost always better. Model it accurately, model it well, but keep it simple.


问:
Implementing an association between 2 classes
Consider the following association between the 2 classes

.

Here the association means, In the class Log I have an array of Traces. and in class Trace there is an object of Log.

Here I have a problem in implementation these 2 classes now.
If I want to make Log instance, I need an array of Trace and when I go to make an instance of Trace, again I need an Log object. And this loop is continuing.

So am i in wrong way?

答:
You don't need a Trace instance to create an array of Trace objects. You just need a typed array.

Therefore it's obvious how to implement this: create an empty array in the Log constructor, and when something noteworthy happens, create a Trace that knows its Log, and add it to the array.

There are other, more complicated situations, but so far you haven't shown anything that requires breaking any kind of cycle to work.


问:
Has Little Endian won?
When teaching recently about the Big vs. Little Endian battle, a student asked whether it had been settled, and I realized I didn't know. Looking at the Wikipedia article, it seems that the most popular current OS/architecture pairs use Little Endian but that Internet Protocol specifies Big Endian for transferring numeric values in packet headers. Would that be a good summary of the current status? Do current network cards or CPUs provide hardware support for switching byte order?</p>

答:
No, nobody has won. We as a species we have failed to standardize the order in which we store our bytes, along with the direction we write and the side of the street we drive on.

As a consequence, anyone who wants to transfer data between two different systems over a network or in a file, has only about a 50% chance of the reasonable initial version of their data dumping code being correct in their environment, and even if it works, has a 50% chance of working in their customer's.

To deal with this you need to go look up platform specific functions with names like "htonl" in headers with names obviously dating back to the 70's like "arpa/inet.h", because the situation has not improved since then and probably never will.

Title: Has Little Endian won?


答:
The question is how is going to be created first.

You can create the traces and when you plug the traces into the log you just add a function in Trace to specify the father log

I didn't test this idea yet but I believe it will work.

Title: Implementing an association between 2 classes

Body:
Consider the following association between the 2 classes

.

Here the association means, In the class Log I have an array of Traces. and in class Trace there is an object of Log.

Here I have a problem in implementation these 2 classes now.
If I want to make Log instance, I need an array of Trace and when I go to make an instance of Trace, again I need an Log object. And this loop is continuing.

So am i in wrong way?


答:
The Groovy language does allow -:

```<code>println('ABC'-'B')
</code>```

returns:

```<code>AC
</code>```

And:

```<code>println( 'Hello' - 'World' )
</code>```

returns:

```<code>Hello
</code>```

And:

```<code>println('ABABABABAB' - 'B')
</code>```

returns:

```<code>AABABABAB
</code>```

Title: Why is the minus sign, '-', generally not overloaded in the same way as the plus sign?

Body:
The plus sign + is used for addition and for string concatenation, but its companion: the minus sign, -, is generally not seen for trimming of strings or some other case other than subtraction. What could be the reason or limitations for that?

Consider the following example in JavaScript:

var a = "abcdefg";
var b = "efg";

a-b == NaN
// but
a+b == "abcdefgefg"
```

Body:
The Groovy language does allow -:

println('ABC'-'B')

returns:

AC

And:

println( 'Hello' - 'World' )

returns:

Hello

And:

println('ABABABABAB' - 'B')

returns:

AABABABAB


问:
the future of commercial products
I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>

答: While there are some open source products which are indeed popular and professionally developed, I don't think that they pose any challenge to commercial mode of development, in fact I foresee some sort growth of some sort of hybrid model where we  have an open source product at the core which is used to generate revenue either by customization, support, consultancy or downstream development. In fact I see bigger threat to commercial development from collapse of IP regime.</p>

ContentLicense: CC BY-SA 2.5

Title: the future of commercial products


答:
There is still no consensus:

The majority of larger computer systems (server/desktop/laptop) currently use little-endian architectures

The majority of smaller computers (tablets/phones) use an endianness-independent processor architecture, but run operating systems that use little-endian order

So at the hardware level, LE is far more common.  But:

Most inter-computer communication is carried out using protocols that specify big-endian order

A very large proportion of the world's software runs on a virtual platform that defaults to big-endian order whenever data is written to external storage.

Both orders are going to be with us for the foreseeable future.

Title: Has Little Endian won?

Body: When teaching recently about the Big vs. Little Endian battle, a student asked whether it had been settled, and I realized I didn't know. Looking at the Wikipedia article, it seems that the most popular current OS/architecture pairs use Little Endian but that Internet Protocol specifies Big Endian for transferring numeric values in packet headers. Would that be a good summary of the current status? Do current network cards or CPUs provide hardware support for switching byte order?</p>


问:
Should I use scrum for big projects?
I've been working as a programmer on a project designed for generic software for gas stations (to be redistributed for many customers) for 18 months. The project is big. Today we have around 150 tables. We haven't used a specifc approuch, it was not well managed.

The person table has today around 70 columns, but 15 months ago it had around 30 columns. These new fields emerged in order to integrate with other modules such as sales, financial and accounting. Also many fields were created then deleted.

As a result, we had many refactoring and rework. The project never gets ready because there are always new requirements emerging.

Here's my doubt: if we had used a usual approach of specification, we would had interviews, a requirements document, activity, sequence and class diagrams, so we would know since the begin that the "person" table would need 70 fields, then we had avoided a lot of refactoring.

Could scrum help in this project? I have a feeling that in this case scrum would end up in a lot of refactoring as well.

I'm only a programmer, not a project manager. I'm wondering how it should have been done: with scrum or with big design up front.

Edit

Just to complement the end of this story.
Eight months later I asked this question, after put the project in production in some "test costumers" the project officialy failed. The product owner decided to abandon the project. It got hard to fix problems and a lot of perfomance problems occured.

答:
It looks like you have churned your way in an uncontrolled development process to create a never-ending development system. This occurs in agile systems too.

The root problem is a lack of requirements, and while your solution might seem to be to use an agile methodology to fix this (as agile is designed around changing requirements) it would not solve the problem.

Even agile methods require a fairly firm starting point. They respond well to changing requirements, but they are just as useless as any other methodology if you start with no requirements. You still have to have a plan that you're heading towards before you start. Agile helps when that goal drifts, it does not help you define that goal.

Now its true that a fixed up-front design is too rigid if you do not know exactly what you are building.

So, I think you're going to have to move from your current 'chaos' methodology to something more organised and will have to implement a fair amount of design and planning. You can try to do this in one go with a heavy methodology, or you can be more flexible with an agile one. What you cannot do is expect any methodology to fix your lack of initial planning.

Incidentally, Kanban sounds more appropriate for your needs. Scrum works best with small teams and projects. Kanban can work with larger projects but it also works with a throughput of work approach, so design changes are continual and not chunked into sprints. I think you'd have more success with that.

Title: Should I use scrum for big projects?


答:
If you can't manage requirements and don't have people capable of implementing requirements properly, SCRUM isn't going to help you (much), and that seems to be the real problem you're facing.

SCRUM can help you better deal with changing requirements than more static project management systems, but it's not the holy grail that will magically make everything work. In fact, unless your people are on board, willing and capable of working with SCRUM, and so is the rest of the organisation, it may end up making things worse.

If you've a table that's grown so much to fit in stuff to link with other systems, I postulate your database design is seriously flawed for example. No amount of SCRUM is going to improve your database design without you including people who are good at database design in your team and not being afraid of those design changes and the changes they will cause to the rest of your system.

Title: Should I use scrum for big projects?

Body:
I've been working as a programmer on a project designed for generic software for gas stations (to be redistributed for many customers) for 18 months. The project is big. Today we have around 150 tables. We haven't used a specifc approuch, it was not well managed.

The person table has today around 70 columns, but 15 months ago it had around 30 columns. These new fields emerged in order to integrate with other modules such as sales, financial and accounting. Also many fields were created then deleted.

As a result, we had many refactoring and rework. The project never gets ready because there are always new requirements emerging.

Here's my doubt: if we had used a usual approach of specification, we would had interviews, a requirements document, activity, sequence and class diagrams, so we would know since the begin that the "person" table would need 70 fields, then we had avoided a lot of refactoring.

Could scrum help in this project? I have a feeling that in this case scrum would end up in a lot of refactoring as well.

I'm only a programmer, not a project manager. I'm wondering how it should have been done: with scrum or with big design up front.

Edit

Just to complement the end of this story.
Eight months later I asked this question, after put the project in production in some "test costumers" the project officialy failed. The product owner decided to abandon the project. It got hard to fix problems and a lot of perfomance problems occured.


问:
Working with local connections instead of global
In recent weeks I became very concerned that the way I've been working with database connections for the past years, is simply wrong.

I exclusively create a new connection for each database operation I have to perform. only in the more complex programs, I would stack several tasks (Sql commands) in the background and then every few seconds I would  create a new single connection, and execute these with the same connection.

Here is typical sample:

```<code>     SqlConnection connection = new SqlConnection(con);
            SqlCommand command = new SqlCommand(@"
            DECLARE @Pk TABLE (Id int)
            INSERT INTO Petrol.Reports(
            [TimeStamp])
            OUTPUT INSERTED.Id INTO @Pk
            VALUES(
            @TimeStamp)

            SELECT Id FROM @Pk", connection);
            command.CommandType = CommandType.Text;

            SqlParameter parameter = command.Parameters.Add("@TimeStamp", SqlDbType.DateTime);
            parameter.Value = this.TimeStamp;

            using (connection)
            {
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        this.Id = reader.GetInt32(0);
                        Ref.Petrol_ReportsById[Id] = this;
                    }
                }
            }
</code>```

Recently I started working with PostgreSQL and I was freighted to see that it creates a new process for almost every connection I create.

The deal is that most code samples around are using very similar approach, but I'm afraid that this is just to keep things simple.

I consider re writing my objects generating tool to share a single connection between all operations (with thread safety in mind), would this be a correct approach in your opinion?

答:
You should, although it is likely already being done for you

In database operations, a large part of the cost associated with the operation is setting up the connection, doing proper authentication, and so on. It makes a lot of sense to not have a new connection for every operation but simply re-use existing connections. This is a pattern called connection pooling.

The thing with connection pooling is that it is such a great improvement that a lot of times the language you are working with will do it implicitly. You will often have to explicitly tell the code in some whay that you do NOT want to use connection pooling. In your code, the call to close on the connection would not actually close the connection unless you specifically configure your connection string that way. It will simply return it to the pool, making it available for use again.

With that in mind your pattern of connection usage is very good: you get a connection (that will be created if none are available, or simply be a re-used connection that existed), use it for the shortest amount of time you need it to execute your actions, and then release it (to be either destroyed after a period of time or re-used for other actions).


问:
Software architecture entity connections
For learning purpose I want to create an app.

So I thought I will do something real easy to learn a lot about object oriented programming and modelling. After some thinking I had the idea to do a simple Sport-Ranking app. I thought this is very simple and I could build it up further and further.

So first, this is why I thought it is easy: Is all you need is three Entities. Person, Gender and Race.

They would look roughly like:

```<code>+--------+     +----------+     +--------+
| Person |     | Race     |     | Gender |
+--------+     +----------+     +--------+
| name   |     | name     |     | name   |
| birth  |     | date     |     +--------+
| e_mail |     | distance |
| gender |     | address  |
+--------+     +----------+
</code>```

Now of course I was wrong. This bluddy race part is getting tricky.

So I changed race to:

```<code>+---------+  +------------+  +------------+  +----------+  +----------+  +--------+
| Race    |  | R_Distance |  | R_Category |  | R_Result |  | R_Number |  | R_Time |
+---------+  +------------+  +------------+  +----------+  +----------+  +--------+
| name    |  | distance   |  | category   |  | result   |  | number   |  | time   |
| date    |  +------------+  +------------+  +----------+  +----------+  +--------+
| address |
+---------+
</code>```

I'm verry uncertain if this is right. I mean a Race-Time and Race-Number belongs to the race and also belongs to the Person. So how can I connect them?

What else should I think about? How to handle if a race has interims and laps?

Should I also have a entity R_Rank?

答:
You need an intermediate object for that. If a person finished a race, you would store the result of that race in a separate object: a PersonRaceResult. It would have a reference to the Person that ran and a reference to the Race the person ran, as well as properties for the result such as a Time indicating the total time to complete the Race.

If you need things like laps, your model stays about the same (assuming every lap is the same distance). Race would then probably have a NumberOfLaps property, a PersonRaceResult whould have the references to Race and Time but also a collection of PersonRaceResultLapTimes. These would have a reference back to their PersonRaceResult, as well as a LapNumber to indicate what lap was run as well as a Time which indicates the time it took for a lap. In order to get the final result time, your PersonRaceResult would loop through all the PersonRaceResultLapTimes, add all the Time-properties and return that.


答:
Please note that when I wrote this answer, I didn't realise that the system was not in production yet.

They way you describe your product, I don't think that your immediate problem is that of managing requirements, nor your development process. It is that of your system architecture.

You have managed to create a monolith - and a rather large one at that. 150 tables is a lot for one system*. In particular, you mention that you have 40 new fields during the last 15 months just for integrating to external systems. I would seriously consider splitting your system into several autonomous services, probably starting with services for integrating to external systems - but later identifying separate business areas implemented in you monolith, and then perhaps split those concerns into separate services.

If you manage to split this monolith into separate maintainable code bases, you can also split your developers into smaller teams with well-defined responsibilities in specific areas of your business, and you can have a lot of smaller agile teams maintaining their own code base, instead of all hacking in the same code base.

As to why you have arrived at such an architecture, the root cause for your problem, there can be many answers. Maybe it's rooted in you development process, maybe all your developers are only experienced with transactional consistent software, or maybe it's a consequence of how your organization is structured (you are the victim of Conway's Law). I think there's a good chance it is a combination of the latter two.

I don't think that implementing scrum, or being better at managing requirements will help solve your immediate problem, nor the root cause. Adjusting the architecture for the complexity of you system will, and addressing the root cause for why you have build such a system will.

* Some will probably argue that they can maintain a system with 150 tables - or they have maintained much larger systems, but I do believe that most developers will consider this a large number of tables for one system.

Title: Should I use scrum for big projects?


答:
18 months, 150 tables and still not in production? Sounds much like a death march for me. The only way you can fix this, if there is any chance to save this now, is to narrow the scope of your project dramatically - at least for your first production release. What you need is proper release planning, small, reachable goals and getting the system to the end user as soon as possible.

And when you have your first release in production, with only a tenth of the requirements implemented, you will have to extend it step-by-step by the next block of requirements, which will cause "refactoring". You will also get feedback, which means bugfixing and changed requirements, which will cause refactoring, too.

Now to you question - will Scrum help? Maybe, maybe not. Scrum is a tool to support iterative development and changing requirements, and focussing on the important things first. Other "Agile" methods do this too, and a not-so-formalized process might handle that also. But as long as you try to bring a monster like this in one "big bang" into production, it does not matter if you use "agile" or "upfront" development, both will fail.

So before thinking about Scrum, first rethink your goals and your release strategy, and then check if Scrum is the right tool for that, not vice versa.

Title: Should I use scrum for big projects?


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
My first open source contribution was for a library that I had previously used (and would've suffered greatly without) on a previous paid project. During my initial use I had spotted a bug in the code so I created a patch, joined the project, and submitted it for review.

About 8 months later when I had some free time I decided that I would give back (and work on my development skills) by contributing more to the project. So I cloned the repository and started getting familiar with the codebase. After a few weeks of submitting minor patch fixes to the codebase and monitoring the feature requests, I picked up a feature request to add a pretty substantial module to the project.

Since generating many individual patch fixes is pretty tedious for any significant development I cloned the repository to a branch on git hub and started punching away code. A few weeks and several thousand lines of code later the project leader and me worked through integrating and testing my fixes into the library in a way that worked consistently with the rest of the codebase.

It was an invaluable process that I learned a lot from:

When I started I didn't know how to use Git, by the end I could proficiently create remote tracking branches and merge or rebase them into the master branch without breaking a sweat.

I started in VS 2008 and ended up migrating to Linux and Monodevelop to work on writing code (because VS is unicode retarded and line endings are such a pain in git). It turns out that theres not much you can't do in *nix that you can do in *dows.

I had never really done any unit testing before, Nunit is a piece of cake to use and writing unit tests is pretty elementary stuff.

I had to learn to swallow my tongue and listen as well as practice patience. There's no point in standing a firm ground on your position on an open source project because everybody involved is knowledgeable (probably more so than yourself) and capable of accepting/rejecting your ideas based on substance not delivery. It's extremely humbling and rewarding at the same time.

Just having one other skilled developer's eyes on a large base of my code pointed out flaws in my style that I had never considered before (as well as I pointed out flaws in his code). For me, I learned that it's easier/better to define constants than it is to use a bunch of magical numbers with detailed commenting.

That particular project was based around generating and decoding networking packets on all levels of networking protocols. I have a personal interest in lower level networking so it was great to have discussions with another developer with shared interest and knowledge in the domain.

If you want to just get your feet wet: find a project that you already use; clone the repository; and start seeing if you can fix some bugs and/or add some unit tests. It seems intimidating to look at someone else's codebase with fresh eyes but it's an extremely valuable skill to learn. Submit some patches. You can expect your code to be closely scrutinized at first. Don't worry about it, it's a normal part of the process to gain the trust of the project admin(s).

After establishing a base of merit with the projects admin(s) start seeking more responsibilities such as, proposing new features, or asking to be assigned to implementing feature requests.

If you can't find an already existing project on one of the main open source repository networks (github, sourceforge, google code) think of an app that you'd really like to use that doesn't exist yet and start your own.

Be prepared to be humbled and expect work to be rejected in favor of further revisions. The myth that anybody can add code to an open source project is completely false. There's always a gatekeeper between you and push access. The better your code, the less it will be scrutinized in the long run as you gain trust of the project admin(s). If it's your project, you'll be that gatekeeper.

Update:

I just thought about it and realized that I didn't bother to mention which project that a lot of my answer is referencing. For those who want to know, it's SharpPcap. The lead developer Chris Morgan is very professional and on point. He does a hell of a job managing the project and taught me a lot about what it takes to mature a OSS project.

Due to personal time constraints I haven't been able to contribute code in over a year but I still try to give back by lurking on Stack Overflow and answering questions about SharpPcap occasionally.


问:
Difference of efficiency
I'm doing a compiler, and I'm using the System.out.println(); to print assembly;

And the code get bigger, and more complicate to understand. I want to know whats is the difference of efficiency between this and if I should or no:

```<code>System.out.println("iload");
</code>```

Or:

```<code>private void printAssemblyCode(String code) {
    System.out.println(code);
}
printAssemblyCode("iload");
</code>```

It's only to be more readable. It's worth it or not doing this?

答:
The overhead of calling one more method to output something will be too small to notice, since I/O is much, much slower than computation.

The question remains how much more readable it is to use your custom print method rather than println directly. I would think it is small, but it could be worthwhile anyway, since the added cost is very close to 0.

Title: Difference of efficiency


答:
Putting the code into a method has a different advantage: If you ever decide to not print to console, you would only need to change a single line of code.

Hardcoding the print-to-console like that throughout your project is not a good idea.

Once you have a working version and want to continue with it then you'd have to go through and change how you pass the assembly to the calling code for further processing. One of the things you can do is change the prints to a call to a pluggable interface that collects the opcodes (not as strings) and a implementation that prints them to console.

Title: Difference of efficiency

Body:
I'm doing a compiler, and I'm using the System.out.println(); to print assembly;

And the code get bigger, and more complicate to understand. I want to know whats is the difference of efficiency between this and if I should or no:

```<code>System.out.println("iload");
</code>```

Or:

```<code>private void printAssemblyCode(String code) {
    System.out.println(code);
}
printAssemblyCode("iload");
</code>```

It's only to be more readable. It's worth it or not doing this?


答:
The efficiency is not much different due to optimizations in modern Java compilers, but it does not gain much flexibility. The only thing it lets you do is turn off printing in one location rather than many.

You would be better served by delegating to a logging framework. Java has built-in logging, and there are other frameworks such as Log4j.

Using a logging framework you gain several abilities your current code does not:

You can log to arbitrary streams: standard out, standard error, a file, a socket, etc.

You have additional diagnostic levels. Rather than on or off you can have error, warning, info, et al and you can control which diagnostic levels are output.

Logging messages can include additional information such as the class and line number where the logging occurred (if you pass along a Throwable), and the date and time.

All of the configuration is done through, well, configuration, not code. Rather than commenting out a line of code and rebuilding, you can edit an XML or properties file and you are done.

Once you get in the hang of using a logging framework it is just as easy as using System.out.println() but there is far more capability if you need it.

Finally, a logging framework typically requires a tiny amount of initialization but adds little or no noticeable overhead to the running process when you invoke its functionality.

Title: Difference of efficiency


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

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

答: Not really. I find that coding is something you have to continually keep doing to maintain and improve. On a long break I actually often revert to bad habits. It's only when I come across some of my previous code (before the long break) that I realise just how good I was back then.</p>


问:
Could an instance be equal to some other instance of a more specific type?
I've read this article: How to Write an Equality Method in Java.

Basically, it provides a solution for an equals() method that supports inheritance:

```<code>Point2D twoD   = new Point2D(10, 20);
Point3D threeD = new Point3D(10, 20, 50);
twoD.equals(threeD); // true
threeD.equals(twoD); // true
</code>```

But is it a good idea? these two instances appears to be equal but may have two different hash codes. Isn't that a bit wrong?

I believe this would be better achieved by casting the operands instead.

答:
It is often useful for non-public-facing classes to have an equivalence-testing method which allows objects of different types to consider each other
"equal" if they represent the same information, but because Java allows no means by which classes can impersonate each other it's often good to have a single public-facing wrapper type in cases where it might be possible to have equivalent objects with differing representations.

For example, consider a class encapsulating an immutable 2D matrix of double values.  If one outside method asks for an identity matrix of size 1000, a second asks for a diagonal matrix and passes an array containing 1000 ones, and a third asks for a 2D matrix and passes a 1000x1000 array where elements on the primary diagonal are all 1.0 and all others are zero, the objects given to all three classes may use different backing stores internally [the first having a single field for size, the second having a thousand-element array, and the third having a thousand 1000-element arrays] but should report each other as equivalent [since all three encapsulate a 1000x1000 immutable matrix with ones on the diagonal and zeroes everywhere else].

Beyond the fact that it hides the existence of distinct backing-store types, the wrapper will also be useful for facilitating comparisons, since checking items for equivalence will generally be a multi-step process.  Ask the first item if it knows whether it's equal to the second; if it doesn't know, ask the second if it knows whether it's equal to the first.  If neither object knows, then ask each array about the contents of its individual elements [one might add other checks before deciding to do the long-slow individual-item comparison route].

Note that the equivalence-test method for each object in this scenario would need to return a three-state value ("Yes I'm equivalent", "No I'm not equivalent", or "I don't know"), so the normal "equals" method would not be suitable.  While any object could simply reply "I don't know" when asked about any other, adding logic to e.g. a diagonal matrix which would not bother asking any identity matrix or diagonal matrix about any elements off the main diagonal would greatly expedite comparisons among such types.


问:
Pthread scheduling (System and Process)
I've read the operating system concepts 8th edition written by abraham silberschatz. However, I don't understand Pthread Scheduling.

Thread-library schedules user-level-threads on LWP(Lightweight Process).

This is Process-Contention Scope(PCS) because contention occurs between threads belonging to the same process.

OS schedules kernel-threads on CPU.

This is System-Contention Scope(SCS) because contention occurs between all threads belonging to the system.

I thought that PCS is corresponding to user-level-thread and SCS is corresponding to kernel-level-thread.

But the following code is setting thread mode as user mode.

```<code>pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
</code>```

I don't understand why it is user mode, not kernel mode.
Please Someone aware of this let me know, thank you for reading.

答:
I think you are confusing inter-process (user) space, intraprocess threads, and system space.  So let's start with some definitions.

Threads belong to a process.  A process can run within user space and system space.  Which space a process belongs to is a function of how it is invoked.

System space tends to be the lowest level and is where protected or kernel processes run.  Typically, they are owned by the system itself.

User space tends to be higher level and has less privileged processes.

Inter-process (user) space threads can be thought of as threads belonging to separate processes.

Intraprocess threads can be thought of as threads belonging to a single process.  And that process may be running in user or system space.

So when you call:

```<code>pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
</code>```

What you're really doing is moving the thread from being part of the rest of that calling process and moving it out into user space.  Effectively it makes the thread a new process and is equivalent to fork, but I'm not positive on that aspect so don't quote me on it.

I think your confusion comes from the _SYSTEM portion of that definition.  However, an operating system wouldn't necessarily want a process to be able to move from user space into system space as that could lead to an undesirable privilege escalation for that process.  The kernel rightfully doesn't trust user space processes as they have been historically proven to be rubbish (from the kernel's perspective).

Said another way, that pthread_attr_setscope call doesn't allow you to move from PCS into SCS.

The man page is semi-helpful in understanding this.

PTHREAD_SCOPE_SYSTEM

  The thread competes for resources with all other threads in all processes on the system that are in the same scheduling allocation domain (a group of one or more processors).  PTHREAD_SCOPE_SYSTEM threads are scheduled relative to one another according to their scheduling policy and priority.

emphasis added

Note the final clause in the part I emphasized: "that are in the same scheduling allocation domain".  And also note that it makes no mention of being able to switch to a different scheduling allocation domain.

Title: Pthread scheduling (System and Process)

Body:
I think you are confusing inter-process (user) space, intraprocess threads, and system space.  So let's start with some definitions.

Threads belong to a process.  A process can run within user space and system space.  Which space a process belongs to is a function of how it is invoked.

System space tends to be the lowest level and is where protected or kernel processes run.  Typically, they are owned by the system itself.

User space tends to be higher level and has less privileged processes.

Inter-process (user) space threads can be thought of as threads belonging to separate processes.

Intraprocess threads can be thought of as threads belonging to a single process.  And that process may be running in user or system space.

So when you call:

pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

What you're really doing is moving the thread from being part of the rest of that calling process and moving it out into user space.  Effectively it makes the thread a new process and is equivalent to fork, but I'm not positive on that aspect so don't quote me on it.

I think your confusion comes from the _SYSTEM portion of that definition.  However, an operating system wouldn't necessarily want a process to be able to move from user space into system space as that could lead to an undesirable privilege escalation for that process.  The kernel rightfully doesn't trust user space processes as they have been historically proven to be rubbish (from the kernel's perspective).

Said another way, that pthread_attr_setscope call doesn't allow you to move from PCS into SCS.

The man page is semi-helpful in understanding this.

PTHREAD_SCOPE_SYSTEM

  The thread competes for resources with all other threads in all processes on the system that are in the same scheduling allocation domain (a group of one or more processors).  PTHREAD_SCOPE_SYSTEM threads are scheduled relative to one another according to their scheduling policy and priority.

emphasis added

Note the final clause in the part I emphasized: "that are in the same scheduling allocation domain".  And also note that it makes no mention of being able to switch to a different scheduling allocation domain.


问:
Conventions for revision control with Maven/Jenkins
For a software project I am working on, we have a 'dev => QA => production' methodology. That is, we create  a release candidate (deployed to Artifactory), give it to QA (deploy to QA systems and a QA backend/application server) who takes a week or so to look at it, and if they it's ok, we make a production release.

Now, I come from an embedded/native app background, not as much Java/systems/CI. And I am accustomed to revision control organized with all releases tagged (in this case, the production release tags are always just copies of an RC tag).

```<code> branches/1.2
 branches/1.3
 tags/1.2.0-rc
 tags/1.2.0
 tags/1.3.0-rc
 tags/1.3.1-rc
 tags/1.3.1
</code>```

However, several team members state that this doesn't work well with Maven (and maybe Jenkins too). Instead, they suggest:

```<code> branches/1.2.0-rc
 branches/1.3.0-rc
 branches/1.3.1-rc
 tags/1.2.0
 tags/1.3.1
</code>```

I am arguing that a release candidate should not be a branch, as we need to deliver a known entity to QA (as opposed to a continuous integration/deployment situation where we might cut the production release directly from our development line without waiting for QA). The fact that several developers are checking code into the RC branch, and there is little control around it, has caused issues.

Could somebody please explain if there's something about Maven or Jenkins that would make the second way "better"? Is there anything that makes the first way more difficult to implement?

答:
I don't quite see how Maven or Jenkins would relate to this! But I'd like to give a general distinction to this. (Even if this is a pretty old question...)

A branch is something that you work on.

A tag is only a name.

So in case your work is an RC, you could still be in need of fixes or improvements, that's why you keep working on it and having a branch for it.

Once you're done and your work is released, you keep a permanent pointer to that version (the tag).

So I'd favor version 2 also! I'd call this the typical way. And maybe that's why it integrates with Jenkins better, too - because as long as it's still work in progress and you might have to redeploy, it's better to have a branch (as a deployment source - at least we work this way with Bamboo).


问:
Ever-running timed tasks
I need to design a piece of software which is invoking some actions regularly. By regularly I mean that there is x things that need to be done at 12.00, y things at 12.30 etc,etc.

The times and dates are accessible from the DB.

My question is - what would be the best approach to handling never-stopping nature of the app?

Obvious solution would be an infinite cycle with a timer and state of the app recording. If process dies, we start off the last entry. It is important that even if process dies when it's time to do something, we still do it when it has been restarted.

Are there any smarter approaches to this?

Would Ruby's Class: Concurrent::TimerTask be of any real advantage as a timing mechanism (aside of being multi-threaded)?

答:
You have to be careful with this kind of distributed system. For example: imagine I have a triggering server in London and another in New York. If a Deep One cuts through the cable between them, London will think "NY's gone down, I have to take over", and NY will think "London's gone done, I have to take over"... and your application will be triggered twice. That means you have to have at least 3 servers so one can act as a monitor for the others to arbitrate whether they are disconnected from each other or really down.

Often in such situations, one acts as a master and the other a standby, so only one is effectively running at any given time. When the standby detects the master is not longer responding (to heartbeats for example) then it becomes the master and takes over.

This supposes your application to be triggered is similarly distributed - no good London trying to run an app on the NY server if the NY server has failed.

Of course,it also supposes your DB is accessible from both servers, failure to contact the DB makes the currently running master server consider itself disconnected and intentionally fall over, and that means your DB has to be resilient too (or you might as well run your triggering server on the DB server itself).

Fully fault tolerant, distributed systems are not trivial to get right. You can get 80% of the required service quite easily, its the other 20% that's really hard. ZeroMQ has some great architectural documentation concerning network topology that is very good to read and will help you understand which type of fault tolerance you might want.

Given that, maybe all you really need is a localhost-served perl script that runs regularly and remembers the last time it ran. How long can you tolerate between the time something should run and when it does? If that time is greater than the reboot time of a server, there's your simple-yet-effective solution. IF you need absolute sub-second responses with 99.9999% availability - well, lets say the author of ZeroMQ probably still has a large hole behind his house that could yet be turned into an executive swimming pool.

Title: Ever-running timed tasks


答:
I never felt my general skillset improved after a break (thinking about it, improving a skill without practice seems rather hard), but it's definitely so that after a break of some days/weeks my mind was clearer and it was easier focusing and seeing both the big picture and small implementation details at the same time. In other words, I'd come up with better code.

However, if the break is too long (say months), it's the other way around: then I have to get used to it again before acquiring the same level as before.

Also, the above is true for almost everything I (and likely, almost everybody) do that requires some sort of training of the mind: snowboarding, bmx, board games, puzzels, ... and even sex.

Title: When returning from a period of not programming, do you find you've improved?

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

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


问:
How are comments usually parsed?
How are comments generally treated in programming languages and markup? I am writing a parser for some custom markup language and want to follow the principle of least surprise, so I'm trying to determine the general convention.

For example, should a comment embedded within a token 'interfere' with the token or not? Generally, is something like:

```<code>Sys/* comment */tem.out.println()
</code>```

valid?

Also, if the language is sensitive to new lines, and the comment spans the new line, should the new line be considered or not?

```<code>stuff stuff /* this is comment
this is still comment */more stuff
</code>```

be treated as

```<code>stuff stuff more stuff
</code>```

or

```<code>stuff stuff
more stuff
</code>```

?

I know what a few specific languages do, nor am I looking for opinions, but am looking for whether or not: is there a general consensus what is generally expected by a mark up in regards to tokens and new lines?

My particular context is a wiki-like markup.

答:
Usually comments are scanned (and discarded) as part of the tokenization process, but before parsing. A comment works like a token separator even in the absence of whitespace around it.

As you point out, the C specification explicitly states that comments are replaced by a single space. It is just specification-lingo though, since a real-world parser will not actually replace anything, but will just scan and discard a comment the same way it scans and discards whitespace characters. But it explains in a simple way that a comment separates tokens the same way a space would.

The content of comments are ignored, so linebreaks inside multiline comments have no effect. Languages which are sensitive to line breaks (Python and Visual Basic) usually do not have multiline comments, but JavaScript is one exception. For example:

```<code>return /*
       */ 17
</code>```

Is equivalent to

```<code>return 17
</code>```

not

```<code>return
17
</code>```

Single-line comments preserve the line break, i.e.

```<code>return // single line comment
    17
</code>```

is equivalent to

```<code>return
17
</code>```

not

```<code>return 17
</code>```

Since comments are scanned but not parsed, they tend not to nest. So

```<code> /*  /* nested comment */ */
</code>```

is a syntax error, since the comment is opened by the first /* and closed by the first */

Title: How are comments usually parsed?

Body:
Usually comments are scanned (and discarded) as part of the tokenization process, but before parsing. A comment works like a token separator even in the absence of whitespace around it.

As you point out, the C specification explicitly states that comments are replaced by a single space. It is just specification-lingo though, since a real-world parser will not actually replace anything, but will just scan and discard a comment the same way it scans and discards whitespace characters. But it explains in a simple way that a comment separates tokens the same way a space would.

The content of comments are ignored, so linebreaks inside multiline comments have no effect. Languages which are sensitive to line breaks (Python and Visual Basic) usually do not have multiline comments, but JavaScript is one exception. For example:

return /*
       */ 17

Is equivalent to

return 17

not

return
17

Single-line comments preserve the line break, i.e.

return // single line comment
    17

is equivalent to

return
17

not

return 17

Since comments are scanned but not parsed, they tend not to nest. So

 /*  /* nested comment */ */

is a syntax error, since the comment is opened by the first /* and closed by the first */


答:
To answer the question:

is there a general consensus what is generally expected by a mark up?

I would say none would expect a comment embedded inside of a token to be legal.

As a general rule of thumb, comments should be treated the same as whitespace. Any place that would be valid to have extraneous whitespace should also be allowed to have an embedded comment. The only exception would be strings:

```<code>trace("Hello /*world*/") // should print Hello /*world*/
</code>```

It would be quite odd to support comments inside strings, and would make escaping them tedious!

Title: How are comments usually parsed?

Body:
How are comments generally treated in programming languages and markup? I am writing a parser for some custom markup language and want to follow the principle of least surprise, so I'm trying to determine the general convention.

For example, should a comment embedded within a token 'interfere' with the token or not? Generally, is something like:

```<code>Sys/* comment */tem.out.println()
</code>```

valid?

Also, if the language is sensitive to new lines, and the comment spans the new line, should the new line be considered or not?

```<code>stuff stuff /* this is comment
this is still comment */more stuff
</code>```

be treated as

```<code>stuff stuff more stuff
</code>```

or

```<code>stuff stuff
more stuff
</code>```

?

I know what a few specific languages do, nor am I looking for opinions, but am looking for whether or not: is there a general consensus what is generally expected by a mark up in regards to tokens and new lines?

My particular context is a wiki-like markup.

Body:
To answer the question:

is there a general consensus what is generally expected by a mark up?

I would say none would expect a comment embedded inside of a token to be legal.

As a general rule of thumb, comments should be treated the same as whitespace. Any place that would be valid to have extraneous whitespace should also be allowed to have an embedded comment. The only exception would be strings:

trace("Hello /*world*/") // should print Hello /*world*/

It would be quite odd to support comments inside strings, and would make escaping them tedious!


答:
In whitespace-insensitive languages, ignored characters (i.e. whitespaces or those that are part of a comment) delimit tokens.

So for example Sys tem are two tokens, while System is one. The usefulness of this might be more apparent if you compare new Foo() and newFoo() one of which will construct an instance of Foo while the other calls newFoo.

Comments can play the same role as a run of whitespaces, e.g. new/**/Foo() works the same as new Foo(). Of course this can be more complex, e.g. new /**/ /**/ Foo() or whatnot.

Technically, it should be possible to allow comments within identifiers, but I doubt it is particularly practical.

Now, what of white-space sensitive languages?

Python comes to mind and it has a very simple answer: no block comments. You start a comment with # and then the parser works exactly as though the rest of the line didn't exist but were just a newline instead.

In contrast to that, jade allows for block comments, where the block ends when you get back to the same indentation level. Example:

```<code>body
  //-
    As much text as you want
    can go here.
  p this is no longer part of the comment
</code>```

So in this realm, I wouldn't say you could say how things are usually handled. What seems to be a commonality, is that a comment always ends with an end-of-line, which means that all comments act exactly the same as new lines.

Title: How are comments usually parsed?

Body:
In whitespace-insensitive languages, ignored characters (i.e. whitespaces or those that are part of a comment) delimit tokens.

So for example Sys tem are two tokens, while System is one. The usefulness of this might be more apparent if you compare new Foo() and newFoo() one of which will construct an instance of Foo while the other calls newFoo.

Comments can play the same role as a run of whitespaces, e.g. new/**/Foo() works the same as new Foo(). Of course this can be more complex, e.g. new /**/ /**/ Foo() or whatnot.

Technically, it should be possible to allow comments within identifiers, but I doubt it is particularly practical.

Now, what of white-space sensitive languages?

Python comes to mind and it has a very simple answer: no block comments. You start a comment with # and then the parser works exactly as though the rest of the line didn't exist but were just a newline instead.

In contrast to that, jade allows for block comments, where the block ends when you get back to the same indentation level. Example:

body
  //-
    As much text as you want
    can go here.
  p this is no longer part of the comment

So in this realm, I wouldn't say you could say how things are usually handled. What seems to be a commonality, is that a comment always ends with an end-of-line, which means that all comments act exactly the same as new lines.


问:
Is there a convention for where to store crash-recovery files?
I work on an application where we have the potential to attempt a file save in the top-level exception handler. The intention would be save a file which can then be sent into the support team, validated for corruption, and restored as far as possible. (We have a small enough customer base to work like this.)

Is there a convention for where to store such a file? I've seen %APPDATA%/Local/Temp used for one program - is that a mainstream idea, or just a one-off? Or would it be entirely up to me? Ideally, the user will be able to retrieve this file themselves. (AppData is normally hidden by default, I think?)

答:
The flaw with using [user]/AppData/Local/Temp is that it's a location that users (and tools) will delete to free hard drive space.  If you want these files to stay around, I would avoid using Temp.

If you look at your %APPDATA% folder, you'll see that a common convention to use is %APPDATA%/[Vendor]/[Application] for any user specific data that an application wants to save.

For example, I have:

%APPDATA%/Microsoft/Office

%APPDATA%/JetBrains/Resharper

%APPDATA%/Adobe/Acrobat


问:
Login using email or username?
Is registration login using email a better idea than username to identify the user?</p>

答:
Email definitely. Look, users already have it bad enough with a bajillion user/pass to remember for other sites. Most sites do use the Email Address for the username, so just go with that and make your users life easier...

OpenID ftw... if your willing to invest time to get it setup, I think there is $$ involved to but I could be wrong?

Title: Login using email or username?


问:
How to avoid the LoadBy pattern?
In our codebase for a sophisticated system controlling many aspects of businesses, we have a certain unwritten law to not fudge around in code with complicated SQL, instead writing it into a function in the entity's class to centralize the database access, and this great pattern turned into pages and pages of

```<code>class Car:
    List<Car> LoadByManufacturerId(id);
    List<Car> LoadByModelId(id);
    List<Car> LoadByCountryId(id);
    List<Car> LoadByCityId(id);

    Car LoadByChassis(chassis);
    Car LoadById(id);
    Car LoadByCountryIdAndChassis(countryId, chassis);
    Car LoadByPersonIdAndIndex(personId, index);
</code>```

As in, everytime someone needs to make a query by a new parameter, a new method is created, but that's only half the problem: Many times people don't take the time to look at the code before creating one of these (documentation is non-existant) and end up creating multiple versions of the query under the same name, duplicating code all around.

We're in a C# project, but many of the devs don't understand much LINQ beyond basic from s in tablename where blabla select s, so what is the best way to refactor this pattern into something not so prone to these kind of problems with the minimal friction?

答:
If you're writing a repository, your repository methods should be structured around business processes, not CRUD methods.

Writing Linq instead of these methods is not all that difficult, and you can combine conditions.

```<code>var result = Cars.FirstOrDefault(x => x.ManufacturerID == manufacturerID
      && x.ModelID == modelID);
</code>```

Further Reading

P of EAA: Repository

The Repository Pattern

Title: How to avoid the LoadBy pattern?

Body:
If you're writing a repository, your repository methods should be structured around business processes, not CRUD methods.

Writing Linq instead of these methods is not all that difficult, and you can combine conditions.

var result = Cars.FirstOrDefault(x => x.ManufacturerID == manufacturerID
      && x.ModelID == modelID);

Further Reading

P of EAA: Repository

The Repository Pattern


问:
killing / SIGTERM for Node.js child_process
With regard to a child process in Node.js that is created like so:

```<code>var cp = require('child_process');
var n = cp.fork('child.js');
</code>```

When forking a child_process with Node.js is it proper to kill the child process when it's done with it's work?

At the moment my guess is that if you don't kill the process that it stays idle and just uses up resources unnecessarily, but I am not clear on this.

答:
You can either exit from inside the child process using process.exit(0) (note that 0 can be replaced with other code), or you can kill it from the parent process, in your example n.kill();

I assume you would want to kill it from inside the script, since there you would have the context to know when the job is done.


问:
How to get up to speed and be productive when joining new projects
this is a problem I've been struggling a bit with. I often get brought along to join projects to help out with development. The problem is, a lot of times I'm assigned to fix bugs, implement new features, etc but I find myself lost in a large code base. I don't know which file is doing what; which functions are being called or used; which best practice is preferred and etcetera....

I feel like I'm walking into a big mansion and expected to figure where the owners put their screwdrivers, hammers, and nails; what did they to fix their broken plumbing; what brand of paint they used to paint their tiles; you get the general idea.

Not all devs / tech leads provide adequate documentation. More often than not, there is no documentation / diagram to show how the app is supposed to work. Even worse, some devs / tech leads are not around, either because they quit or because they are taking an extended vacation. With that said, what are some tips & advice on how to become productive and writing code as quicky as possible?

答:
Simply put: nothing you do will speed up the process of learning the ins and outs of a complex (and often un- or badly- documented) system. All you can do is make the process easier for yourself.

I tend to pick up bugs and try to work my way through fixing them with the help of a debugger - so first priority for me is to get my dev environment set up so it all works and I know where things are. Then I can poke around and see the calls going on in the debugger which often is all I need. I'll also write down sequence diagrams of the major calls that are going on to help me remember.


答:
Tool similarity. Is the team using tools you already know or do you have to learn plus the code base itself?

Learning styles. Are you a hands-on learner, someone that can easily read and then apply at an abstract level or do you like to listen to instructions? Different styles can mean different approaches to my mind.

Pattern recognition. How well can you spot patterns in code? How well could you see conventions and styling guidelines used? This can also help in figuring out code at times.

Sometimes it helps to get the basics resolved first as well as to go step by step through a process rather than trying to fly in at the 11th hour.

Title: How to get up to speed and be productive when joining new projects

Body:
this is a problem I've been struggling a bit with. I often get brought along to join projects to help out with development. The problem is, a lot of times I'm assigned to fix bugs, implement new features, etc but I find myself lost in a large code base. I don't know which file is doing what; which functions are being called or used; which best practice is preferred and etcetera....

I feel like I'm walking into a big mansion and expected to figure where the owners put their screwdrivers, hammers, and nails; what did they to fix their broken plumbing; what brand of paint they used to paint their tiles; you get the general idea.

Not all devs / tech leads provide adequate documentation. More often than not, there is no documentation / diagram to show how the app is supposed to work. Even worse, some devs / tech leads are not around, either because they quit or because they are taking an extended vacation. With that said, what are some tips & advice on how to become productive and writing code as quicky as possible?


问:
the future of commercial products
I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>

答:
I think what you really mean is proprietary products. There are a great many commercial and open source products on the market.

Barring some kind of idealistic unification in world cultures, I think that the law of supply and demand will continue to hold. If your product is proprietary but more feature rich and stable than free / open source products, you will continue to find a market for decades to come.

I think the trend will start to shift when it is 'safe to assume (tm)' that most computer users are also somewhat knowledgeable when it comes to programming. I don't see that happening for generations, however.

Right now, most computer users (perhaps I'm dangerously generalizing here, forgive me if I am) want to share their programs. When people begin demanding that they be able to modify their software to do what they want it to do with the same enthusiasm that sharing received, well ... we'll see.

I also think we have yet to see the tip of the iceberg when it comes to what SAAS is going to do to market wide.

In short, I predict that the innovation that we'll see over the next 60 years will pale only in comparison to the subsequent litigation that results. Your question comes into play when software is not designed in a court of law.

Title: the future of commercial products


答:
I don't think there is good technical solution. I would always recommend a Query pattern, but that just shifts the problem from "add method" to "add class", albeit in OCP way.

So only possible option is people solution. If people don't understand LINQ, then teach them. Have a weekly or even daily trainings on how to use LINQ. Motivate them to learn it themselves and try it. Identify people who understand it and who will be ready to help others if they don't understand anything. Do a code review of DB code, so duplicates can be identified. Pick people who will be responsible for DB code and who will roam the codebase, fixing, deduplicating and refactoring code. Motivate people to look for existing solution before they add their own.

Title: How to avoid the LoadBy pattern?

Body:
In our codebase for a sophisticated system controlling many aspects of businesses, we have a certain unwritten law to not fudge around in code with complicated SQL, instead writing it into a function in the entity's class to centralize the database access, and this great pattern turned into pages and pages of

```<code>class Car:
    List<Car> LoadByManufacturerId(id);
    List<Car> LoadByModelId(id);
    List<Car> LoadByCountryId(id);
    List<Car> LoadByCityId(id);

    Car LoadByChassis(chassis);
    Car LoadById(id);
    Car LoadByCountryIdAndChassis(countryId, chassis);
    Car LoadByPersonIdAndIndex(personId, index);
</code>```

As in, everytime someone needs to make a query by a new parameter, a new method is created, but that's only half the problem: Many times people don't take the time to look at the code before creating one of these (documentation is non-existant) and end up creating multiple versions of the query under the same name, duplicating code all around.

We're in a C# project, but many of the devs don't understand much LINQ beyond basic from s in tablename where blabla select s, so what is the best way to refactor this pattern into something not so prone to these kind of problems with the minimal friction?


问:
What does it mean to build from source?
I'm trying to install numpy using this. This link opens with these instructions:

These instructions describe how to build NumPy and SciPy libraries from source.

If you just want to use NumPy or SciPy, install pre-built binaries as described in Installing the SciPy Stack.

If I'm not wrong, to "build" generally means to compile files into machine readable ones and then group them into an executable. From the expression "build from source", I infer that, firstly, there are multiple ways to build a file and, secondly, this particular way builds the file from its source code.

If this is true, is a pre-built binary a set of files that have already been compiled?

答:
In general, the 'from source' part of 'build from source is redundant, though it is a commonly included redundancy.

However, it is entirely plausible (though very rare, if it happens at all) to build from a non-source format. For example, one could compile to C source code to LLVM IR and distribute that. Users would then compile the LLVM IR to their target architecture. This could provide an architecture-independent format to distribute, while also obfuscating the actual code.

is a pre-built binary a set of files that have already been compiled?

Yes, generally this means compiled into an executable format or linkable library (as opposed to an intermediate format like above).

Title: What does it mean to build from source?


答:
If I'm not wrong, to "build" generally means to compile files into machine readable ones and then group them into an executable.

Basically yes, though the term is a lot more general than that. For instance, the machine readable files might be libraries rather than executables. Or the output might be a set of scripts designed to run on a VM of some kind rather than a blob of native machine code. The key thing is that it's an automated process which transforms "source" files edited by humans into some other files which are actually useful.

From the expression "build from source", I infer that, firstly, there are multiple ways to build a file and, secondly, this particular way builds the file from its source code.

Usually when this phrase is used, it's referring to building something from source as opposed to using a pre-built version of it. There is no "other way" to build stuff that does not involve source, unless the build process has been split into multiple stages and for some reason you're only involved in one of those stages.

If this is true, is a pre-built binary a set of files that have already been compiled?

In the context of a traditional, ahead-of-time compiled language such as C or C++, that is correct.

Title: What does it mean to build from source?

Body:
I'm trying to install numpy using this. This link opens with these instructions:

These instructions describe how to build NumPy and SciPy libraries from source.

If you just want to use NumPy or SciPy, install pre-built binaries as described in Installing the SciPy Stack.

If I'm not wrong, to "build" generally means to compile files into machine readable ones and then group them into an executable. From the expression "build from source", I infer that, firstly, there are multiple ways to build a file and, secondly, this particular way builds the file from its source code.

If this is true, is a pre-built binary a set of files that have already been compiled?


答:
As you have already found, building from sources generally implies going from the source form (i.e. non executable, not usable) to the final form of something (an executable program, but even a shared library has a binary form).

But there's usually not more than one way to build something: you may skip steps, e.g. when something depends on something else, you may get those dependencies already compiled from elsewhere - or like this case you may get the precompiled binaries.

Yes, a pre-built binary is the final product which components have already been compiled - this holds true for an executable as a shared library.

Title: What does it mean to build from source?


答:
There isn't enough developers in the world to develop all the software companies need worldwide.

There is a lot of room for both commercial and FOSS.

The future of commercial software is not compromised. It will just evolve. Just like music and news market.

Natural selection will occur as usual. Only species (companies) which adapt to their environment (the market) will survive. The ones will strong resistance to change will eventually die.

Title: the future of commercial products

Body: I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>


问:
Is it a good idea to make method behavior depend on the calling thread?
I want to subclass a 3rd party class, in order to make it thread-safe.

I have a good idea of how to implement this, but there is a problem: the superclass has a property, which affects the behaviour of one of its methods. If one thread sets the property, it will interfere with the other threads when they call the method.

I can see two ways to do this:

Create a thread-safe 'stateless' object which then has multiple 'views' into it. The property is in the view and each thread has its own view instance.

Detect which thread makes the call in the property's get accessor and the method, and store the state for that thread internally.

(1) is self-explanatory, but it involves more boilerplate code. (2) does something non-trivial behind the scenes, but if it works, it is completely transparent.

Which is best, for maintainability and readability? The more complex code but whose behaviour is up-front, or the code which is easier to use when it works, but if it breaks it will do so in a location and way which is not obvious?

Is there any reason an object should not be dependent on what thread interacts with it?

(EDIT: Removing reference to the 3rd party class, since the requirements of the implementation are not as simple as it sounds and it was generating more confusion than needed!)

答:
Stating the obvious, creating a synchronized stream is just-about completely pointless1.

It isn't that you cannot ensure the steams internals aren't mangled by multi-threading, that's actually really easy.

The problem comes from the fact that just almost all code relies on implicit exclusive access to the stream to ensure that conceptually atomic pieces of output aren't arbitrarily interrupted and interrupting each other, which will make the output flat-out useless.

If multiple threads can access the same thread, they rely on you, the programmer, sensibly synchronizing access in logical units anyway.

Regarding the exceptions, that's for the few times when either you ensure that output will be moved to the stream in logical units (everyone being on-board with it, or you using a forwarding stream which will not ever auto-flush), or things are so broken you can only write your error-message, hope for the best, and abort anyway.


问:
Rest api with a hello resource / main entry point
I'm designing a Rest API for our web application.

There's one idea that came to my mind today and I haven't found in recent searches: a "hello" resource, where clients are supposed to connect as the first step; it should be like the "entrance" to the whole service.

The main reason is to have a defined point where I can attach server-side logging logic; it could tell the whole application state, so that clients do not try to access several other resources that would fail; theoretically it could return a reader token that allows requests toward resources to be successful for anonymous clients.

That's almost it, quite an initial shape of idea instead of a complete one, but the idea appeals to me.

What do you think about it?

答:
Your question is complicate to answer, as a lot of persons doesn't agree about what is really a REST API. The only authorative - but unfortunately "too conceptual" - answer is the Roy Fielding's PhD thesis. So depending on your needs, you will adhere to different degree of the REST principles.

What is the requirements of your clients ? Do you need really to fulfill the 3 levels of maturity of REST ? Especially the third, that involve for a client to do more request to build its own application state (rather than "hardcoded" URIs that have also some benefits!)

Let's say, that you want to adhere strictly with REST following with verbs, resources and HATEOAS stuff.
The first step is to create a main entry point that will be the starting point of your client.
A client that retrieve this main entry point through a resource, will have some links that redirect to your differents resources (which resources you put depends on your software architecture!). Here, you will probably have a link to the hello resource.

I didn't get why you need a reader token, but token are a common practice to have a kind of "stateless" permission as your server doesn't store any information about the client, because the token is held by clients.

You should also note that if you start to deal with HATEOAS, it will requires to have hypermedia format. JSON is not an hypermedia format, there isn't any notion of links in this format. But it exists a lot of hypermedia format (Siren, HAL, Hydra, etc...) that have been proposed.


问:
Should http requests be in the constructor or in a static function?
Which is conventional? For example, this is in the constructor:

```<code>public class Foo {
...
    public Foo(...) {
        // http requests
    }
...
}
</code>```

and this is in the static method:

```<code>public class Foo {
...
    public Foo(...) {
        ...
    }

    public static Foo get(...) {
        // http requests
        return Foo(...);
    }
...
}
</code>```

Are there any advantages/disadvantages to either one? (threading, speed?)

答:
There is a general consensus that a constructor shouldn't ever throw an exception in Java. It can cause a mess with trying to recover from the new.  You can, but its one of those "try to avoid it if it can be done in a sensible way."

To that extent, the static Builder (that you call get(...)) is probably a better approach to follow. That allows you to properly build and dispose/close the resources for invoking http and handle the exceptions (what if this request fails? or that next one?)

With a Builder approach, one should consider making the constructor private so that you can guarantee that the state of Foo is properly constructed by the get(...) method, if it is constructed at all.

For threading and speed? There is really no difference. It is entirely an issue of making sure that exceptions are thrown in a non-surprising circumstance and any resources (the web requests) are properly closed in the event something goes wrong.


问:
Working with local connections instead of global
In recent weeks I became very concerned that the way I've been working with database connections for the past years, is simply wrong.

I exclusively create a new connection for each database operation I have to perform. only in the more complex programs, I would stack several tasks (Sql commands) in the background and then every few seconds I would  create a new single connection, and execute these with the same connection.

Here is typical sample:

```<code>     SqlConnection connection = new SqlConnection(con);
            SqlCommand command = new SqlCommand(@"
            DECLARE @Pk TABLE (Id int)
            INSERT INTO Petrol.Reports(
            [TimeStamp])
            OUTPUT INSERTED.Id INTO @Pk
            VALUES(
            @TimeStamp)

            SELECT Id FROM @Pk", connection);
            command.CommandType = CommandType.Text;

            SqlParameter parameter = command.Parameters.Add("@TimeStamp", SqlDbType.DateTime);
            parameter.Value = this.TimeStamp;

            using (connection)
            {
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        this.Id = reader.GetInt32(0);
                        Ref.Petrol_ReportsById[Id] = this;
                    }
                }
            }
</code>```

Recently I started working with PostgreSQL and I was freighted to see that it creates a new process for almost every connection I create.

The deal is that most code samples around are using very similar approach, but I'm afraid that this is just to keep things simple.

I consider re writing my objects generating tool to share a single connection between all operations (with thread safety in mind), would this be a correct approach in your opinion?

答:
I consider re writing my objects generating tool to share a single connection between all operations

Your current code works, and if it works fast enough, why do you want to fix something which is not broken?

Only if some code of yours has some noteable or measurable performance problems, and you know opening and closing the connections too often is the cause, you should consider to rewrite it in the described manner. Do not optimize just for the sake of optimization.