问:
Why are the  and  tags deprecated?
This question came up in one of my college classes. The professor only gave the answer that it was more descriptive, but it seems as though  and  are rather explicit in their meaning and is easier to type than  and .

What were the official arguments for the deprecation of these tags?

答:
Last summer, I read the complete HTML5 specification, and every previous HTML specification (even the abandoned ones), and all CSS specs I could find, and a lot of XML specs. Since I love semantically rich hypertext documents, let me give you the idea behind the relevant HTML semantics in HTML5.

Before HTML5

Before HTML5, i and b were indeed out of fashion. The reason was that they essentially worked like em and strong, respectively, but with focus on presentation and not on semantics (which is bad).

Indeed, i meant that the text should be in italics (it said something about how the text should be rendered on-screen). On the other hand, em meant that the text was to be emphasised (it said something about the semantics of the text).

There is an important theoretical difference here. If you use em, the user agent (=browser) knows the text should be emphasised, so it can render it in italics if the document is displayed on-screen (or all-caps if formatting is not possible, or maybe even in boldface is the user prefers that), it can pronounce it differently if the document is spoken to the user, etc.

Notice that emphasis really is about semantics. For instance, the phrases

The cat is mine. (=not the dog!)

The cat is mine. (=not yours!)

do not have the same meaning.

The same difference applies to b (boldface font) and strong (strong emphasis).

A general principle of digital writing in general, and of hypertext authoring in particular, is that you should separate content and style. In hypertext authoring, this means that the content should be in the HTML file, and the style should be in a CSS file (or a number of CSS files). A different but related principle is that the document should be rich in semantics (like marking up headers, footers, lists, emphases, addresses, navigational areas, etc.). This has a number of advantages:

It is much easier for computer programs to interpret the document. These programs include browsers, text-to-speech applications, search engines, and digital assistants. (For example, the browser can let you save an address to your address book, if only it can find and interpret it. Also, you might know that Microsoft Word can create and automatically update a TOC for you if you mark up your headings correctly.)

It is much easier to change the style later on. (If you want to change the colour of all your third-level headings in your 860-page document, you can change a single line in the stylesheet. If you had mixed content and presentation, you would have to go through the entire document manually. And you would probably miss a heading or two, making the document look unprofessional.)

You can use different stylesheets depending on the circumstance (is the document being displayed on-screen or printed on paper?). You can even let the end user choose the style herself. (My website offers a number of alternate stylesheets. In IE and FF, you change these using the View menu.)

So, in short, i and b were deprecated because they were HTML tags concerned about presentation, which is totally wrong.

In HTML5

In HTML5 i and b are no longer deprecated. Instead, they are given sematic meaning. So they are now actually about semantics, and not about presentation.

As before, you use em to mark up emphasis: "The cat is mine." But you use i for almost all other cases where you would use italics in a printed work. For instance:

You use i to mark up taxonomic designations: "I like R. norvegicus."

You use i to mark up a phrase in a different language compared to the surrounding text: À la carte

You use i to mark up a word when you talk about the word itself: "drink is both a noun and a verb"

It is also a good idea to use the class attribute to specify the precise usage (also Google "microformat" and "microdata"). And, of course, in the second case, you should really use the lang attribute to specify the correct language. (Otherwise, for instance, a text-to-speech agent might mispronounce the text.)

A year ago or so, the HTML5 specification also said that cite should be used to mark up names of books, films, operas, paintings, etc.:

What do you think of Nymphomaniac?

Finally, since long ago, dfn is used to mark up the defining instance of a phrase in a text (like a mathematical definition, or the definition of a term):

A group is a set X equipped with a single binary operation * such that...

So the italics in your printed book, which can mean a lot of different things, is represented by four different HTML5 tags, which is really great, because semantics is good, as I tried to convince you about earlier. (For instance, you can ask your browser to make a list of all definitions in the text, so you can make sure you know them all before the exam.)

Turning to strong and b, the HTML5 specification says that strong should be used to mark up an important part of the text, like a warning or some very important-to-catch word in a sentence. On the other hand, b should be used to mark up things that need to be easy to find in the text, like keywords. I also use b as headings in list items (LIs).

Title: Why are the <b> and <i> tags deprecated?


问:
Has research been done on the effectiveness of Planning Poker as an estimation technique?
Although it is a commonly held opinion that planning poker improves the accuracy of project estimations (a small sample of which demonstrated on this question), has any defined research been done on the subject?

More specifically, I am looking for non-circumstantial information showing that planning poker would be an improvement over traditional estimation techniques.

答:
A story from my experience.

When our team started - we were using planning poker by Mountain Goat. Since our team was distributed among 2 cities, we were short on options for estimation methods. As for the tool itself — it was Planning Poker 3.0 JIRA Add-On

Thus, as our team was growing (in size of members and in terms of experience), we found out that the planning poker does not fulfil our needs anymore. Due to the scattering factor of team members, due to issues from different projects that have to be estimated during the same meeting, due to inefficiency for estimating large piles of stories - we switched from this method to another - the Team Estimation Game by Steve Bockman.

This method worked well for us, though the preparation time for a session increased (we didn't have a proper tool with the "online multiplayer" solution) - our scrummaster used Google Docs for preparing an estimation session.

ContentLicense: CC BY-SA 3.0


问:
Accepting the UUID collision risk based on number of clients
After reading some questions about the probability of UUID collisions it seems like collisions although unlikely, are still possible and a conflict solution is still needed. Therefore I am wondering about the background of choosing UUIDs for CouchDB

Is the "unlikely collision" a responsibility of the developer?

Was it expected that IDs will be used by a reduced set of clients?

When I went through the documentation it looked like CouchDB algorithm was great to withstand partition, but the more I read about the problems of distributed ID generation, the more I believe taking the UUID collision risk is only feasible with a low number of clients.

Although I am still interested in the previous questions, the main thing I want to find out is:

Is it the normal practice accepting the collision risk of UUIDs counting on a low number of distributed generators? Or always assumed that the probability of collision is so low that is not a concern?

答:
I've just got very little experience with CouchDB, but there is a suffix you can configure for the utc_id algorithm, starting in version 1.3 utc_id_suffix

In general, I trust random generators when they have a unique origin (e.g. one instance of CouchDB), but not really when they're being generated from different sources and with the same algorithm and format (e.g. replicating instances of CouchDB). This also applies to processes and threads depending on the scope. With the exception of having a mechanism to differentiate specifically each random sequence origin like the suffix above.


问:
How to avoid model duplication in JavaEE web applications with a JSON front end
Recently we developed a web app that uses the following tech stack:

hibernate as orm

spring

extjs (MVC javascript front end)

For 1 business object, let it be a Personnel, we have:

1) a Personnel class (hibernate)
2) PersonnelDTO (will explain why we needed this)
3) a Personnel javascript model for Extjs (I don't know may be other javascript UI frameworks does not need a model defined)

Need for number 2 arised when we couldn't deal with sending hibernate objects back and forth, dealing with sessions and circular references etc. etc.

Plus, in some cases you need a fully filled Personnel object (full fields joined), sometimes just a few fields and a relation. Sometimes you need all the info to process a Personnel but you can't send it all the way to the client (security, privacy reasons). So we used DTO's to decouple model objects and objects that will be sent through the wire.

Adding-removing a field in such a project design becomes very tedious and error prone. Adding a field requires:

add to DB tables

add to model object

add to DTO

add to model -> DTO converter (when it's a field that can't be automatically mapped) regarding different scenarios that requires different amount of information about model

add to Extjs model

add to CRUD forms on the page

add to client and server validators...

Isn't there a better approach to building similar applications? We are thinking of starting a new project and don't want to make the same mistakes.

答:
Isn't there a better approach to building similar applications?

I am working on a mid-sized project (150k LoC), with a similar setup:

Spring 4

OpenJPA for persistence

jQuery as the only frontend "framework". I introduced Backbone.JS which is only halfheartedly adopted. A good deal of our application is grid over data, which is implemented via datatables.net.

We are facing similar problems.

In general, there is only little to no help for that.
If you are using ORM, you have to use the @Entity-POJOs.
If you do not want to expose these objects to the outside, there aren't many options:

1) As you already do: use DTOs - but there is the disadvantage of mapping fields and keeping fields in sync
2) Instantiate a new Domainobject - as said above: @Entities are POJOs and copy over those fields, you want to expose.

Some of our application is grid over data, so there isn't always the need for fully fledged domain objects and sometimes you need a bunch of attributes from several objects. For such cases there is the possibility to work with Constructor expressions in the SELECT clause (see specification). So you could build aggregate-objects (or however you want to name these DTOs) which could span across multiple tables and where each attribute is associated to one column of your resultset. In this case the new object isn't necessarily an @Entity. It has to provide only a constructor which takes all of the columns. (Note to myself: try this out for @Entities).

add to model -> DTO converter (when it's a field that can't be automatically mapped) regarding different scenarios that requires different amount of information about model

This would be best solved via reflection: copy over all fields in the new object from the old one. Done.

The following is highly subjective:

I find ORM isn't the perfect fit for our project. It is a nice to have which frees you from writing tedious boilerplate code, but comes with several downsides: performance trouble (objects involve multiple _LEFT JOIN_s, which you wouldn't need nor make, when writing SQL), too much overhead for simple queries (you get full objects restored instead of just 2 columns or so needed), problems with joins (you are only allowed to join tables, which reflect your models - otherwise, you have to use tricks to get around). If I would start over, I would take a mixed approach: ORM for simple stuff and doing complex stuff with JDBC-templates (our project is currently 100% ORM-Driven).

That said, we now have to take a look at the frontend:
Since the advent of MV*-frameworks on the client-side, the question rises, where to put the stress on: client-side vs server-side validation or using both. Here is a nice talk from yeahuda Katz about »the tale of the two MVCs«.

If you go the client-side road, you haven't a duplication of "models", you have client-side-models and "persistence-objects" (@Entities)

To sum it up:

some painpoints stay: add to DB tables, add to model object, (add to DTO), add to Extjs model

some could be made easy: add to model -> DTO converte (use reflection)

you could decide on an either-or-base for some: add to client and server validators

Modern applications are complex.


问:
Creating a web app that authenticates users from two different databases
I am in a bit of an awkward programming situation, and it will help me a lot to get your input in this situation.

I am building a web app which expects to authenticate users from another, separate application (through API calls), and also authenticate users from it's own database. Essentially, there are two separate user bases.

Let's say the app I'm building is App1, and the other app which I'm making API calls to is App2. This communication is only one-way; App1 makes API calls to App2, but App2 does not make calls to App1. Users can register in App1 and create an account in App1's database - but during this process, App1 makes an API call to App2 to make sure the email/username being entered into App1 is not already present in App2.

Now, the other side of this. If a user is already registered in App2, they do not need to go and register again in App1. They can simply go to App1 and log in. In doing so, App1 sends an API call to App2 to authenticate the user, and creates a copy of the App2 user's account in it's own (App1) database.

Problems arise when there are two distinct users, one in App1, and the other in App2, that share the same username. Now, when the App2 user attempts to log into App1, there will exist two users in App1 with the same username! How can a scenario like this be avoided? Is this even a place I want to be (working with App2's user base)?

答:
There are two ways in which two distinct users sharing the same name (XYZ) may come to exist in both apps.

First situation:

User XYZ already exists in App2.

Another user also named XYZ, but not the same person, tries to register in App1 but gets authenticated in App2 first, because somehow the password happens to be the same of App2's XYZ user, and a copy of the account is created in App1.

Second situation:

User XYZ already exists in App1.

Another user also named XYZ, but not the same person, registers in App2 and, since there's no communication from App2 to App1, the creation of such a user succeeds.

The first situation is very hard to come by. If App2 demands the password to be non-trivial, the possibilities of two users creating the exact same password is small.

The second situation is very probable. In that case when App1's XYZ user tries to login, the authentication against App2's database will fail because passwords don't match and the user will not be able to register in App1.

Possible solution

First find out what's the unique identifier of users in App2. Is it the username? Is it an email address ?

If it's an email address, being an email address an externally generated ID that can't repeat, you should also make the email address and not the username the identifier in App1.

If it's username that provides unicity in App2, then we are out of luck. Since you have no control of App2, you can't possibly prevent a distinct person from creating an account with the exact username that exists on an unrelated application.

Find out if App2 uses a 3rd party authentication authority ( see bellow ) and adopt it yourself.

The only way to make such interoperability is making both App1 and App2 resort to a 3rd party to generate identity. An example of that is using an mail address as identifier ( users need access to the email address to successfully register since a link to complete the registration is sent to that address ), or using Facebook or Goole like StackExchange does, or another provider of centralized authentication.

If nothing of the above applies, and since App1 is using App2 as authentication authority without App2 knowing, and since you don't have control over App2, then you such re-consider the whole relationship with App2.


问:
What does this function do?
Does this function means its calculating x=(x-1) + x^2?</p>

```<code>Function unknown(x)
  if ( x == 1 )
    return 1
  else
    return unknown(x‐1) + x*x
</code>```

答:
The function can be written in a more mathematical form as:

```<code>unknown(1) = 1
unknown(x) = unknown(x - 1) + x * x    [if x is not 1]
</code>```

To see why this is the same as the sum of squares, you can substitute the second line into itself recursively and observe the pattern that emerges:

```<code>unknown(x) =                                         unknown(x - 1) + x * x
unknown(x) =                     unknown(x - 2) + (x - 1) * (x - 1) + x * x
unknown(x) = unknown(x - 3) + (x - 2) * (x - 2) + (x - 1) * (x - 1) + x * x
etc ...
</code>```

After expanding several times, you find that eventually* you will reach the special case of unknown(1) since the argument is steadily decreasing by one at each expansion.  Hence,

```<code>(after expanding many times ...)
unknown(x) = unknown(1) + 2 * 2 + ... + (x - 1) * (x - 1) + x * x
unknown(x) =         1  + 2 * 2 + ... + (x - 1) * (x - 1) + x * x
</code>```

Hence, this is simply the sum of squares.

[*] Unless your initial x is less than one, in which case the function diverges (never terminates) since the argument will just keep becoming more and more negative.

Title: What does this function do?

Body:
The function can be written in a more mathematical form as:

unknown(1) = 1
unknown(x) = unknown(x - 1) + x * x    [if x is not 1]

To see why this is the same as the sum of squares, you can substitute the second line into itself recursively and observe the pattern that emerges:

unknown(x) =                                         unknown(x - 1) + x * x
unknown(x) =                     unknown(x - 2) + (x - 1) * (x - 1) + x * x
unknown(x) = unknown(x - 3) + (x - 2) * (x - 2) + (x - 1) * (x - 1) + x * x
etc ...

After expanding several times, you find that eventually* you will reach the special case of unknown(1) since the argument is steadily decreasing by one at each expansion.  Hence,

(after expanding many times ...)
unknown(x) = unknown(1) + 2 * 2 + ... + (x - 1) * (x - 1) + x * x
unknown(x) =         1  + 2 * 2 + ... + (x - 1) * (x - 1) + x * x

Hence, this is simply the sum of squares.

[*] Unless your initial x is less than one, in which case the function diverges (never terminates) since the argument will just keep becoming more and more negative.


问:
How does one learn QA?
When starting to learn programming you would usually point someone over to Code Academy, or Learn Python the Hard Way or even The C Programming language and tell them start writing code until it works.

But how would one proceed if he wants to learn QA?

More specifically, a programmer who wants to learn about the QA process and how to manage a good QA methodology. I was given the role of jumpstarting a QA process in our company and I'm a bit lost, what are the different types of testing (system, integration, white box, black box) and which are most important to implement first? How would one implement them?

答:
There are simple rules of thumb.

Try what the manual says. Install and run on a clean target, user license, the works. Does it work? Did you have to add anything not covered in the manual?

Are all the default control values usable? Or is there something that's wrong, or blank, by default and always has to be changed?

Set every value in the user interface to something other than its default. Can you detect a difference caused by the change? Is it correct? Do them one at a time, or in the smallest sets possible, to make the results clear.

Set every value in the user interface to a second, non-default, value. Change everything at once. Can you detect the difference? Is it correct?

One by one, do something to cause every error message to be generated. Do something similar, but correctly, so that no error message is generated.

All of the above depend on changing a condition, between an "A" case and a "B" case, and that change having a detectable result. Then the "C" case produces another change, another result, and so forth. For 10 tests, you need 11 conditions. Using defaults as much as possible is a good first condition.

By now you've got a list of things to test, that you recorded, and results, that you recorded, and maybe some new bugs. Throw something big and complicated at the solution. Give it a file of 173000 words to sort, paste a Jane Austin novel or some telecommunications standard 100 pages long, a 50MB bitmap graphic, 3 hours of streaming video. Open the performance monitor and get CPU-bound, or I/O bound. For an hour. Check memory use: always increasing? Rises and falls?

Take the list of bugs closed in the last week, month, sprint, etc. Check them. All. Are they really fixed?

Keeping track of what to do, how it worked on what version/release/build/configuration, open and closed bugs, what controls have been set or changed, what data, test files or examples have been used, etc. is all part of Quality world. Keep results as tables in a spread sheet, make version controlled backups / saves snapshots.

Someone writing software, or any one creating anything, has an idea of what they're trying to make. The quality process starts with expectations. Requirements, specifications, rules, or another articulation of what's expected. Then there's the solution, the thing offered to perform, assist, enable or automate what's expected. Then there are tests, operations, examples, inspections, measurements, questionnaires, etc., to relate one or more particular solution(s) to (relevant) expectations. Finally, there's an adjustment, compensation, tuning, correction or other positive action that is hoped to affect the solution(s).

When one writes software, one has a goal of it doing something, and to the extent that's expressed, the behavior can be checked. Hello.exe displays "Hello World" on a screen. "2**150" in the Python interpreter displays, "1427247692705959881058285969449495136382746624L". Etc. For small problems and small solutions, its possible to exhaustively test for expected results. But you wouldn't test a word processor just by typing in some words, or even whole documents. There are limits of do-ability and reason. If you did type in all of "Emma" by Jane Austin, would you have to try her other four novels? "Don Quixote" in Spanish?

Hence an emphasis on expectations. Meeting expectations tells you when the solution is complete. My web search for "Learn Quality Assurance" just returned 46 million potential links, so there's no shortage of opinions. Classic books on the subject (my opinion, worth what you paid for it:) include

"Quality is Free" by Philip Crosby

"Zen and the Art of Motorcycle Maintenance" by Robert Pursig

"Managing the Software Process" by Watts Humphrey

"The Mythical Man Month" by Fred Brooks

"Code Complete" by Steve McConnell

Take 5 minutes to read some of the Amazon reviews of those books and you'll be on your way. Get one or more and read them. They're not boring. Browse ASQ, Dr. Dobbs, Stack Overflow. Above all, just like writing software. DO it. Consider the quality of some software under your control. Does it meet expectation? If so, firm hand-shake and twinkle in the eye. Excellent!. If not, can it be corrected? Move to the next candidate.

I like the Do-Test-Evaluate-Correct loop, but its not a Universal Truth. Pick a process and follow it consciously. Have people try the testing, verification and validation steps described in the language manual they use most frequently. Its right there on their desk, or in their phone's browser.

Look at your expectations. Are they captured in a publicly known place? With revision control? Does anyone use them? Is there any point where the solutions being produced are checked against the expectations they are supposed to be meeting?

Look at your past and current bug reports. (You need a bug tracking system. If you don't have one, start there.) What's the most common catastrophic bug that stops shipment or requires an immediate patch? Whats the most commonly reported customer bug? What's the most common bug that doesn't get fixed?

Take a look at ISO 9000 process rules. Reflect on value to your customers/users. Is there's a "customer value statement" that explains how some change affects the customer's perception of the value of the solution? How about in the requirements?

By "the QA process", you could mean "Quality Assurance", versus "QC", "Quality Control"? You might start with the http://www.ASQ.org web site, where the "American Society for Quality" dodges the question by not specifying "Control" (their old name was "ASQC") or "Assurance".

Quality; alone, "assured" or "controlled", is a big idea with multiple, overlapping definitions and usages. Some will tell you it cannot be measured in degrees- its present or not, no "high quality" or "low quality" for them. Another famous claim is that no definition is satisfactory, so its good to talk about it, but avoid being pinned down in a precise definition. How do you feel about it?

Title: How does one learn QA?


问:
Is there a clever way to calculate a mode of an online series without storing the series?
My program's aim is to determine the correct time zone offset (GMT+k) as a series of numbers are fed to it. eg:

-4
+11
1
-4
-4

So, here -4 (the mode of the series) is the correct value.  But this requires storing the series then analyzing it and I do not have enough storage (RAM and FLASH) for this.  The running average can be calculated easily by storing the list size and the sum.  Is there a similar case for finding the mode?

答:
There is a way to do this if the mode will appear at least 50% of the time:

```<code>def mode(numbers):
    mode, count = 0, 0
    for number in numbers:
        if not count:
            mode, count = number, 1
        elif number == mode:
            count += 1
        else:
            count -= 1
    return mode
</code>```

If the mode doesn't have this property, then I can't think of a way other than to use an array of 24 counters, incrementing the correct one for each number encountered (index = number + 11), then looping through keeping track of the index with the largest count. The mode will then be index - 11.

If you can't use an array, then you could multiply in a prime (number += 11; accumulator *= number * (number + 1) + 41) for each number encountered, then compute the prime factorization and keep track of the index of the factor with largest exponent. The mode will then be index - 11. The problem with this is that a 64-bit integer can only store a few primes (8, maybe 10) multiplied together before overflowing.

Body:
There is a way to do this if the mode will appear at least 50% of the time:

def mode(numbers):
    mode, count = 0, 0
    for number in numbers:
        if not count:
            mode, count = number, 1
        elif number == mode:
            count += 1
        else:
            count -= 1
    return mode

If the mode doesn't have this property, then I can't think of a way other than to use an array of 24 counters, incrementing the correct one for each number encountered (index = number + 11), then looping through keeping track of the index with the largest count. The mode will then be index - 11.

If you can't use an array, then you could multiply in a prime (number += 11; accumulator *= number * (number + 1) + 41) for each number encountered, then compute the prime factorization and keep track of the index of the factor with largest exponent. The mode will then be index - 11. The problem with this is that a 64-bit integer can only store a few primes (8, maybe 10) multiplied together before overflowing.


问:
Measure of power other than Turing completeness
I originally tried asking this on StackOverflow, but it was too subjective :-(. I am interested in methods of defining the power of programming languages. Turing completeness is one, but it is almost universally satisfied. What would be nice is to define a measure of power that discriminates among programming languages that are actually in used. For example, can anyone propose a non-subjective method that would discriminate between assembly and Java?

Turing completeness means that a language is maximally powerful in what it can output (which pretty much means it can do anything non-time based in the real world). So if we want to define a stronger measure of power, we need to take another approach. Shortness was suggested in the original question, but this is not easy to define at all. Does anyone have any other suggestions?

答: I'd define how powerful a language is by how productive you can be with it.  A lot of people tend to talk about productivity in terms of writing code quickly, but since the majority of a program's lifecycle is maintenance, not development, a better measure is how easily you can read and debug the code, especially when it's written by someone else.  The most powerful languages are the ones that are easiest to read and maintain.</p>

ContentLicense: CC BY-SA 2.5


问:
What is the difference between a function and a component?
I just listened to Software engineering Radio podcast on components. Their description of components were very vague, they made them sound like lower level versions of functions. I am trying to figure out what components mean in the context of the composite pattern.

What is the difference in purpose between a function and a component?

What does a component have to do with the composite pattern?

Can you describe what a component is by using a funny metaphor? For example, explain how  creating a component like baking an apple pie.

答:
I really don't think that the podcast's discussion of "components" is directly in the context of the composite pattern. They are talking about component-based software engineering. I suppose this is one of the pitfalls of the ambiguity of software development terminology.

But, putting that aside to discuss the composite pattern, there's a nice explanation here, in case you haven't read it.

Basically, in the composite pattern, a Component class is simply a class that provides some abstract functionality. In most real-world use cases, it's a class with an interface to output data, like a post or a message. In ruby, I'll implement a Message class:

```<code>class Message

    def initialize
        @message = ''
    end

    def display
        #abstract
    end

end
</code>```

In the composite pattern, a Leaf is a single entity, that generally displays just one unit of information. In our example, a Single message will simply output the string that it is instantiated with:

```<code>class Single < Message

    def initialize(message)
        @message = message if message.is_a?(String)
    end

    def display
        puts @message
    end

end
</code>```

In the composite pattern, a Composite is an object that can contain other components, whether those components are themselves Composite or simply single Leaves. For our example, I'll create a Multiple message class:

```<code>class Multiple < Message

    def initialize
        @message = []
    end

     def display

        @message.each do |message|

            message.display

        end

    end

    def add (message)
        message = Single.new(message) if message.is_a?(String)
        @message << message if message.is_a?(Message)
    end

end
</code>```

The end result is that Multiple message objects can contain Single messages as well as nested Multiple messages

```<code>m1 = Multiple.new
m1.add 'Hello!'
m1.add 'Hola!'
m1.add 'Bienvenue!'

m2 = Multiple.new
m2.add 'Salut!'
m2.add 'Jumbo!'

m1.add m2

m1.display
</code>```

This code will output:

```<code>Hello!
Hola!
Bienvenue!
Salut!
Jumbo!
</code>```

In metaphor, I suppose a Component could be like an executive in a business. Any given executive may work alone, or be the head of a division or department. But, when you go around and ask how much money each executive is going to need for the upcoming fiscal year, you don't care which one they are. If they work alone, they will simply tell you what their salary is/should be. If they are the head of a division, they will add on the money needed by all of the employees working under them. Those employees may or may not also be the heads of sub-devisions, in which case the same process would happen recursively.

Hope that helps!

Body:
I really don't think that the podcast's discussion of "components" is directly in the context of the composite pattern. They are talking about component-based software engineering. I suppose this is one of the pitfalls of the ambiguity of software development terminology.

But, putting that aside to discuss the composite pattern, there's a nice explanation here, in case you haven't read it.

Basically, in the composite pattern, a Component class is simply a class that provides some abstract functionality. In most real-world use cases, it's a class with an interface to output data, like a post or a message. In ruby, I'll implement a Message class:

class Message

    def initialize
        @message = ''
    end

    def display
        #abstract
    end

end

In the composite pattern, a Leaf is a single entity, that generally displays just one unit of information. In our example, a Single message will simply output the string that it is instantiated with:

class Single < Message

    def initialize(message)
        @message = message if message.is_a?(String)
    end

    def display
        puts @message
    end

end

In the composite pattern, a Composite is an object that can contain other components, whether those components are themselves Composite or simply single Leaves. For our example, I'll create a Multiple message class:

class Multiple < Message

    def initialize
        @message = []
    end

     def display

        @message.each do |message|

            message.display

        end

    end

    def add (message)
        message = Single.new(message) if message.is_a?(String)
        @message << message if message.is_a?(Message)
    end

end

The end result is that Multiple message objects can contain Single messages as well as nested Multiple messages

m1 = Multiple.new
m1.add 'Hello!'
m1.add 'Hola!'
m1.add 'Bienvenue!'

m2 = Multiple.new
m2.add 'Salut!'
m2.add 'Jumbo!'

m1.add m2

m1.display

This code will output:

Hello!
Hola!
Bienvenue!
Salut!
Jumbo!

In metaphor, I suppose a Component could be like an executive in a business. Any given executive may work alone, or be the head of a division or department. But, when you go around and ask how much money each executive is going to need for the upcoming fiscal year, you don't care which one they are. If they work alone, they will simply tell you what their salary is/should be. If they are the head of a division, they will add on the money needed by all of the employees working under them. Those employees may or may not also be the heads of sub-devisions, in which case the same process would happen recursively.

Hope that helps!


答:
There is no clear notion of the term »component«. You could use it in many different ways. But if you go to the root of the word (in terms of linguistics) you have »componere«, which is itself a »compositum« of »cum« (with) and »ponere« (put). So if you put something together you have a »composition« of individual parts.

There are two main aspects for components:

Composition »put together«

Compartmentalization »independent things«

So a software component is a unit or part of software, which in itself could be used independent from the actual composition - but on the other hand is used to build a larger system. Ideally you have a software in which each component is orthogonal, which means, no component is dependent on another component and they do each their job, where no functionality is duplicated (a form of DRY).

In most cases you could substitute »component« with »part«.

I am trying to figure out what components mean in the context of the composite pattern.

The point of the composite pattern is to put independent parts under a unique interface. You have the base component as a contract for each part to comply with. You have a leaf which is the part and you have the composite, which contains a collection of those parts.

1) What is the difference in purpose between a function and a component?

A component is the subject / carrier of a function ( in OO-terms).
On the other hand, if you take functional languages, I think it would be okay, to speak of functions as components in a functional composition.
In a broader sense, you could speak of a component in a whole, which represents one function: e.g. »a printing component« which stands for the function to be able to print.

2) What does a component have to do with the composite pattern?

See above: Composite is about putting together components.

3) Can you describe what a component is by using a funny metaphor? For example, explain how creating a component like baking an apple pie.

One way to put it: A component is like an ingredient for a meal.

Another way to put it: A component is a player in a soccer game. Each of them is different and has to play another role in the game, but together, they are a team and play soccer.

Title: What is the difference between a function and a component?

Body:
I just listened to Software engineering Radio podcast on components. Their description of components were very vague, they made them sound like lower level versions of functions. I am trying to figure out what components mean in the context of the composite pattern.

What is the difference in purpose between a function and a component?

What does a component have to do with the composite pattern?

Can you describe what a component is by using a funny metaphor? For example, explain how  creating a component like baking an apple pie.


问:
Difference between a defect and a bug in testing?
What is the difference between a defect and a bug? </p>

答:
Here is one I did earlier for my employer Q-LEAP based on the ISTQB vocabulary and I also checked the IEEE vocabulary. Enjoy.

Bug and Defect? The same even though one can have endless discussion about this. We have really other things to worry about, life is complicated enough already, etc.

An example of how the term is used in the wild, from "How Google Tests Software" p. 113. Open an article of "IEEE Software" and it's used the same way. Indeed, one rarely encounters the word "defect" in real life.

Life of a Bug

Bugs and bug reports are the one artifact every tester understands.
  Finding bugs, triaging bugs, fixing bugs, and regressing bugs are the
  heartbeat and workflow for software quality. This is the part of
  testing that is the most conventional at Google, but there are still a
  few interesting deviations from the norm. For this section, we ignore
  the bugs that are filed to track work items and use the term to
  identify actual broken code. As such, bugs often represent the
  hour-to-hour and day-to-day workflow for engineering teams.

A bug is born. Bugs are found and filed by everyone at Google. Product
  Managers file bugs when they catch issues in the early builds that
  differ form their specifications/thoughts. Developers file bugs when
  they realize they accidentally checked in an issue, or find an issue
  somewhere else in the codebase, or while dogfooding Google products.
  Bugs also come in from the field, from crowd-sourced testers, external
  vendor testing, and are filed by Community Managers monitoring the
  product-specific Google Groups. Many internal versions of apps also
  have quick one-click ways to file bugs, like Google maps. And,
  sometimes, software programs create bugs via an API.


问:
What are the advantages and Disadvantages of Using an Aspect Orientated Programming Paradigm
Ok so here is the question: What are the advantages and Disadvantages of Using an Aspect Orientated Programming Paradigm.

My advantages and disadvantages thus far:

Advantages:

Complements object orientation.

Modularizes cross-cutting concerns improving code maintainability and understandability.

Disadvantage:

Not the easiest of concepts to grasp - not as well documented as O-O

O-O goes far enough in the separation of concerns...

Would anyone like to challenge any of these/ add their own?

Many Thanks,
J

答:
Disadvantage:
Poor tool-chain support:- debugger and profiler may not know about the "Aspect Oriented Programming" because of this reason they may work on code as if all the aspects had been replaced by procedural code.</p>


问:
Is there any license which require to distribute the source code, even it is only used in a company's internal project?
I am looking for a software license which has stronger protection than AGPLv3. The GPL license said that when we distribute the software, we must provide a way for user to download the source code. However there is a loophole in this license, the GPL FAQ said (see below) it is not considered "distribution" if the company uses it as an internal project. Is there any license which require to distribute the source code, even it is only used in a company's internal project?

PS, GPL FAQ "Internal Distribution" section:

Is making and using multiple copies within one organization or
  company “distribution”?
 No, in that case the organization is
  just making the copies for itself. As a consequence, a company or
  other organization can develop a modified version and install that
  version through its own facilities, without giving the staff
  permission to release that modified version to outsiders.

However, when the organization transfers copies to other organizations
  or individuals, that is distribution. In particular, providing copies
  to contractors for use off-site is distribution.

答:
If you are asking about license that forces to attach source to every binary copy somehow, I highly doubt that somebody wrote something like this; since it implies that any software under this license would be at least twice larger than usual, which is not crucial, of course, but still is quite onerous for end-user.

If you are interested in licenses that forces anybody to publish sources of any modifications they made, even if they are for internal use in organization only, then yes, there was at least one licence of that kind – Reciprocal Public License.

But, think seven times before you use it. Besides the obvious incompatibility with GNU GPL, so you would not be able neither to borrow (A)GPL-code for this project, nor other (A)GPL-projects would be able to use your code (many believe, this is enough to avoid such a license); licenses with that kind of restrictions do not qualify as licenses for Free / Libre Software at all (according to both FSF and DFSG), in other words, your project would be considered as non-free / proprietary software. This implies that it would never be included in main repositories of most free operating systems (such as Debian, Ubuntu, Red Hat, Fedora, etc).


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
Work hard.  Do everything you're told and learn everything.  You're very lucky to work under someone who knows a lot more than you, keep working until you can catch up.

In addition to working hard, and succeeding in the job you're in now, I'd like to give some advice that is maybe an answer to the question you're not asking.  (It wasn't even on my radar when I got my first software job).

The internet is made by people like you.  And people like you can make money on the internet.

Find something you're passionate about.  Build it.  Sell it.  Be your own boss.

Open up http://news.ycombinator.com and start reading the articles.  You're going to see an endless wave of stories from people like you, who had an idea, built a website and managed to make a dollar or two doing it.  It's inspiring and eye-opening there's a guy who earns a ridiculously good wage selling a bingo card generator to teachers... another guy who sold a website to google for millions.  There's a lot of other interesting technology stuff in there too.

'Rich Dad, Poor Dad' there are places where he's got good advice.

'The Four Hour Work Week' take this one with a grain of salt, but he does have some interesting ways of looking at work & life.

Keep learning from the guy you're under now. There is so much to learn in 'your first real job' that I can't even begin.  In the long run though (three, five, ten, twenty years) if you learn how to make your own money, you won't have to worry about impressing someone else.


答:
Well IANAL, but I think there is good reason why GPL allows internal use without distribution: in reality, it would be extremely hard to enforce a stronger kind of license on any  company as long as they keep all their stuff internal. And if a company decides not to publish or distribute certain source code or code modifications, any employee taking actions against that decision could be easily sued by them for a breach of business secrets.

So, I am pretty sure there exist some written licenses which try to enforce distribution even when done internally, but I think also that any of them is pretty useless.

Body:
I am looking for a software license which has stronger protection than AGPLv3. The GPL license said that when we distribute the software, we must provide a way for user to download the source code. However there is a loophole in this license, the GPL FAQ said (see below) it is not considered "distribution" if the company uses it as an internal project. Is there any license which require to distribute the source code, even it is only used in a company's internal project?

PS, GPL FAQ "Internal Distribution" section:

Is making and using multiple copies within one organization or
  company “distribution”?
 No, in that case the organization is
  just making the copies for itself. As a consequence, a company or
  other organization can develop a modified version and install that
  version through its own facilities, without giving the staff
  permission to release that modified version to outsiders.

However, when the organization transfers copies to other organizations
  or individuals, that is distribution. In particular, providing copies
  to contractors for use off-site is distribution.


问:
What to learn to become freelancer?
I have around 8 years experience in software development. I have worked on application development all these years using C++ /win32.

I few years from now I want to become a freelancer . I tried to look into some freelance sites and I am not able to find any projects on C++/win32. I feel C++/Win32 wont help me much and I need to learn new skills . But my job require me to still work on C++ , so I cann't learn any new skills. I can still learn some new skills but without good project , it won't make any sense.

I have shortlisted few skills

php

jquery

perl

python

android

I am still confused which one to start and how to get expertise in them.Any suggestions?

答:
I work as freelancer for over a year now. And what I found out that although having technical knowledge (languages, design pattern, etcetc) is necessary, you should understand and do also those thing, which did not have to do in companies as a coder that much. You will not have a manager, accountant, salesman, marketer. Although you might get some of those, that's a luck.. you shouldn't refuse such support if get one. So try to know more also about these things, even if you are in a company yet:

try to value your days: how could you sell your today work.

manage your plan, track your time

try to market yourself: find out a product, try to find a market for is, who could use, need your product, publish your codes to show what you can do, sell your technical abilities and also your knowledge in a concrete domain; maybe have a blog, share your results and ideas

find ways to deal with customers, learn to communicate well with them: customers have often unrealistic expectations, facing them with reality or kindly saying no is a virtue which is good to know

have a strategy: choose and stick (but not too hardheadedly) to a group of technologies which you use for solving problems in a selected domain

So far what I see, it is a much safer feeling to be in a company, but more fun as a freelancer.

Title: What to learn to become freelancer?


问:
Dealing with code that has been written but isn't yet needed
I wrote a class to do something, but then realised that it wasn't needed, as I could optimize existing code to get the speed of execution I needed, rather than integrating the new class in with existing code (which would have been more complicated). However, I'm unsure if my current solution will be fast enough when I've written the rest of the program, so I'd like to keep the unused class around somewhere. I don't want to just keep it in the main version of the source code, as it would just be unnecessary clutter, but I think there must be a neater solution than putting it in its own file away from the rest of the project and coming back to it if I later need it.

I'm new to using source control, so I'm not sure what to do there. Could I create a side branch with the class, and merge it into the main branch without later?

答:
I would git tag the current HEAD with a name like my-old-class Then I'd delete the class and move on.

A branch makes sense if you are going to keep working on it. But you aren't. git tag functions more like a bookmark so you can always go back and find the version of the code that contained your class.

You could also just delete the class, and if you need it again search through the log for the commit.


问:
Why does "charset" really mean "encoding" in common usage?
Something that has long confused me is that so much software uses the terms "charset" and "encoding" as synonyms.

When people refer to a unicode "encoding", they always mean a ruleset for representing unicode characters as a sequence of bytes - like ASCII, or UTF-8. This seems reasonable and intuitive; the idea is that you are "encoding" those characters as bytes using the specified ruleset.

Since those rulesets sometimes only provide the ability to "encode" some subset of all unicode characters, you might imagine that a "charset" - short for 'set of characters' - would simply mean a set of unicode characters - without any regard for how those characters are encoded. An encoding would thus imply a charset (an encoding like ASCII, which only has rules for encoding 128 characters, would be associated with the charset of those 128 characters) but a charset need not imply an encoding (for example, UTF-8, UTF-16 and UTF-32 are all different encodings but can encode the same set of characters).

Yet - and here is the crux of my question - real-world usage of the word "charset" does not match what the construction of the word would imply. It is almost always used to mean "encoding".

For example:

The charset attribute in HTML is used to specify an encoding

Charsets in Java are encodings

charsets and character sets in MySQL are, once again, encodings

How old is this curious (ab)use of language, and how did this counter-intuitive definition of 'charset' come to exist? Does it perhaps originate from a time when there truly was, in practice, a one-to-one mapping between encodings in use and sets of characters they supported? Or was there some particularly influential standard or specification that dictated this definition of the word?

答:
RFC2045 introduced "character set" into MIME and by that time it was already clear not all encodings mapped one char to one octet. RFC2130 discusses this history a bit more.

Basically, "charset" was a more popular term when those standards were written, it's more succinct than "character encoding" or "text encoding scheme", and less ambiguous than "encoding".


答: With git, the rm command don't delete the history of the file. So you can get your class back later without problems.</p>

Title: Dealing with code that has been written but isn't yet needed

Body:
I wrote a class to do something, but then realised that it wasn't needed, as I could optimize existing code to get the speed of execution I needed, rather than integrating the new class in with existing code (which would have been more complicated). However, I'm unsure if my current solution will be fast enough when I've written the rest of the program, so I'd like to keep the unused class around somewhere. I don't want to just keep it in the main version of the source code, as it would just be unnecessary clutter, but I think there must be a neater solution than putting it in its own file away from the rest of the project and coming back to it if I later need it.

I'm new to using source control, so I'm not sure what to do there. Could I create a side branch with the class, and merge it into the main branch without later?


问:
Does distributing GPLd assets with a non-GPL application violate the license?
I'm trying to figure out if I can distribute the Faenza icons, which are GPL licensed, with some MIT-licensed software I'm working on. What does the GPL license really mean when applied to a non-software medium, like an icon set, that is primarily used in software applications?

If I load the icons dynamically from external files instead of compiling them into an executable, would this violate the GPL license?

If not, would it make a difference if the icons were compiled in?

If I can compile them into a program, does the license just mean I can't compile the SVG "source code" of the icons into a program?

If I can't compile the SVG source into a non-GPL program, can I load it dynamically?

Even if I'm technically allowed to package the icons with my software under some of the above conditions, would I be violating the spirit of the license?

Relevant: Does distributing non-GPLd assets with a GPL application violate the license?

答:
Standard disclaimer: I am not a lawyer.  You should get one, if you are concerned about possible legal issues.

Certainly, you can distribute the GPL-licensed Faenza icons with some MIT-licensed code, since both of MIT licenses (yes, there are at least two of them) are GPL-compatible. The same way as you can mix MIT and GPL code in one project, you can mix MIT code with GPL assets, while you are releasing the entire software product under GPL. It should not entail any practical problems, since it does not imply re-licensing of code to GNU GPL, it still remains under terms of permissive MIT license, only code + icons as a whole would be GPL-licensed.

I did not say, that there are no other ways (most probably, you are right about “package, but do not embed”), but I wanted to point out that there is a way, one can be absolutely sure about.


答:
FWIW, IIRC,
Back in the Commodore 64 days, a character set was a function from {0,...255} to the set of all uxv black and white images where u and v were maybe 8 and 12. So "changing your character set" meant using the POKE command in the BASIC language to modify the memory locations designated to hold those images. For example the ASCII code 65 meant A and the image of an A would be stored starting at memory address a*65+b for some b and I guess a=u*v.</p>

Title: Why does "charset" really mean "encoding" in common usage?

Body:
Something that has long confused me is that so much software uses the terms "charset" and "encoding" as synonyms.

When people refer to a unicode "encoding", they always mean a ruleset for representing unicode characters as a sequence of bytes - like ASCII, or UTF-8. This seems reasonable and intuitive; the idea is that you are "encoding" those characters as bytes using the specified ruleset.

Since those rulesets sometimes only provide the ability to "encode" some subset of all unicode characters, you might imagine that a "charset" - short for 'set of characters' - would simply mean a set of unicode characters - without any regard for how those characters are encoded. An encoding would thus imply a charset (an encoding like ASCII, which only has rules for encoding 128 characters, would be associated with the charset of those 128 characters) but a charset need not imply an encoding (for example, UTF-8, UTF-16 and UTF-32 are all different encodings but can encode the same set of characters).

Yet - and here is the crux of my question - real-world usage of the word "charset" does not match what the construction of the word would imply. It is almost always used to mean "encoding".

For example:

The charset attribute in HTML is used to specify an encoding

Charsets in Java are encodings

charsets and character sets in MySQL are, once again, encodings

How old is this curious (ab)use of language, and how did this counter-intuitive definition of 'charset' come to exist? Does it perhaps originate from a time when there truly was, in practice, a one-to-one mapping between encodings in use and sets of characters they supported? Or was there some particularly influential standard or specification that dictated this definition of the word?


问:
Is it fair to patent workarounds?
While developing a FAT32 driver for my bootloader, I thought to make it complete by adding the long file name support.

While watching around for some specification, and I also found
articles about Microsoft suing for infringement of their patents on something that basically is a workaround.
Knowing about this events made me think: is it fair to patent things that are workarounds?

答: If a solution to a problem is a workaround or not is often just a matter of viewpoint.  And to find a good workaround for a problem is sometimes not easy and may need a whole lot of intellectual work, not necessarily less than a "straightforward" or "uncompromising" solution. So assumed software patents would be any kind of fair (which I strongly deny!), I don't see why patents for "workarounds" should be less fair than for other "non-workarounds".</p>

Title: Is it fair to patent workarounds?


问:
Liskov Substitution and SRP Principle violation - how best to structure this scenario?
While learning SRP and LSP, I'm trying to improve the design of my code to comply best with both of these principles. I have an employee class that has a calculatePay method on it.

Firstly, I believe following OOP SOLID Principles, calculatePay() method should not be an employee objects responsibility. Common responsibilities of employees would be to performDuties(), takeLunchBreak(), clockIn() and clockOut() etc.

Am I right in thinking this way? That's why I feel calculatePay() should belong in some other class. Okay so that's my SRP insecurity.

Coming to LSP:

I have subclasses like accountants, salesman, and directors. These are all employees that get paid. How would I change this design to better support volunteers? Volunteers don't get paid.

```<code>public class Employee {

    private String name;
    private int salary;
    private boolean topPerformer;
    private int bonusAmount;

    public Employee(String name, int salary, boolean topPerformer, int bonusAmount) {
       // set fields etc..
    }

    // This method doesn't seem to belong here.
    public int calculatePay(){
        if(topPerformer)
            return salary+bonusAmount;
         else{
            return salary;
         }
    }
}
</code>```

答:
As long as calculatePay() is as simple as in your example, and as long as it does not need any parameters more than members from Employee, I would leave the method where it is. But when calculatePay() becomes more complex, and it needs information from outside the Employee class (like information from the employer, about taxes, actual date, etc.) I would refactor the calculation into a separate class like a "PaymentCalculator".

To your second question: assumed a volunteer is also an employee, then it is one with salary and bonus of zero. As long as the code which actually calls the calculatePay does not expect a payment of greater zero, I don't see a violation of the LSP.


问:
How best to involve junior developer in designing an application from scratch?
We are a team of 3 developers (2 experienced devs and a junior).

We just started a brand new project. We've designed the application, concentrated efforts on choosing the right architecture and now we are laying the first lines of code. We are writing the core of it, what will be the foundation of the entire application.

This ain't no easy application either. Hard performance requirements, massively distributed, complex entity model etc.

We are all out of our comfort zone, especially the junior. He doesn't have the experience to create a good design upfront. That's not a problem though because me and the other dev are there to help and we both believe in mentoring and in building teams, but... we don't know exactly what would be the best way to do it, so that he gets an enjoyable experience and learns the maximum amount of skills.

We both realized that we didn't have a junior on new projects, only on existing ones where it was easier on the junior because he had an entire code base from which to learn and inspire. But for this app we have almost no code. We just started.

We were thinking at a few approaches:

have him try on his own for a couple of days then intervene and refactor the code together with him, steer him in the right direction then repeat => Might not be a fun experience for him since we will be pointing out his mistakes on every refactor;

have him pair programming with one of us => he might become just a "bystander" and agree with everything we do, without actually learning a lot or digesting much of the information;

have us build the skeleton of each module, with a solid design and then giving the module to him to add the missing pieces => might not be fun to pick up after us and there is the risk that he only pays attention to filling the gaps and not to the entire design.

How can we involve him in the design so that he doesn't feel left somehow outside of it and so that he learns a lot from the experience and gaining enough confidence to try it on his own?

答:
All 3 ways look good to me. Actually trying 10 different agile ways at the same time should give you good results soon, at least you'll know which way works and which one does not (which one will work best depends a lot on the personalities of the players).

The pair programming problem will not occur if you stick to the process with the typing/thinking hats switching every 10-minutes (or so), no exception, following the process originally described by Kent Beck (I don't remember where)

As for involving other people in the design - what we have found that helps is if during the design phase some design documents (with some UML models) are created. The other people (your junior) can then proof read them, review them, play devil's advocate. This role of an independent unspoiled 3rd party can be actually very beneficial, e.g. for exploratory testing - http://www.softwaretestinghelp.com/exploratory-testing-beyond-traditional-testing-boundaries


答:
The term “charset” is of course short for “character set”, which in turn is an old term used for a character encoding, which can be interpreted as a) a mapping between sequences of bytes and characters, b) a mapping between integers (code numbers) and characters or c) a mapping between abstract characters and either integers or sequences of bytes.

“Character set” was taken into use since it is a short and simple expression. In it, “set” has a vague meaning (as the entire concept is vague), but it has later often been misinterpreted as a collection (“set” in set theoretical sense), as described in Dan Connelly’s (once) famous Character Set Considered Harmful.

What mattered most then was that the identifier charset was taken into use in MIME and in HTTP. HTTP 1.0 alias RFC 1945 quotes the MIME definition, “a
method used with one or more tables to convert a sequence of
octets into a sequence of characters” and then comments on the confusion: “This use of the term ‘character set’ is more commonly
referred to as a ‘character encoding.’ However, since HTTP and
MIME share the same registry, it is important that the terminology
also be shared.”


问:
GPL- How much source must be released?
Suppose I have a GPL v2-licensed library that is of interest to a closed-source project (e.g. Wolfram Alpha).

If some of my code were used in Wolfram Alpha, or a product that interfaces with Wolfram Alpha, would they have to release all of their code for Wolfram Alpha under the GPL v2 license?

答:
If Wolfram was to use link against GPL code in their software, then they would be required to distribute that resulting work per the GPL, as those are the terms of redistributing the GPL code.

The FSF makes this very clear in their FAQ: http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem

Title: GPL- How much source must be released?


问:
To find the oldest/newest element in a heap
I want to find the oldest/newest element added into a heap of size k. At any given point of time if I have to find say the oldest element in the heap is there any approach with O(1) space and O(1) time.

I was thinking of an approach of having a queue of the same size as that of the heap and add all the element into the queue as they are added to the heap. This yields a constant time solution but this requires an extra O(k) space. I would like to know if this problem can be solved with constant space.

答:
You can use a Double-End Priority Queue for this. There are a number of implementation methods available and the structure is routinely available in many libraries. Most Java libraries call it a MinMaxPriorityQueue though. It offers O(1) retrieval of Min and Max (Newest/Oldest) in O(1) time.

In order to fulfill your space requirement, you'd need to use an interval heap where each node has two values. Book-keeping is a little tricky but no slower than normal.


问:
How to lock/unlock a button based on tweeting
I have a button that will be disabled until you send out a tweet that I have crafted.

Only users with twitter accounts will have access to this, and I will require users to sign-in to be able to access this button.

What kind of tools are available for me to check whether

The user has actually tweeted it

The user has not deleted the tweet afterwards

Now, there is no way to actually stop the user from deleting the tweet, but I would like to disable the button if the user has actually chosen to delete it afterwards.

答:
By the fact "Only users with twitter accounts will have access to this, and I will require users to sign-in to be able to access this button" it simply means that the user ALREADY has login, before you start creating the HTML page.

Ie, before login, the user will see a form of HTML page, but after login, and at your webserver you have authenticated him via OAUTH2, then you will create the HTML specifically past-login.

That will also help to answer "the user has actually tweeted it", as you can now link the userid, with the tweet counter for specifically that user - 0 or 1.   Ie, you need will need to maintain a database at the server side of all userid who have tweeted it, and then add/remove everytime a new user added to it, or old user remove from it.   (which answer question 2)

Now, finally is the display of button:    simple, just check the database, if the userid is there, display it, otherwise don't generate the button for the HTML.

As you can see, everything is done at the server side - just like the user-dependent information for stackexchange.com as well.   If u create embedded Javascript to do the generation of HTML? well, it is not secure, and also wrong, because the user can login / delete from from two different PC/browser, and you will get inconsistencies.


答:
If you maintain a separate data structure along side your heap, this would likely solve your problem.  This is the approach that the LinkedHashMap uses (a linked list along side the HashMap) to allow for an LRU cache and well known ordering of the entries in the LinkedHashMap (insertion order) (grepcode LinkedHashMap.Entry).

This data structure would look like a Deque or something similar and is ordered by insertion order.  No other ordering is imposed on this structure.

The biggest problem with doing this though, is that the two structures (the heap and the deque) are not synchronized, one would have to do book keeping to remove from the deque when something is removed from the heap.

One approach to this would be to use a weak reference (Java Reference, C# WeakRefrence class).  When you walk the deque you would poll the Reference for get() to see if its actually there, and if so return that, otherwise discard that element in the deque and keep walking the list until you find a Reference that has an object attached to it.

The gotcha here is that if you are pointing to the object the heap is pointing to, it is possible that some other part of the code has taken a strong hold on the object and you'll think that is still in the Heap.

To avoid this, the deque should instead point to the heap element rather than the object the heap element is pointing to, and be very clean with your removal of the element from the heap when it is disposed (and not letting it leak outside of the heap - except to the deque (which should probably be inside the heap)).  I will admit to not knowing how long the Reference will still point to something and what conditions are necessary to deterministically clear it.

This then would allow the garbage collector to do the work for you of book keeping.  The trade off is instead of each time the insert or removal is being done form the heap and book keeping being done then, the book keeping is done when the deque is polled or peeked.  Which way the trade off goes is something to consider based on the insertion, removal, and polling the application does of the heap.

A thought of sticking yet another data structure inside the heap may allow for issues of deterministic references.  If you have a HashMap in the heap that holds all the objects too (though note that its not actually holding copies of them juts its own strong references to the objects).  When something is added or removed from the heap, it is also added or removed from the HashMap.  Thus, the deque, instead of holding weak references to the object holds a strong reference.  When the deque is polled, it checks the HashMap to see if the object is still in the heap.

Either way, what this ultimately provides is a deque such that the first element returned from the deque is the oldest in the heap, and the last element returned from the deque is the newest object in the heap.

Title: To find the oldest/newest element in a heap

Body:
I want to find the oldest/newest element added into a heap of size k. At any given point of time if I have to find say the oldest element in the heap is there any approach with O(1) space and O(1) time.

I was thinking of an approach of having a queue of the same size as that of the heap and add all the element into the queue as they are added to the heap. This yields a constant time solution but this requires an extra O(k) space. I would like to know if this problem can be solved with constant space.


答:
There are at least 2 encodings applicable to the transfer of text.  The character encoding describes how characters (glyphs) are encoded.  All languages use a subset of the UCS character set, which are often encoded to an 8 bit value.  Standardized character sets have standard character encodings, and the terms are generally used interchangeably.

The transfer encoding describes how the text is transferred and is generally independent of the character encoding.  Most transfer encodings are not transparent and alter the bytes sequence being transferred.  8-bit transfer encoding is transparent for 8-bit encodings.  7-bit transfer encoding can only transfer 7-bit character sets such as ASCII

ASCII uses 95 printable characters and a few more characters for carriage control (line feed, form feed, carriage return, backspace and tabs) encoded in 7 bits.  There are are additional control characters using the remaining values.  ASCII is a proper subset of the UCS character sets as well as many of the 8 bit character sets.  ISO-8859-1 is also a proper subset of the UCS character set, but these characters have different encoding in UTF-8, which uses multiple bytes for character values greater than 127.

IBM mainframes use(d) the EBCDID which used a different 8-bit encoding.  There are translation tables which map the printable characters between ASCII and ECBDIC character encodings. ECBDIC has a larger character set than ASCII because it has punctuation marks not available in ASCII.  This may prevents full round trip transformation between these two encodings, if the initial encoding is ECBDIC.

These encoding were not sufficient for languages with characters not covered by the ASCII printable characters.  Microsoft and others used 8-bit extensions to the ASCII character set and encoded additional characters with values above 127.  A single extension was not sufficient for all languages as these extensions only added up to 96 characters to the character set.  This resulted in multiple character sets (charsets) being used for different languages with different 8 bit character encoding.  These character sets include the characters required for that language or language family.  The additional characters may be encoded to different values in different charsets.  English users are most likely to notice this with extended punctuation (left and right quotation marks, and dashes) which show up incorrectly if the wrong character set is used.  This makes it important to know the character set used with an 8 bit character encoding.

For single byte encodings only characters in the character set can be encoded.  Some languages required multi-byte encodings to cover their character set.  The Unicode (UCS) character set requires multi-byte encodings for characters outside the ASCII character set.  This character set is a superset of all the language specific encodings.  UTF-8 is a compact encoding of the UCS character set.  ASCII requires no additional bytes, and most (all?) European language characters can be encoded as one or two bytes.  The full UCS-2 character set can be encoded in one to three bytes.  All characters in the current UCS character set can be encoded in one to four bytes.


答:
I would use composition to model this problem.

There are more classes this way, but the classes are better segregated.  A person has a role.  A role has a salary.  If the company changes the way that pays are calculated it requires changes in the PayCalculator.  If the definition of a person is changed, it only requires change in the Person class.  If a person is a volunteer, they get a salary of 0 in their CompanyRole.  Note that the same person can then later be promoted to a genuine employee quite easily (no need to create a new Person).

```<code>class Person
{
    string Name { get; private set; }
    CompanyRole Role { get; set; }

    public Person(string name)
    {
        this.Name = name;
    }
}

class CompanyRole
{
    Decimal Salary { get; set; }
    string Name { get; private set; }

    public CompanyRole(string roleName)
    {
        this.Name = roleName;
    }
}

static class PayCalculator
{
    private CompanyRole role;
    private Decimal bonus;

    Decimal CalculatePay(bool topPerformer)
    {
        return topPerformer ? role.Salary : role.Salary + bonus;
    }

    public PayCalculator(CompanyRole role, Decimal bonus)
    {
        this.role = role;
        this.bonus = bonus;
    }
}

// elsewhere in the application
public void PayRun(Person topPerformer)
{
    foreach (var person in Company)
    {
        var calculator = new PayCalculator(person.Role, bonusAmount);

        // this method is defined elsewhere
        PayPerson(person, calculator.CalculatePay(person == topPerformer);
    }
}
</code>```

This is just a starting point.  Consider creating an overload for the CalculatePay method which calls the method passing false as a parameter (this could clean up the calling code a little).  Also note that it is not the responsibility of the Person class to store whether the person is the top performer.  That should be the responsibility of a different class altogether (after all, there should only ever be one top performer, which is why it's a parameter).

Title: Liskov Substitution and SRP Principle violation - how best to structure this scenario?

Body:
While learning SRP and LSP, I'm trying to improve the design of my code to comply best with both of these principles. I have an employee class that has a calculatePay method on it.

Firstly, I believe following OOP SOLID Principles, calculatePay() method should not be an employee objects responsibility. Common responsibilities of employees would be to performDuties(), takeLunchBreak(), clockIn() and clockOut() etc.

Am I right in thinking this way? That's why I feel calculatePay() should belong in some other class. Okay so that's my SRP insecurity.

Coming to LSP:

I have subclasses like accountants, salesman, and directors. These are all employees that get paid. How would I change this design to better support volunteers? Volunteers don't get paid.

```<code>public class Employee {

    private String name;
    private int salary;
    private boolean topPerformer;
    private int bonusAmount;

    public Employee(String name, int salary, boolean topPerformer, int bonusAmount) {
       // set fields etc..
    }

    // This method doesn't seem to belong here.
    public int calculatePay(){
        if(topPerformer)
            return salary+bonusAmount;
         else{
            return salary;
         }
    }
}
</code>```

Body:
I would use composition to model this problem.

There are more classes this way, but the classes are better segregated.  A person has a role.  A role has a salary.  If the company changes the way that pays are calculated it requires changes in the PayCalculator.  If the definition of a person is changed, it only requires change in the Person class.  If a person is a volunteer, they get a salary of 0 in their CompanyRole.  Note that the same person can then later be promoted to a genuine employee quite easily (no need to create a new Person).

class Person
{
    string Name { get; private set; }
    CompanyRole Role { get; set; }

    public Person(string name)
    {
        this.Name = name;
    }
}

class CompanyRole
{
    Decimal Salary { get; set; }
    string Name { get; private set; }

    public CompanyRole(string roleName)
    {
        this.Name = roleName;
    }
}

static class PayCalculator
{
    private CompanyRole role;
    private Decimal bonus;

    Decimal CalculatePay(bool topPerformer)
    {
        return topPerformer ? role.Salary : role.Salary + bonus;
    }

    public PayCalculator(CompanyRole role, Decimal bonus)
    {
        this.role = role;
        this.bonus = bonus;
    }
}

// elsewhere in the application
public void PayRun(Person topPerformer)
{
    foreach (var person in Company)
    {
        var calculator = new PayCalculator(person.Role, bonusAmount);

        // this method is defined elsewhere
        PayPerson(person, calculator.CalculatePay(person == topPerformer);
    }
}

This is just a starting point.  Consider creating an overload for the CalculatePay method which calls the method passing false as a parameter (this could clean up the calling code a little).  Also note that it is not the responsibility of the Person class to store whether the person is the top performer.  That should be the responsibility of a different class altogether (after all, there should only ever be one top performer, which is why it's a parameter).


答:
For your first question, Strategy Pattern might be best solution. Each concrete strategy would be related to concrete employee type. But you should have separate employee types if different employees have different behaviors.

For your second question, it is similar situation as I answered here : Is this a violation of the Liskov Substitution Principle?

If you don't want to return 0 as "paid", then introduce IsPaid property of Employee which is checked before the payment calculation and execution takes place.


问:
Why is the use of conjunctions in method names a bad naming convention?
In my team, we work closely with a few software architects. They approve all design decisions of our projects, do some code reviews etc.

Our projects consist mainly of backend functionality implemented in PHP using the Symfony 2 framework. So syntactically, the code, naming conventions and project structure look almost identical to what Java would look like (Symfony 2 encourages such structure). I'm mentioning this because Java-specific conventions also apply in our case (if possible).

Recently, they suggested something that I find very strange: all methods should have conjunctions in their name e.g. getEntityOrNull, setValueOrException etc.

Such a naming convention feels very wrong to me, but I can't come up with any concrete arguments or online articles/pages that specifically challenge this.

The only things I came up with is:

such information should be present in the method's annotations, like @return or @throws

the use of conjunctions ("and", "or" etc.) in method names usually suggest that the Single Responsibility Principle is not properly respected

What are some other concrete arguments against this naming convention?

答:
Your two arguments are sound. But if they're the ones in charge of deciding the naming convention, try not to feel too bad about it being something you don't agree with.

While you're at it, you should convince them not to use the "get" and "set" portions unless those methods actually do directly set or get a member variable.


答:
They are probably doing so because of naming conflicts.  I assume that you cannot have two methods named getEntity, one which possibly throws an exception and one which returns null.  Therefore, you have to name them accordingly.

I, for one, dislike the practice of having many different ways of calling the same method unless it is performing some alteration that only that particular class can perform.

In other words, if getValueOrNull is simply calling getValueOrException, capturing the exception, and in that case returning null, this can be performed by the caller.  It clutters the class with methods that don't really contribute anything useful.  Rather I would prefer the getValue, and know that it throws the exception.  Better still, I would prefer to know that all get methods potentially throw exceptions, and none of them return null instead so that behavior is uniform throughout my project, or inversely, all potentially return null, and know that the caller would have to throw an exception if that were desired.

However, it is also true that you're not in charge of that.  My advice is to bring it up, but don't sweat the petty things.  Ultimately, the responsibility of such naming conventions falls on their shoulders, regardless of whether or not they take your advice, and because it is their asses on the line, I believe it is their prerogative to say no, in my humble opinion.

Title: Why is the use of conjunctions in method names a bad naming convention?

Body:
In my team, we work closely with a few software architects. They approve all design decisions of our projects, do some code reviews etc.

Our projects consist mainly of backend functionality implemented in PHP using the Symfony 2 framework. So syntactically, the code, naming conventions and project structure look almost identical to what Java would look like (Symfony 2 encourages such structure). I'm mentioning this because Java-specific conventions also apply in our case (if possible).

Recently, they suggested something that I find very strange: all methods should have conjunctions in their name e.g. getEntityOrNull, setValueOrException etc.

Such a naming convention feels very wrong to me, but I can't come up with any concrete arguments or online articles/pages that specifically challenge this.

The only things I came up with is:

such information should be present in the method's annotations, like @return or @throws

the use of conjunctions ("and", "or" etc.) in method names usually suggest that the Single Responsibility Principle is not properly respected

What are some other concrete arguments against this naming convention?


答:
Firstly, I believe following OOP SOLID Principles, calculatePay() method should not be an employee objects responsibility... Am I right in thinking this way?

Yes and no. That behavior should not be the responsibly of the employee, but not because of any programming or design principle. It is because no company in the world lets their employees calculate their own pay, so it isn't how your model is. Simple as that.

It isn't a question of following SOLID, it is a question of modeling your business domain as your business domain really is.

If you don't know where responsibility should lie you go back to your domain and keep looking until it is crystal clear and you don't even have to ask the question. This isn't a programming principle, this is just design. No keyboard required. You need to understand the model, understand who are the objects and understand what their role and behavior is. You need to understand that before you even sit down to write any code.

How would I change this design to better support volunteers? Volunteers don't get paid.

How does the real world business deal with volunteers? Figure that out and then just reflect that in your objects.

If you are ever in doubt about where responsibility should go or which object should do what, just go back to your business model. It should be blindingly clear from that. If it isn't then you need to leave the code and do some more design until you understand how the business manages these things.

While many businesses are not run at top efficiency, few are run in a complete mess. It is likely that your business has already figured out what a "volunteer" is. You may speak to a a director and they will say "Oh god no, we don't think of volunteers as employees at all, they are completely different" In which case you reflect that in your code. Or they may say that pay roll just treats volunteers as employees that get paid 0 each month. Again reflect that in your model.

If this is a programming assignment or something and you are not actually modelling a real business, but rather making up the business as you go along with the code, I would stop and start again modelling a business you know actually exists and that you have some experience with how it is run and structured.


问:
When are Getters and Setters Justified?
Getters and setters are often criticized as being not proper OO. On the other hand, most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are the same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

http://typicalprogrammer.com/?p=23

http://c2.com/cgi/wiki?AccessorsAreEvil

http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm

http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example

Procedural version of code:

```<code>struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}
</code>```

Mutator version of code:

```<code>class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);
}
</code>```

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

https://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil

https://stackoverflow.com/questions/996179

答:
When are getters and setters justified?

When the behavior "get" and "set" actually match up to behavior in your model, which is practically never.

Every other use is just a cheat because the behavior of the business domain is not clear.

Edit

That answer might have come across as flippant, so let me expand. The answers above are mostly correct but focus on the programming paradigms of OO design and some what miss the big picture. In my experience this leads people to think that avoiding gettings and setters is some academic rule for OO programming languages (e.g people think replacing getters with properties is grand)

In fact it is a consequence of the design process. You don't have to get into interfaces and encapsulation and patterns, arguing over whether it does or doesn't break these paradigms and what is or isn't good OO programming. The only point that ultimately matters is that if there is nothing in your domain that works like this by putting them in you are not modeling your domain.

The reality is that it is highly unlikely that any system in your domain space has getters and setters. You cannot walk up to the man or woman who is responsible for payroll and simply say "Set this salary to X" or "Get me this salary". Such behavior simply doesn't exist

If you are putting this into your code you are not designing your system to match the model of your domain. Yes that breaks interfaces and encapsulation, but that isn't the point. The point is that you are modelling something that doesn't exist.

More over you are probably missing an important step or process, because there is probably a reason I can't just walk up to pay roll and say set this salary to X.

When people use getters and setters they tend to push the rules for this process into the wrong place. This is moving away from your domain even more. Using the real world example, it is like salary assuming that the random person who walked in has the permission to get these values otherwise he wouldn't be asking for them. Not only is that not how the domain is, it is in fact lying about how the domain is.

ContentLicense: CC BY-SA 4.0

Title: When are Getters and Setters Justified?


答:
Standard disclaimer: I am not a lawyer. You should get one, if you are concerned about possible legal issues.

If some of my code were used in Wolfram Alpha ... would they have to release all of their code for Wolfram Alpha under the GPL?

No. While GNU GPL indeed is ‘hereditary’ license, that forces one to apply GPL to his program, that use GPL-licensed library, distributing it (speaking in the terms of GPLv3, conveying it), GPL does not force anyone to distribute software he wrote.

Wolfam Alpha is a web-application or, if you will, software as a service (SaaS). That kind of usage does not qualify as distributing / conveying under terms of GNU GPL, so you cannot require Wolfram Alpha LCC to publish sources of their product.

If you do not like this (reasonably), you have to consider using GNU AGPL (Affero General Public License) for the next versions of your libraries – it was purposefully created to prevent that problem. (That decision, of course, would not be retroactive.)

Suppose you develop and release a free program under the ordinary GNU GPL. If developer D modifies the program and releases it, the GPL requires him to distribute his version under the GPL too. Thus, if you get a copy of his version, you are free to incorporate some or all of his changes into your own version.

But suppose the program is mainly useful on servers. When D modifies the program, he might very likely run it on his own server and never release copies. Then you would never get a copy of the source code of his version, so you would never have the chance to include his changes in your version. You may not like that outcome.

Using the GNU Affero GPL avoids that outcome. If D runs his version on a server that everyone can use, you too can use it. Assuming he has followed the license requirement to let the server's users download the source code of his version, you can do so, and then you can incorporate his changes into your version.

— GNU.org. ‘Why Affero GPL’

P. S. @whatsisname pointed out that Wolfram Alpha is actually offered for deploying at customer’s hardware (what the price might be, I wonder). That should overturn the situation. But I believe, OP had not knew about it, choosing the hypothetical example, as well as I had not realized it, answering.

Title: GPL- How much source must be released?

Body:
Suppose I have a GPL v2-licensed library that is of interest to a closed-source project (e.g. Wolfram Alpha).

If some of my code were used in Wolfram Alpha, or a product that interfaces with Wolfram Alpha, would they have to release all of their code for Wolfram Alpha under the GPL v2 license?


问:
What layers reference each other in a multi layer design?
I'm creating a project and I'm having difficulty and contrasting opinions on how to do things when it comes down to separating layers. I'm not fully sure what layers should reference each other.

I have read in certain blogs/posts that the flow should be

the view references the business layer

the business layer references the data layer

the data layer only knows about it self

On the other hand I have also seen the following

the view references the business layer

the business layer knows only about itself

the data layer references the business layer

Using the second method I have been using the business layer using IOC but im reluctant to progress without more knowledge.

I have read a number of posts but the answers seem many and varied. Any clarification would be great.

Thanks

答:
From further reading on stack overflow I believe I have found my answer.
You do not want your business layer to access you data layer but rather have it injected using an IOC container. Using this method will also allow me to inject testable objects which will help unit testing.

This is exactly what I needed. Thanks for your help


问:
Custom Video Player
I have a custom file type .mft which is basically a zip that has video inside (mpg,mp4,etc) that is encrypted/protected.

My ideia is to create a custom video player which will read those .mft files, for a private group of users (users provide user and password), and the custom player will not allow to save the video, so that no one can re-share it, and can only view it.

I saw that VLC has this library http://vlcdotnet.codeplex.com/releases/view/121099, so my player would use it.

My question is : Is it really possible to block users from not saving the video? I don't think so, because there are several software to record desktop activity.

What do you think?

答:
In response to that last comment of yours, someone has actually coined this difficulty as the "Analog Hole". You cannot simultaneously show something to a user, and hide it from their computer's access.

http://en.wikipedia.org/wiki/Analog_hole

It still might be possible to A) Provide basic download difficulties to at least make it very difficult for the common user to obtain it, B) Watermark your video to avoid stealing.

There's also Encrypted Media Extensions, which I believe are used by Netflix now and would be a high-effort, high-security approach. You could look into them, but I admit that I know very little about their implementation.

Title: Custom Video Player