答:
Wikipedia explains planning poker quite well. Let me recap some of what's state there with a focus on your case:

Why planning poker?

First of all, you should all be on board as to why you are doing a planning poker as opposed to a "normal" estimation. The reason is actually quite simple: all of us suck big time when it comes to estimating time for a task. Pretty much every study has revealed, that the human brain is simply incapable of estimating task that take any reasonably amount of time. (Also a reason, why tickets that go beyond 2-3 days in their estimate are pretty much worthless in terms of their estimate.)

Why complexity rather than effort?

This goes hand in hand with the above. Effort usually means time, and we suck at that. Complexity instead is hard to quantify objectively, which is a good thing in this case. It's your gut that tells you this story is going to be complex. For someone else it may be less complex. But you need not quantify exactly how complex it really is. You have no need to get this number X of complexity - as opposed to a timed effort, where you eventually have to agree that it takes X days or some such.

Why hide the cards?

The cards with your complexity guestimate are played hidden and then revealed all at once. This is done to ensure you are not influenced by other people's opinions prior to making your own initial estimate. If everyone has about the same gut feeling in terms of complexity, then you're done. If there are wildly different numbers occurring, you know there's something to be discussed hidden there. In this way, you can very quickly deal with stories for which everyone has the same idea of the required complexity/effort.

Why Fibonacci numbers?

The numbers on your cards are typically Fibonacci numbers or some other kind of sequence with a lot of gaps in the numbers. This is to enforce you to fully trust your gut feeling. If you have to choose between 8 and 13, that's much more of a statement than going for 9 or 10. Also, as mentioned above, the large differences are where the hidden problems are, so by enlarging the gaps, you increase the chance to detect these problems better.

Why does this work at all?

Interestingly, the first few times you do a planning poker it won't work. It's as simple as that. What does "3" or "5" even mean? There is no definition for what each number means (on purpose!) and it is up to your whole team to discover the actual meaning behind each of these numbers. Only after you have accepted estimating your stories in these numbers - and after you have realized several of these - do you get a better idea of when you should raise a 5 and when it is an 8 rather.

Once you combine this with the concept of velocity and measuring your sprint progresses via these story points, you have a whole new scale of efficiency that is more or less independent of traditional time estimations.

Nevertheless, for me personally, the most beneficial point of planning poker is that by using fibonacci numbers instead of time estimates, you have a much easier time to detect uncertainties. With classical time estimates you are not forced to make such "extreme" (due to the number gaps) decisions, hence, estimates may be rather close together and the team may falsely believe that they understood the story well enough.

Example

A simple example of what typically happens is that a story is presented, and then person A comes up with an objection. It's something along the lines "please do not forget that this feature affects X and this may mean it's more costly than what we thought so far". The main problem is that there is always this person A at the table. There's always something someone is worried about. If you have an open up-front discussion, you have no idea really how large of a worry this thing X is.

If you make hidden estimates based on time, then it gets a bit better. But still, a person A with a valid objection may not be a clear outlier in her estimate yet. On the other hand, with planning poker, person A has to think more about how much of an actual problem X is. For two different problems, you cannot properly distinguish their importance by the above "spoken text of objection". Even with time estimates it's rather hard to see which is more of a problem. The hope of using planning poker here is that you end up with one objection being just 2-3 points different from the others' estimates, but the other objection which ended up 5 or 8 points away from the median may just be the most important uncertainty of your sprint planning.

Title: What is the purpose of planning poker in a sprint?

Body:
Our business analyst and project leads tell us the client's requirement as Stories. Every Sprint planning, we (developers) are asked to play planning poker.

They asked all of us to consider the 'Complexity' rather than 'Effort'. We are really confused and we are wasting time on our meetings. One developer raised a question, 'What should we really want to consider? Is it about the code/DDL change that we have to do in this requirement (time estimation) or is it about whether or not we have understood the requirement?'

But what do they (business analyst & project leads) really mean by 'understand the requirement' and 'raise a card'?

Plus, we have slicing meetings for individual scrum teams, where each developer gives an estimation of time for given task for each scrum team. So, what kind of thing are they really talking about in Planning Poker?

Can anyone explain this using an example? Try to differentiate what they are really talking about when they say 'Complexity' & 'Effort'.


问:
Is static going to make any difference in this code snippet
I have been to an interview and was asked this question - is there any difference adding or removing the static keyword in these classes?

I know what static means but my understanding of this point is weak.

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public static class aAsposeNew
{
    public static void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public static void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

and without the static keyword:

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew aAN = new aAsposeNew();
            aAN.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public class aAsposeNew
{
    public void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

答:
In addition to the two options you posted (static method in static class, instance method in non-static class), there is a third option: a static method in a non-static class:

```<code>class Program
{
    static void Main(string[] args)
    {
        aAsposeNew.MultipleInstancesProblem();
        Console.ReadLine();
    }
}

public class aAsposeNew
{
    public static void MultipleInstancesProblem()
    {
        // elided
    }
}
</code>```

I distinguish between the cases as if the class had some instance fields (or auto-properties), there would be a difference, as there'd be a memory impact from instantiating the class with new that you wouldn't get if it were a static method. For your code this doesn't matter as there are no instance fields or auto-properties.

This static method in non-static class case is still the same as the method being static in a static class, which, for your case, is the same as an instance method in an instance class (other than the way the method is called as @craysiii points out in his answer.

ContentLicense: CC BY-SA 3.0

Body:
In addition to the two options you posted (static method in static class, instance method in non-static class), there is a third option: a static method in a non-static class:

class Program
{
    static void Main(string[] args)
    {
        aAsposeNew.MultipleInstancesProblem();
        Console.ReadLine();
    }
}

public class aAsposeNew
{
    public static void MultipleInstancesProblem()
    {
        // elided
    }
}

I distinguish between the cases as if the class had some instance fields (or auto-properties), there would be a difference, as there'd be a memory impact from instantiating the class with new that you wouldn't get if it were a static method. For your code this doesn't matter as there are no instance fields or auto-properties.

This static method in non-static class case is still the same as the method being static in a static class, which, for your case, is the same as an instance method in an instance class (other than the way the method is called as @craysiii points out in his answer.


问:
Most efficient way to calculate number of iterations to run
Let's say I have a batch process that executes 4 times per loop, and needs to execute a total of 9 items.

Example:

Iteration 1 executes 4 items of 9, leaving 5 left

Iteration 2 executes 4 times of 9, leaving 1 left

Iteration 3 only executes 1 item because that's all that is left.

Currently I handle it with a modulus operation:

```<code>$number_of_items = 9
$number_of_executions_per_loop = 4

For $iteration = 1 to $number_of_items Step $number_of_executions_per_loop
   If $number_of_items < ($iteration * $number_of_executions_per_loop) Then
      $iteration_execution_count = MOD($number_of_items,$number_of_executions_per_loop)
   Else
      $iteration_execution_count = $number_of_executions_per_loop
   EndIf

   ExecuteJobsFunction($iteration_execution_count)

Next
</code>```

I am wondering if there is a cleaner way to handle these types of scenarios that I see frequently. Is there a math trick that can be done to determine how many items to execute?

答:
Judging by the dollar signs sprinkled in your code, you appear to be using some extremely high level and possibly highly inefficient script, so taking a MOD() is probably the least of your concerns, and what you do is just fine.

But if you really really want to simplify it, then you might want to consider something like the following:

```<code>number_of_items = 9
number_of_executions_per_loop = 4

For iteration = 1 to number_of_items Step number_of_executions_per_loop
   iteration_execution_count = number_of_executions_per_loop
   If iteration_execution_count > number_of_items - iteration Then
      iteration_execution_count = number_of_items - iteration
   EndIf

   ExecuteJobsFunction(iteration_execution_count)

Next
</code>```

Body:
Judging by the dollar signs sprinkled in your code, you appear to be using some extremely high level and possibly highly inefficient script, so taking a MOD() is probably the least of your concerns, and what you do is just fine.

But if you really really want to simplify it, then you might want to consider something like the following:

number_of_items = 9
number_of_executions_per_loop = 4

For iteration = 1 to number_of_items Step number_of_executions_per_loop
   iteration_execution_count = number_of_executions_per_loop
   If iteration_execution_count > number_of_items - iteration Then
      iteration_execution_count = number_of_items - iteration
   EndIf

   ExecuteJobsFunction(iteration_execution_count)

Next


问:
Abstraction in algorithms
I asked some questions about algorithms, and some replied they are abstract concepts, however I don't know what abstraction means for algorithms or how it applies.

For objects, I know if we remove the details of an object we have made it abstract, for example a Person is more abstract than Student

I thought maybe they mean removing details of an algorithm and just specifying it with its input and output for example A = Sort(A) is more abstract than bubble sort implementation.

Am I correct?

答:
No, you're not correct about what that person meant; your reference to objects is a rather technical detail of OO languages (which concerns abstractions the code is modelling), and talking about an algorithm only in terms of input and output is a different level of abstraction, one step too high (but at the same time too low because you seem to think about it again in terms of a programming language).

Algorithms are abstract concepts in the sense that the definition of a specific algorithm (let's say Bubblesort) is independent of how it's implemented. You can implement Bubblesort in any programming language you like, Haskell, Java, C, assembler, or even directly in hardware. You can even do it manually. But it will always be Bubblesort, it will always do things in the same way, and always have the characteristics (O(n^2) worst case running time, O(n) on presorted data) of Bubblesort.

Title: Abstraction in algorithms


问:
Logging function names on systems with few (memory and space) resources
Our logging module has a buffer that often gets full and we are searching for a solution to shorten our logs, without making any compormise in performance.

The code is written in C++ and currently we are using __FUNCTION__ to extract the function name for a trace, but on windows environments it also appends the whole namespace, which often represents more than half of the trace.

One of the proposed solutions was to parse the string returned by "__FUNCTION__" and extract the function name only, but we would rather not make this time performance compromise.

Another proposed solution was to #define a short function name at the beginning of every method and #undefine it at the end.

Is there any other approach for shortening (the file name in) logs on systems that have few resources?

答:
You could use __LINE__ instead, and although the function names will no longer be present in your logs, you can easily resolve them when analysing the logs.

An alternative is a static object in each function, declared at the start, that wraps trhe logger functions so you use it to write the log lines. The constructor would store a code (eg the line number of the declaration) that would be logged in place of the function name subsequently.


问:
Best way to model a singleton in a relational database
When designing relational database schema for web applications, I often find a case where I end up creating a table just to contain one row, and only one row. It feels like that is the wrong way to design it, but I can't come up with anything significantly better, or that is obviously "the right way to do it."

A recent example is a site that let the users manually control content on the home page. Well, there's only one home page. I created a table that had all the necessary fields to build the homepage, such as a text field for an area that contained descriptive text. A field to store the name of a big image file. Some foreign keys that point to articles that will be featured on the homepage, etc. It works, but it feels wrong to have a table with just one row.

In the past I've tried many other designs, such as allowing multiple rows in the homepage table and selecting one at random. I've tried adding a boolean field named "active" and selecting one of the active homepages at random. I've tried forcing only one row to be active at any given time in the application logic. I've tried not even making a homepage table and having all the other items, such as articles, to have boolean fields with names like featured_on_homepage.

In most cases I could build the homepage with a bunch of constants in a settings file. The main problem with the settings file is that it is under developer control. Because something like the contents of the homepage is something to be edited by the user, it has to go in the database.

On many sites, I don't have this problem because I can build things like the homepage with a query such as selecting the five newest articles. But when I have pages that are manually curated with strict requirements, it becomes tricky to model it in the database. But imagine you've got a photo table and an article table. The requirement is that the homepage will display exactly five photos, exactly three articles, and two blocks of arbitrary text manually controlled by the user. How do you model that in the database the right way?

Also, I have this modeling problem in many other cases besides just homepages. It's just the easiest and most generally applicable example I could come up with.

答:
One simple approach would be to save the Home Page properties in a Properties table (or call it something else) that is made up of Name & Value columns.

HomePageProperty1    -   UserValue1

HomePageProperty2    -   UserValue2

It may not be an ideal solution, but it is simple and flexible.  It also eliminates the table with one row scenario.

ContentLicense: CC BY-SA 2.5


答:
Maintain a map in which you accumulate function names and associate them with unique integer ids.

You should be able to optimize the performance of the map by taking into consideration the fact that the function name produced by the compiler for a certain function will always have the same address. (There will be only one string constant per function name in the data segment.) Exactly how you do that might be the subject of another stackoverflow question, but it is not even necessary.

So, the first time you encounter a function name, issue a unique id for it (by incrementing a counter) and generate a log entry documenting the fact that this id will from that moment on refer to the entire function name (namespace and all).

Then, from that moment on, whenever you encounter that function name, emit only the integer id instead.

You might also want to write a utility to run on your desktop computer which reads such a log and deciphers it by replacing these ids with the actual function names.

Title: Logging function names on systems with few (memory and space) resources

Body:
Our logging module has a buffer that often gets full and we are searching for a solution to shorten our logs, without making any compormise in performance.

The code is written in C++ and currently we are using __FUNCTION__ to extract the function name for a trace, but on windows environments it also appends the whole namespace, which often represents more than half of the trace.

One of the proposed solutions was to parse the string returned by "__FUNCTION__" and extract the function name only, but we would rather not make this time performance compromise.

Another proposed solution was to #define a short function name at the beginning of every method and #undefine it at the end.

Is there any other approach for shortening (the file name in) logs on systems that have few resources?


问:
What is the purpose of planning poker in a sprint?
Our business analyst and project leads tell us the client's requirement as Stories. Every Sprint planning, we (developers) are asked to play planning poker.

They asked all of us to consider the 'Complexity' rather than 'Effort'. We are really confused and we are wasting time on our meetings. One developer raised a question, 'What should we really want to consider? Is it about the code/DDL change that we have to do in this requirement (time estimation) or is it about whether or not we have understood the requirement?'

But what do they (business analyst & project leads) really mean by 'understand the requirement' and 'raise a card'?

Plus, we have slicing meetings for individual scrum teams, where each developer gives an estimation of time for given task for each scrum team. So, what kind of thing are they really talking about in Planning Poker?

Can anyone explain this using an example? Try to differentiate what they are really talking about when they say 'Complexity' & 'Effort'.

答:
After dozens of iterations in my team, we figured out that story points are mostly about medium-term project steering. They allow the product owner to project herself 2 or 3 sprints ahead and essentially make business and scope decisions about a release, based on an average velocity.

We've discovered that story points aren't so much useful at a sprint level, because no 2 sprints are similar and predicting how much work will be done is impossible. Consequently, we decided we shouldn't get obsessed with the estimation part and just take planning poker sessions as pretexts for conversation about features.

This concurs with a point made by Mike Cohn here.

As a side note, this is true for a given team, but there's no rule about how story points will help you. I recommend you first stick to the methodology but try to quickly find out by yourself if and how they're useful. Retrospectives will help you reflect on that.


答: In general an abstraction is a simplification or a simplified representation of something, so to produce an abstraction of an algorithm would be state its form in the simplest way - for a sort this would be state it without the details of how the comparisons or the substitutions worked, for instance.</p>

Title: Abstraction in algorithms

Body:
I asked some questions about algorithms, and some replied they are abstract concepts, however I don't know what abstraction means for algorithms or how it applies.

For objects, I know if we remove the details of an object we have made it abstract, for example a Person is more abstract than Student

I thought maybe they mean removing details of an algorithm and just specifying it with its input and output for example A = Sort(A) is more abstract than bubble sort implementation.

Am I correct?


答:
The fundamental problem here is that it is broken. The PM wants to use planning poker to get an idea of the complexity of each story, with the intention of knowing roughly how many stories can be fitted into a sprint (the team's velocity).

As a result, its a "not based on time" that is "based on time". Its no wonder everyone gets confused.

There are ways to make this work for you. Firstly forget about effort and focus on complexity. Forget all about how long it might take to develop and focus instead on the areas each story affects. If you have a story that updates the DB, the server code, the client code and the client documentation, then you can say that's a 4-point story. If it is only a change to the DB sql, then its a 1-point story. This gives you a more understandable way of figuring out relative complexity between stories. (You'll have to come up with some metrics that make sense for your circumstances, maybe test coverage requirements or UI complexity)

My opinion generally though is that its a pointless waste of time that simply encourages sprint planning as if they were mini waterfall projects. Who really cares how many story points you can fit into a sprint? If you have left-over stories at the end of a sprint, you just do them in the next one. Given that, you might as well just make your backlog the size of every outstanding story you have and gradually whittle them all down over time. Delivery takes as long as it takes (but it'll be quicker if you didn't bother wasting 20% of your time in backlog and sprint planning meetings). At the end of the project, nobody cares how many story points were delivered. What people care about is the delivered project.


答:
I think Frank's and Encaita's answers pretty much covers it but there are some additional things to consider:

Why use story points

The aim of estimating with story points is to give the relative complexity of developing features for your application. A simple way to think about it is take a story you have in the upcoming sprint e.g. a url change. You know this is simple in terms of complexity, and has clearly defined acceptance criteria so the whole team agrees that even with testing it's a 1 (using the Fibo scale).

The next story to be estimated is aggregating a set of user data and visualising that on the front end. Now as a developer you know immediately this is way more complex than changing a url. You discuss the story and the acceptance criteria and you have a lot of questions and can see several potential solutions for doing this. The other devs and QA also agree it's very complex. So you all agree that it's a 34 point story. It's worth noting that the Fibo scale also allows you to indicate how much confidence you have in the esimate - the bigger the gaps between numbers indicates the less confidence you have in your estimate

At this point your Scrum master should jump and say that this as a single story is too big and needs to be broken down into smaller stories of less complexity. You can approach this by doing what are known as SPIKES - this is just some time set aside to investigate something. So for this example you and the other devs agree you want 4 hours to discuss and investigate the possible technical solutions.

To cut a long story short you break that big story up into four other stories of 5, 8, 8 and 13 points. No remember that these estimates are all about relative complexity - they don't have to add up to the original estimate plus you have more information now to make a more accurate estimate.

You then agree as a team that for this sprint you'll aim to get done the 13 point story, one 8 point story plus the 1 point url change you had already identified. So a total of 22 points. The next sprint you get 27 points done, the following sprint you get 18 points done. After 3 sprints you can start to get some confidence in your velocity (velocity is the amount of work your team can get done in one sprint). To get the velocity take the average of the previous sprints. So in this example the average is (22+27+18) / 3 = 22.3 so round it to the nearest on the Fibo scale which is 21.

Now for the next sprint just aim to get 21 points done.

Don't get hung up on getting your story point estimate exactly right - it's not an exact science. You know a url change is far less complex than aggregating data so just score it accordingly.

Plus discussing these things as a team is good. Look back at your estimates during sprint review and discuss if you were happy with them or not and then feed this into the next sprint planning session.

The whole team estimate

The whole team must agree on a single estimate for each story. A feature isn't done until it's production ready. Just getting the code written is by no means done. In my experience Scrum teams have been far more effective when working as a team. Take an example of the team I'm working with right now. When I joined they were doing all the sprint meetings and planning poker but during the sprint the process was 1. BAs/Product Owners define the requirements as stories with acceptance criteria and acceptance tests 2. They hand these requirements to the developer who then writes the code 3. The developer has the code merged into the development branch for QA to test 4. QA test then they start asking questions and tests fail so it goes back into development.

What's missing here? There's not enough discussion up front and each team member only saw their own task. Now the BA/PO, devs and QA get together before writing any code to discuss the requirements in detail and ask questions up front, then continue the discussion throughout the sprint. This is far more efficient and leads to better quality solutions.

Planning poker helps this process because it forces the team to discuss the feature and agree, as a team, how complex delivery of that feature is. In traditional software development the Project Manager was responsible for delivery of the project but anyone with experience of that approach knows it doesn't work because more often than not, people do not take responsiblity for their part in the delivery of the application. In Agile you shouldn't need project managers because the team takes responsibility as a whole for delivery of the application.

On time estimation of tasks

My view having worked with teams that estimate time on tasks and teams that only do story point esimtates is DON'T DO TIME ESTIMATES! They're actually just a waste of time. They're not as accurate as story points because they are specific to individuals not the team, and each individual will have a different idea of time estimation(bring on the flame).

Story points accept that things i.e. requirements, change all the time so really you need an indicator of what the team can complete in a sprint.

Once you have an understanding of velocity you can measure your deliverables in time because you know what you can get done in each sprint e.g. every two weeks you know what features can be delivered. Your scrum master and product owners should be having estimation sessions to look ahead to future sprints then you can get an indicator of how much work you'll get done in the coming few months. This allows product owners to make prioritisation decisions about what features to include in the final application.

I've had developers ask that we estimate time for tasks in order to plan but I actually disagree with this approach (in fact I strongly disagree with this approach) because it is not accurate e.g. what does this will take me 4 hours really mean: one dev might include only the time on the task itself, someone else might add time for making cups of tea!

Time estimates are always handed to someone else for reporting purposes and it also overemphasises the individual elements of delivering a feature vs the whole team effort.

Estimation isn't the biggest problem

As an aside, figuring out estimation is not the biggest problem I think teams have to solve. The most important thing is working together as a team to get things done throughout the sprint, so that you don't hand everything over for testing on the last day. You want to see a steady trickle of features throughout the 2 week sprint. The team dynamic I explained above is a large part of this. Story point estimation will help you plan for this because you'll see which are the big stories that need breaking down into smaller ones that can be delivered into testing regularly.


问:
cpp and h/hpp #include: "why" question
Why does the source include a header and not also the other way around? I googled it but only found questions regarding the use of header files, how to include them but nowhere to say why it is like it is.
If the header is merely the declaration, how does the compiler know the definition only from it?

For example: take foo.cpp, bar.h, bar.cpp. This is what everybody does:

in foo.cpp:

#include "bar.h"

but the bar.cpp is not included neither in the bar.h or foo.cpp. That's why I deem logical that bar.cpp be included in bar.h and so, indirectly in foo.cpp.

答:
If bar.cpp included bar.h and vice versa, then there would be no point in having those two as separate files, since they would be effectively identical.

But there is a point: you don't need the definition for most tasks. Compiling a module that uses the services of bar only needs to know that bar contains a method doThings() which takes an int and returns an int. It does not need to know how bar achieves this (indeed, that is the entire point of modules). Therefore, when compiling another module, the compiler only bothers to read the header file, but when compiling bar itself it reads both files. In a large system composed of many modules, this saves a huge amount of effort because every line of definition code is compiled only once and not many times.

Title: cpp and h/hpp #include: "why" question


问:
8085 assembly question. Why flag stacks named d0-d7?
I'm trying to make my C programming exciting by learning assembly programming.

I've encountered an image of flag registers in 8085 assembly programming. In that image blocks are named from d0-d7(numerals in subscript). Why are they named 'd'? Is this arbitrarily chosen? There is another register with the name 'D', are both same or different?

答:
Yes there is difference

d0-d7 are 8 bit data bus and
 D is one of the register in 8085


问:
Benefits of TOGAF or similar?
I can read the website blurb and be impressed by the alleged benefits, but I haven't worked anywhere or with anyone who followed the TOGAF (or any alternative) architecture framework.

Our organisation has declared itself dedicated to moving from what is currently a fairly shambolic design & development model towards something approaching a modern structured process.

Things like TOGAF have been mentioned as helping achieve a world-class enterprise development environment (!) but I'm convinced that no-one here really understands the real-world benefits that wholesale adoption might bring and, perhaps more importantly, the effort/pain required to achieve the same.

Do you have experience in using TOGAF or similar to wrestle control in an organisation?  Do you think that use of the framework brought any benefit?

Edit:  For clarification TOGAF is "The Open Group Architecture Framework", a detailed method and set of tools for developing an enterprise architecture.  See: http://www.opengroup.org/architecture/togaf8-doc/arch/

答:
I've looked at TOGAF and my company uses other architectural frameworks but I haven't seen that one in use.  I would say that these don't give you much "out of the box".  But, if you use them to help structure your thinking around your system architectures, and adapt it to the particulars of your organization, it can be helpful.

Think about it like this.  It is really hard to start from a blank page and say "let's write up our organization's architectural framework".  Starting from TOGAF might be easier than starting from a blank page.

Title: Benefits of TOGAF or similar?


答: In 8086 assembly that I learnt in Uni, D stood for data. There were four main register groups, AX, BX, CX, DX. Accumulator, Base, Count, and Data. And I suspect it didn't hurt that they were ABCD. </p>

Title: 8085 assembly question. Why flag stacks named d0-d7?

Body:
I'm trying to make my C programming exciting by learning assembly programming.

I've encountered an image of flag registers in 8085 assembly programming. In that image blocks are named from d0-d7(numerals in subscript). Why are they named 'd'? Is this arbitrarily chosen? There is another register with the name 'D', are both same or different?


答:
Compilation of C and C++ code is done in two distinct steps.

In the first step, the source code in a single .c or .cpp file is compiled to object code. While compiling the file foo.cpp, the compiler needs to know that bar contains a method doSomething and what parameters that method expects and what return type it returns, but the compiler doesn't need to know exactly what the function does internally.

The compiler checks that the call in the code from foo.cpp matches how the function is declared (which is obtained by the #include "bar.h"), and then makes an annotation in the object code that at position X the function bar::doSomething is being called.

In the second step, all the source files that make up the application are linked together to create the final executable. At this point, the linker tries to replace the annotations that the compiler made in the object code with the actual address of the corresponding function. The linker is explicitly told which object files it should look at.

It is only at this point that the definitions of all functions need to be available.

Which files are needed to create an application is typically defined in a project file or a makefile.

Title: cpp and h/hpp #include: "why" question

Body:
Why does the source include a header and not also the other way around? I googled it but only found questions regarding the use of header files, how to include them but nowhere to say why it is like it is.
If the header is merely the declaration, how does the compiler know the definition only from it?

For example: take foo.cpp, bar.h, bar.cpp. This is what everybody does:

in foo.cpp:

#include "bar.h"

but the bar.cpp is not included neither in the bar.h or foo.cpp. That's why I deem logical that bar.cpp be included in bar.h and so, indirectly in foo.cpp.


答:
Don't get afraid by words : Abstraction is the process of removing every aspect of the issue that is not useful to solve it.

-So you can concentrate on only what matters-

Abstraction is so widely used because there exist a number of 'patterns' in programming that keeps repeating in every application. Find the pattern corresponding to your issue, find the abstract solution to it, implement it and you're done.

Even better : most (?all?) coding langages provides some built-in abstract patterns, which are most easy to use. Some API also provides more advanced patterns.

Abstracting is removing, so you can reach different level of abstraction by removing more or less aspect of your issue. But if you remove too much elements, you'll say nothing about nothing (expl : A=sort(A) won't solve much issues..).

On the other hand, if you keep too much details you might not see what's relevant to solve the issue.

Balance.

Let's take the sorting issue : It's not relevant what kind of object you want to use, neither the kind of storage you are using for those objects. ( And not either the platform or  the programming language you're using).

Sorting all breaks down to :

- having a collection of object in which you can iterate.

- having a way to compare two elements.

Then the purpose of the sort is to have every two successive items correctly ordered.

Now you can think bubble sort / quick sort / ... for any kind of iterable collection of comparable items.

Solve the issue once, and use it any time you encounter this issue, it doesn't matter if you are using a list, an array, a stack.... to store dates, or graphic objects, or ...  : the abstract algorithm will be the same.

Javascript for instance as a built-in Collection called an Array (it is in fact a dynamic array that can be sparse), which has a sort method. The only thing you have to do to sort the array is to provide the comparison function to the sort method -Great !-.

small example :

```<code>  // let's define a collection of information about travels.
  var travels = [ travel1, travel2, travel3, ...  ] ;
  // sort the travels on their start date
  // : just provide the right comparison function to the sort method.
  travels.sort(  function ( t1, t2 ) { return t1.startDate - t2.startDate } );
  ==> done !
</code>```

Rq : Abstraction is used for algorithm, but also for general software design : that's what design patterns are about.

Just one small example : imagine you have one object very costly to create that you might not even use, what can you do ?

(see that this question is very 'abstract' there's no useless details about the object type, the resource being used, ..., there's only the problem's skeleton).

Answer is -->>> use the lazy initialization pattern : do not create the object until it's actually asked by your application.

```<code>class SomeClass {

    public get someHeavyObject {
         // create object if it was not created already
         if (_someHeavyObject == null) _someHeavyObject = new SomeHeavyObject();
         // return the object
         return _someHeavyObject;
    }

    private _someHeavyObject = null;
}
</code>```

(more on design patterns here http://en.wikipedia.org/wiki/Software_design_pattern )

Another great advantage of abstraction is that when you're seeking help, be it on forums or with a mate, not everyone will want to hear/read the 30 minutes description of what you're building.

If you go straight to the point by abstracting the issue, you greatly raise your chances to be understood and to get your reply.

You will win a great deal of time by reusing the right abstract data types / algorithm / patterns, so do not hesitate to dig into it.

Title: Abstraction in algorithms

Body:
Don't get afraid by words : Abstraction is the process of removing every aspect of the issue that is not useful to solve it.

-So you can concentrate on only what matters-

Abstraction is so widely used because there exist a number of 'patterns' in programming that keeps repeating in every application. Find the pattern corresponding to your issue, find the abstract solution to it, implement it and you're done.

Even better : most (?all?) coding langages provides some built-in abstract patterns, which are most easy to use. Some API also provides more advanced patterns.

Abstracting is removing, so you can reach different level of abstraction by removing more or less aspect of your issue. But if you remove too much elements, you'll say nothing about nothing (expl : A=sort(A) won't solve much issues..).

On the other hand, if you keep too much details you might not see what's relevant to solve the issue.

Balance.

Let's take the sorting issue : It's not relevant what kind of object you want to use, neither the kind of storage you are using for those objects. ( And not either the platform or  the programming language you're using).

Sorting all breaks down to :

- having a collection of object in which you can iterate.

- having a way to compare two elements.

Then the purpose of the sort is to have every two successive items correctly ordered.

Now you can think bubble sort / quick sort / ... for any kind of iterable collection of comparable items.

Solve the issue once, and use it any time you encounter this issue, it doesn't matter if you are using a list, an array, a stack.... to store dates, or graphic objects, or ...  : the abstract algorithm will be the same.

Javascript for instance as a built-in Collection called an Array (it is in fact a dynamic array that can be sparse), which has a sort method. The only thing you have to do to sort the array is to provide the comparison function to the sort method -Great !-.

small example :

  // let's define a collection of information about travels.
  var travels = [ travel1, travel2, travel3, ...  ] ;
  // sort the travels on their start date
  // : just provide the right comparison function to the sort method.
  travels.sort(  function ( t1, t2 ) { return t1.startDate - t2.startDate } );
  ==> done !

Rq : Abstraction is used for algorithm, but also for general software design : that's what design patterns are about.

Just one small example : imagine you have one object very costly to create that you might not even use, what can you do ?

(see that this question is very 'abstract' there's no useless details about the object type, the resource being used, ..., there's only the problem's skeleton).

Answer is -->>> use the lazy initialization pattern : do not create the object until it's actually asked by your application.

class SomeClass {

    public get someHeavyObject {
         // create object if it was not created already
         if (_someHeavyObject == null) _someHeavyObject = new SomeHeavyObject();
         // return the object
         return _someHeavyObject;
    }

    private _someHeavyObject = null;
}

(more on design patterns here http://en.wikipedia.org/wiki/Software_design_pattern )

Another great advantage of abstraction is that when you're seeking help, be it on forums or with a mate, not everyone will want to hear/read the 30 minutes description of what you're building.

If you go straight to the point by abstracting the issue, you greatly raise your chances to be understood and to get your reply.

You will win a great deal of time by reusing the right abstract data types / algorithm / patterns, so do not hesitate to dig into it.


问:
standard format to describe opening schedules
I am working on a project in which I have to model opening schedules (eg a swimming pool is opened from 10:30am to 5pm on Tuesday from january to May. I try to fit this data in a csv and I started using a homemade format (the swimming pool example would be 1/1-30/5|Tu:10+30-17).

I am not really happy with that and I tried to look for a standard format to describe opening schedules. However I failed to find anything relevant. The closest I could find was Repeating intervals but it isn't really what I want.

Is there any standard format to describe opening schedules?

答:
You are going to need a decision tree of some kind. something like (not holiday) and month between jan-may and day of week is Tuesday and hour between 10:30-17

This is the closest to the natural language constraints the non technical users will have to input.

To input them I suggest using a proper gui that allows the user to select the various types. And a calender window to show the result.


答:
If the image you saw is like this one, D0-D7 imply bit positions in the status register, called F (for flags) when part of the AF register pair.  The Ds are misleading because they imply some (nonexistent) relationship to the D register or the data pins (which are multiplexed with the address lines and are actually called AD0-AD7).

Describing bit positions for the status flags doesn't mean much of anything for most people because the only instructions that operate on F deal with a single bit at a time (conditional jumps, conditional subroutine calls and the instructions that set and clear the carry flag).  The only way to operate on the flags as a whole would be to transfer them to or from another register by way of the stack.


问:
Recursion -- is it "divide and conquer" or "code reuse"
Recursion -- as we all know -- is one of those problems -- that wrapping your head around feels like  achieving a "milestone" in your programming voyage.

But when it comes to actually using it in real world problems -- knowing the mechanics of recursion is NOT enough -- one must also understand the nature of the problems where recursion is the most suitable solution.

So my question is this...

what are the "problem patterns" that call for the solution of recursion

is recursion a form of "divide & conquer" strategy or a form of "code reuse" -- or, is a design pattern in its own right

can you give us an example of a real world problem where recursion comes to mind as an immediate solution

-- UPDATE --

a lot of answers are referring to "real problems" as tree traversing, of factorial, etc. I would prefer "the REAL real problems" -- let me give you an example...

We had a LARGE chuck of text (about 30 MB of text as a linked list of structs), and we needed to make an index of it for full text searching. We needed keep the entire index in the memory and re-index the text every 10 minutes.

Every 10 minutes we'd compare the entire text (two linked lists, line by line) with a newly generated chunk of text -- to see what line was changed -- and then we would re-index only that line -- that way we could avoid having to re-index the ENTIRE text. Remember -- we needed to find the diff points between two 30 MB linked lists.

One of my colleagues came up with a fantastic program which used HEAVY recursion to compare the lines -- and then collect the positions where the chucks differed in an array  -- yes i know it sounds puzzling -- how could recursion help here -- but it did.

The point is -- how could he see that this problem could be solved smartly with heavy use of  recursion?

答:
When you write a recursive algorithm, you usually translate a recursive definition of the problem to the code. Then you don't even need to know how it will be executed.

It's what happens in functional programming. In fact, you specify what (definition) rather than how. In other words, you define the base and then define your problem in the term of a sub-problem.

For example consider Factorial algorithm

Define the base: Factorial(1) = 1;

Define Factorial n : Factorial(n) = n* Factorial(n-1);

Then when you encounter a problem, you should think if you can define it recursively or not, if you can define it recursively, you almost have solved it.

However, any recursive function shouldn't be a recursive definition. You can define the base and relate (define) the solution of the main problem to solution (definition) of sub-problems. But for this relation you may need a procedure.

An example is MergeSort in which merge could be an imperative procedure to relate the definition or solution of sorting the whole array to the sort of the sub-arrays.


问:
Integration tests of SQL logic
In my daily work, I use a lot of SQL logic (oracle stored procedures and SQL functions).
To limit the code regression on the implemented code I make what I call "integration scripts" : C# scripts that call the SP with given parameters and compare the result with the intended one and alert me if the result aren't the intended ones.
I run these scripts after each modification to validate that I didn't break everything.

This works pretty well, better than nothing, but it looks like makeshift job.

Is there any practice better than this one to validate SQL based code ?

答:
In less words, this sounds like unit testing.  Your "C# scripts" are the units of pass/failure.

Is there any practice better than this one to validate SQL based code ?

You shouldn't be concerned with validating the actual SQL code.  All you really should care about is the validity of the data and the result.  You should be decoupling your unit tests from the actual underlying mechanism (an RDBMS in this case), so that your unit testing is interchangeable if the underlying data source became different, or even a different type (think: flat file, service request, API calls, etc.).

An example

An automaker shouldn't care about the molecular properties and testing of the metal they use for their cars.  They should care about the numbers and deceleration during an impact test of the car.  Think big picture.

So the better question here shouldn't be "how do I test my SQL logic", but it should be "how do I test and validate my logic and data".

Title: Integration tests of SQL logic


答:
Just to add to Walter..

The property table structure should allow multiple data types.

```<code>Fileds:
PropertyName
PropertyTextValue
PropertyDateValue
PropertyNumericValue
PropertyBoolValue
</code>```

Title: Best way to model a singleton in a relational database

Body:
When designing relational database schema for web applications, I often find a case where I end up creating a table just to contain one row, and only one row. It feels like that is the wrong way to design it, but I can't come up with anything significantly better, or that is obviously "the right way to do it."

A recent example is a site that let the users manually control content on the home page. Well, there's only one home page. I created a table that had all the necessary fields to build the homepage, such as a text field for an area that contained descriptive text. A field to store the name of a big image file. Some foreign keys that point to articles that will be featured on the homepage, etc. It works, but it feels wrong to have a table with just one row.

In the past I've tried many other designs, such as allowing multiple rows in the homepage table and selecting one at random. I've tried adding a boolean field named "active" and selecting one of the active homepages at random. I've tried forcing only one row to be active at any given time in the application logic. I've tried not even making a homepage table and having all the other items, such as articles, to have boolean fields with names like featured_on_homepage.

In most cases I could build the homepage with a bunch of constants in a settings file. The main problem with the settings file is that it is under developer control. Because something like the contents of the homepage is something to be edited by the user, it has to go in the database.

On many sites, I don't have this problem because I can build things like the homepage with a query such as selecting the five newest articles. But when I have pages that are manually curated with strict requirements, it becomes tricky to model it in the database. But imagine you've got a photo table and an article table. The requirement is that the homepage will display exactly five photos, exactly three articles, and two blocks of arbitrary text manually controlled by the user. How do you model that in the database the right way?

Also, I have this modeling problem in many other cases besides just homepages. It's just the easiest and most generally applicable example I could come up with.

Body:
Just to add to Walter..

The property table structure should allow multiple data types.

Fileds:
PropertyName
PropertyTextValue
PropertyDateValue
PropertyNumericValue
PropertyBoolValue


答:
If a unit test breaks, you usually know exactly what went wrong; when an integration test breaks, it's a hint that a piece of your process has something wrong with it.  If you're comfortable with this and your SP isn't incredibly complex, the integration tests from C# should be fine.

A few things to consider :

Use a unit testing framework.  Calling them "C# Scripts" makes me wonder if you're doing these tests without a proper unit testing framework.

Look into rolling back the results of any database mutations after the test has run.  Here's an older example but should work in any test runner

Title: Integration tests of SQL logic

Body:
In my daily work, I use a lot of SQL logic (oracle stored procedures and SQL functions).
To limit the code regression on the implemented code I make what I call "integration scripts" : C# scripts that call the SP with given parameters and compare the result with the intended one and alert me if the result aren't the intended ones.
I run these scripts after each modification to validate that I didn't break everything.

This works pretty well, better than nothing, but it looks like makeshift job.

Is there any practice better than this one to validate SQL based code ?


问:
Producing JSON objects from JPA entities in REST API
I have a REST service producing JSON and consuming JSON.

A lot of this are simple CRUD operations. My initial idea was to simply use the DAOs directly in the controller:

```<code>@ResponseBody()
@RequestMapping(value="/cars/{carID}", method = RequestMethod.PUT)
public Car saveCar(@PathVariable Long carId, @RequestBody Car car) {

   carDAO.save(car);

   return car
}
</code>```

In this example, Car is a persistent @Entity and the save method is just a wrapper for EntityManger.persist();

I heard that it is generally a bad idea to use persistence classes in the controllers for your API. Is that true? If so, why and what is the alternative?

Is this a good idea? Do I need a service layer? If not when would I need it?

Assume the application grows and the operations get even more complex, would I then need a service layer?

答:
Whenever you define a non-CRUD operation you will be in trouble to find a HTTP method, which describes the same thing. This can be solved by defining a new resource. So REST resources cannot be mapped 1:1 to entities. That's the problem in your case.

Imho you need a domain model which is working with the entities and you need a delivery method, which transforms the HTTP request into commands or queries addressed to your domain model. I would check domain driven design if I were you, maybe you learn something you can use in your project.


问:
Is a makefile really needed
I have been programming in c/c++ for a while now, and I have never once used a makefile. I know that it is supposed to be useful when you are dealing with a large project, but I have always been able to compile, build and execute my program using only

```<code>gcc main.c -o run
</code>```

and if I am working with an external library (gtk+, for example) I make a simple bash script that looks like:

```<code>#!/bin/bash
echo compiling....
gcc main.c `pkg-config --cflags --libs gtk+-3.0` -o run
</code>```

So what I'm asking is do I need to learn how to make a makefile?

答:
If you use a modern IDE(*) you will probably never have to look at a makefile in your life, even though the IDE generally will generate one for you on the fly.

Makefiles were a needed skill when I started out 30+ years ago. I rarely see them nowadays (and, if you do need one, there are makefile generators).

In short, don't learn a skill until you need it, or can anticipate needing it. Use the timer saved by not learning makefile to learn something else which will make you a better developer.

(*) and if you are not, you are missing out on a ton of helpful features, like code completion (often with pop up documentation of the completions), code navigation, integrated debugger, integrated unit test, GUI designers, refactoring, et al

Title: Is a makefile really needed


问:
If I find a public web API am I allowed to use it in my application?
If I find a public web API (by public I mean that isn't protected by any type of authentication) what do I need to do so that I am allowed to use it in my own application?

Is it enough to read and follow the terms of service, or do I need to do something over and above that?

Is it true that this is as legal as using a web scraper and that all search engines get away with that?

答:
I am not a lawyer and you aren't even saying which jurisdiction applies to you, so no legal advise from me.

But from a purely practical standpoint, building a product based on an undocumented API is a very bad idea. You have no way to tell if the API will still be there tomorrow. The one who made it can destroy your whole work with a single change to their API.

They might do this intentionally because they want to keep you out. After all, you are only consuming their resources without giving them anything in return. Or they might do it just because their own requirements changed and they don't even know that others also use their API. The only way to have any chance to get a warning in advance is to ask them if you may use it. When you are serious about your project and their API is essential for it, you could ask them to make a deal that they guarantee availability and stability of their API in exchange for money.


问:
Learning VB, and have a question about Focus()
I know that the .Focus() allows you to focus on a text input field, or wherever you wish your eye to be directed, but I am wondering, is there a way to use Focus to direct the person's view to whatever field they left empty?

So in other words, as an example:

```<code>Try
            Code to input Field A

            Code to input Field B

            Code to input Field C

       Catch
            'Error Message Box for one or more of the empty Class Ticket Fields.
            MessageBox.Show("One or More of the Fields are empty! Please Enter a Value!")
            txt_ClassA.Focus()
        End Try
</code>```

Now lets say that someone forgot to enter text into field B, is there a way except to write a try/catch for each individual input field, to have the .Focus() actually focus on B automatically?

答:
I'll try to answer both the technical part of your question in a bit, but I would to start with pointing out that validating a form in its entirety before providing (limited) feedback about the found issues is a bit outdated.
You can read up on the latest insights in usability (and related field) on the dedicated Stack Exchange site. Note though that any of the newer techniques will probably prevent your current problem from occurring, so it may be wise to read up before continueing with your current solution.
However, you may be stuck with some older code or have specific requirements to implement the form as you did so I will also attempt to answer your question from a technical point of view.

Note that the Focus method is not so only about drawing the attention to a specific control on your form.
It also (or, in my opinion, instead) makes a control the active control. This will allow your program to find out on which control a key press or mouse click should to be executed.

You are looking for a way to check if all required fields have values without creating duplicate code. This is a good attitude!
If I would be asked to do this, I would try to find the commonalities (the parts that are duplicate).
In your example, this would be the check on whether or not a text box contains a value, and the reporting of the problem if a problem is found.
I would then create a method where I would store the common code and 'inject' the non-common code, which in you example are the different text boxes.
I have not written any VB since VB 6, so I hope the pseudo VB code below will get the point across.

The method:

```<code>Private Function TextBoxContainsValue(textBoxToCheck as TextBox, labelText String) as Boolean
    If textBoxToCheck.Text = "" Then
        textBoxToCheck.Focus()
        MessageBox.Show("The text box labelled " + labelText + " is required. Please enter a valid value.");
        TextBoxContainsValue = False
    Else
        TextBoxContainsValue = True
    End If
End Function
</code>```

Your current code can then change to something like:

```<code>If Not TextBoxContainsValue(txt_ClassA, "Class A") Then
    ' No need to check the other text boxes since we can put the focus on just one control.
    Exit Sub
End If

If Not TextBoxContainsValue(txt_ClassB, "Class B") Then
    Exit Sub
End If

If Not TextBoxContainsValue(txt_ClassC, "Class C") Then
    Exit Sub
End If
</code>```

Again, this just addresses the technical part of your question (even adds a bit more information about which text box was found empty).
Searching for "form validation" on the User Experience Stack Exchange site (found at: ) resulted in over 50 pages of questions.
Do yourself and your users a big favor a check out at least some of them to get an idea on how to improve your users experience.

Body:
I'll try to answer both the technical part of your question in a bit, but I would to start with pointing out that validating a form in its entirety before providing (limited) feedback about the found issues is a bit outdated.
You can read up on the latest insights in usability (and related field) on the dedicated Stack Exchange site. Note though that any of the newer techniques will probably prevent your current problem from occurring, so it may be wise to read up before continueing with your current solution.
However, you may be stuck with some older code or have specific requirements to implement the form as you did so I will also attempt to answer your question from a technical point of view.

Note that the Focus method is not so only about drawing the attention to a specific control on your form.
It also (or, in my opinion, instead) makes a control the active control. This will allow your program to find out on which control a key press or mouse click should to be executed.

You are looking for a way to check if all required fields have values without creating duplicate code. This is a good attitude!
If I would be asked to do this, I would try to find the commonalities (the parts that are duplicate).
In your example, this would be the check on whether or not a text box contains a value, and the reporting of the problem if a problem is found.
I would then create a method where I would store the common code and 'inject' the non-common code, which in you example are the different text boxes.
I have not written any VB since VB 6, so I hope the pseudo VB code below will get the point across.

The method:

Private Function TextBoxContainsValue(textBoxToCheck as TextBox, labelText String) as Boolean
    If textBoxToCheck.Text = "" Then
        textBoxToCheck.Focus()
        MessageBox.Show("The text box labelled " + labelText + " is required. Please enter a valid value.");
        TextBoxContainsValue = False
    Else
        TextBoxContainsValue = True
    End If
End Function

Your current code can then change to something like:

If Not TextBoxContainsValue(txt_ClassA, "Class A") Then
    ' No need to check the other text boxes since we can put the focus on just one control.
    Exit Sub
End If

If Not TextBoxContainsValue(txt_ClassB, "Class B") Then
    Exit Sub
End If

If Not TextBoxContainsValue(txt_ClassC, "Class C") Then
    Exit Sub
End If

Again, this just addresses the technical part of your question (even adds a bit more information about which text box was found empty).
Searching for "form validation" on the User Experience Stack Exchange site (found at: ) resulted in over 50 pages of questions.
Do yourself and your users a big favor a check out at least some of them to get an idea on how to improve your users experience.


问:
Why is base-for-all-objects discouraged in C++
Stroustrup says "Don’t immediately invent a unique base for all of your classes (an Object class). Typically, you can do better without it for many/most classes." (The C++ Programming Language Fourth Edition, Sec 1.3.4)

Why is a base-class-for-everything generally a bad idea, and when does it make sense to create one?

答:
Java takes the design philosophy that Undefined Behavior should not exist.  Code such as:

```<code>Cat felix = GetCat();
Woofer Rover = (Woofer)felix;
Rover.woof();
</code>```

will test whether felix holds a subtype of Cat that implements interface Woofer; if it does, it will perform the cast and invoke woof() and if it doesn't, it will throw an exception.  The behavior of the code is fully defined whether felix implements Woofer or not.

C++ takes the philosophy that if a program shouldn't attempt some operation, it shouldn't matter what the generated code would do if that operation were attempted, and the computer shouldn't waste time trying to constrain behavior in cases that "should" never arise.  In C++, adding the appropriate indirection operators so as to cast a *Cat to a *Woofer, the code would yield defined behavior when the cast is legitimate, but Undefined Behavior when it is not.

Having a common base type for things makes it possible to validate casts among derivatives of that base type, and also to do try-cast operations, but validating casts is more expensive than simply assuming that they're legitimate and hoping nothing bad happens.  The C++ philosophy would be that such validation requires "paying for something you [usually] don't need".

Another problem which relates to C++, but wouldn't be a problem for a new language, is that if several programmers each create a common base, derive their own classes from that, and write code to work with things of that common base class, such code will be unable to work with objects developed by programmers who used a different base class.  If a new language requires that all heap objects have a common header format, and has never allowed heap objects which didn't, then a method which requires a reference to a heap object with such a header will accept a reference to any heap object anyone could ever create.

Personally, I think that having a common means of asking an object "are you convertible to type X" is a very important feature in a language/framework, but if such a feature isn't built into a language from the start it's difficult to add it later.  Personally, I think such a base class should be added to a standard library at first opportunity, with a strong recommendation that all objects that will be used polymorphically should inherit from that base.  Having programmers each implement their own "base types" would make passing objects between different people's code more difficult, but having a common base type which many programmers inherited from would make it easier.

ADDENDUM

Using templates, it's possible to define an "arbitrary object holder" and ask it about the type of the object contained therein; the Boost package contains such a thing called any.  Thus, even though the C++ doesn't have a standard "type-checkable reference to anything" type, it's possible to create one.  This doesn't solve the aformentioned problem with not having something in the language standard, i.e. incompatibility between different programmers' implementations, but it does explain how C++ gets by without having a base type from which everything is derived: by making it possible to create something that acts like one.

Body:
Java takes the design philosophy that Undefined Behavior should not exist.  Code such as:

Cat felix = GetCat();
Woofer Rover = (Woofer)felix;
Rover.woof();

will test whether felix holds a subtype of Cat that implements interface Woofer; if it does, it will perform the cast and invoke woof() and if it doesn't, it will throw an exception.  The behavior of the code is fully defined whether felix implements Woofer or not.

C++ takes the philosophy that if a program shouldn't attempt some operation, it shouldn't matter what the generated code would do if that operation were attempted, and the computer shouldn't waste time trying to constrain behavior in cases that "should" never arise.  In C++, adding the appropriate indirection operators so as to cast a *Cat to a *Woofer, the code would yield defined behavior when the cast is legitimate, but Undefined Behavior when it is not.

Having a common base type for things makes it possible to validate casts among derivatives of that base type, and also to do try-cast operations, but validating casts is more expensive than simply assuming that they're legitimate and hoping nothing bad happens.  The C++ philosophy would be that such validation requires "paying for something you [usually] don't need".

Another problem which relates to C++, but wouldn't be a problem for a new language, is that if several programmers each create a common base, derive their own classes from that, and write code to work with things of that common base class, such code will be unable to work with objects developed by programmers who used a different base class.  If a new language requires that all heap objects have a common header format, and has never allowed heap objects which didn't, then a method which requires a reference to a heap object with such a header will accept a reference to any heap object anyone could ever create.

Personally, I think that having a common means of asking an object "are you convertible to type X" is a very important feature in a language/framework, but if such a feature isn't built into a language from the start it's difficult to add it later.  Personally, I think such a base class should be added to a standard library at first opportunity, with a strong recommendation that all objects that will be used polymorphically should inherit from that base.  Having programmers each implement their own "base types" would make passing objects between different people's code more difficult, but having a common base type which many programmers inherited from would make it easier.

ADDENDUM

Using templates, it's possible to define an "arbitrary object holder" and ask it about the type of the object contained therein; the Boost package contains such a thing called any.  Thus, even though the C++ doesn't have a standard "type-checkable reference to anything" type, it's possible to create one.  This doesn't solve the aformentioned problem with not having something in the language standard, i.e. incompatibility between different programmers' implementations, but it does explain how C++ gets by without having a base type from which everything is derived: by making it possible to create something that acts like one.


答: You could create a table called STATIC_CONTENT and have columns for a key as well as the content, active/inactive trackers, etc.  Then, create a row with a key of "HomePage" and in your homepage, load the static content for that key and display it.  That way, when you have other static content (about page, contact page, etc.), you can add rows to that table.</p>


问:
How should I provide detailed information about an error, if not through HTTP status codes?

This question comes from here. I believe it deserves to be on its own instead of being lost in a long question with multiple points.

I'm building an API and find myself limited by HTTP error codes. They are just:

Not specific enough (example: HTTP 403 Forbidden to indicate that the price is outside of the allowed range and the same HTTP 403 Forbidden to indicate that the identifier of the product has a wrong format), and at the same time:

Many of them are useless in my case (example: HTTP 402 Payment Required).

Specifically when exceptions are encountered, can I use my own HTTP response codes? If not, what are my options if I want to provide the client with information more specific than “HTTP 500 Sorry we failed but we won't tell you why”?

Note: I develop the server and the client at the same time, so there would be no other clients accessing the API.

答:
Don't invent status codes

You are not expected to invent your own response codes, since the point of the API is to use a standard interface any developer can understand.

The fact that you maintain both the API and its client is irrelevant: since everyone can trace the calls to the API, everyone can implement a different client. The point of using standard interfaces is also:

To facilitate maintenance. If your app should later be maintained by your coworker, he can find his way with ease. He will be lost if it appears that HTTP 306 means success, HTTP 500 is a “Not found” and HTTP 909 is “Internal Server Error”, unless the error is a FileNotFound exception, in which case it's HTTP 404.

To facilitate the work of your system administrator. Tools which deal with server logs use status codes to determine whether this is a error or not. Two concrete examples are:

The displaying of the number of errors (HTTP 4xx and HTTP 5xx) for a given server and:

The tracking of hacking attempts. For instance, when I see a hacking attempt which results in HTTP 200, this immediately attracts my attention: it should be HTTP 4xx instead.

To avoid messing with your HTTP server. IIS, for instance, can easily be offended by some status codes, will catch them and generate its own responses. Configuring both your app and IIS is not always easy (and I've spent several days banging my head with this issue when I started programming ASP.NET websites).

To avoid problems with proxies. For instance, if your API is hosted on a server accessed through Nginx, I'm not sure sysadmins will be happy to spend a few hours redoing all the configuration for your app.

A basic example. When configuring failover, I use proxy_next_upstream directive which indicates in which cases Nginx should switch to the failover machine. Looking at the documentation, I have an impression that you can't set the directive to, say, HTTP 200, so if your API uses HTTP 200 as “Fatal error, all data was corrupted so you may be better using another mirror”, you're out of luck.

To avoid reinventing the wheel. Why would you waste your time standardizing your set codes, while there is already one?

To leverage support from many tools. For instance, Fiddler relies on HTTP response code to colorize the items. I'm not sure if it's easy to configure it to use different statuses. In the same way, different API testing tools may rely on status codes as well (while CURL, conveniently, couldn't care less about the response status, Python's requests package, for instance, will do a redirection in a presence of HTTP 3xx code).

By the way, browsers themselves interpret the response code:

AJAX requests returning HTTP 3xx may lead to automatic redirection.

HTTP 4xx and HTTP 5xx are displayed in red in browsers' developer tools.

Provide additional information

The response code other than HTTP 200 doesn't mean that you can't feed the client with JSON as well (unless it's HTTP 204, in which case there should be no content). This means that you're free to give as much information as you want to the client through JSON. Personally, I include:

The ID of the error in a form of a string. For instance price-range-invalid or product-not-found.

The URI containing additional help, when relevant (when the API is large enough to contain individual pages for every error message). For instance http://example.com/api/v1/errors/price-range-invalid.

The description. For instance “The current price is outside the allowed range. It should be superior to 0 and inferior or equal to 50000.”.

See also how other APIs handle the errors and what sort of information they provide. For instance, this is how Google+ API errors look like:

```<code>HTTP 403

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "ipRefererBlocked",
    "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
    "extendedHelp": "https://console.developers.google.com"
   }
  ],
  "code": 403,
  "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
 }
}
</code>```

Don't provide too much information

Finally, make sure you don't include the exception itself in the details, since it may contain sensitive information and represent a path for a hacker to explore (including the stack trace).

For instance, some PHP websites, when encountering a database related error, just show the SQL query and the error to the user. For a hacker, this is very convenient. For a legitimate user, this is just unfriendly and unhelpful. Don't do that.

Body:
Don't invent status codes

You are not expected to invent your own response codes, since the point of the API is to use a standard interface any developer can understand.

The fact that you maintain both the API and its client is irrelevant: since everyone can trace the calls to the API, everyone can implement a different client. The point of using standard interfaces is also:

To facilitate maintenance. If your app should later be maintained by your coworker, he can find his way with ease. He will be lost if it appears that HTTP 306 means success, HTTP 500 is a “Not found” and HTTP 909 is “Internal Server Error”, unless the error is a FileNotFound exception, in which case it's HTTP 404.

To facilitate the work of your system administrator. Tools which deal with server logs use status codes to determine whether this is a error or not. Two concrete examples are:

The displaying of the number of errors (HTTP 4xx and HTTP 5xx) for a given server and:

The tracking of hacking attempts. For instance, when I see a hacking attempt which results in HTTP 200, this immediately attracts my attention: it should be HTTP 4xx instead.

To avoid messing with your HTTP server. IIS, for instance, can easily be offended by some status codes, will catch them and generate its own responses. Configuring both your app and IIS is not always easy (and I've spent several days banging my head with this issue when I started programming ASP.NET websites).

To avoid problems with proxies. For instance, if your API is hosted on a server accessed through Nginx, I'm not sure sysadmins will be happy to spend a few hours redoing all the configuration for your app.

A basic example. When configuring failover, I use proxy_next_upstream directive which indicates in which cases Nginx should switch to the failover machine. Looking at the documentation, I have an impression that you can't set the directive to, say, HTTP 200, so if your API uses HTTP 200 as “Fatal error, all data was corrupted so you may be better using another mirror”, you're out of luck.

To avoid reinventing the wheel. Why would you waste your time standardizing your set codes, while there is already one?

To leverage support from many tools. For instance, Fiddler relies on HTTP response code to colorize the items. I'm not sure if it's easy to configure it to use different statuses. In the same way, different API testing tools may rely on status codes as well (while CURL, conveniently, couldn't care less about the response status, Python's requests package, for instance, will do a redirection in a presence of HTTP 3xx code).

By the way, browsers themselves interpret the response code:

AJAX requests returning HTTP 3xx may lead to automatic redirection.

HTTP 4xx and HTTP 5xx are displayed in red in browsers' developer tools.

Provide additional information

The response code other than HTTP 200 doesn't mean that you can't feed the client with JSON as well (unless it's HTTP 204, in which case there should be no content). This means that you're free to give as much information as you want to the client through JSON. Personally, I include:

The ID of the error in a form of a string. For instance price-range-invalid or product-not-found.

The URI containing additional help, when relevant (when the API is large enough to contain individual pages for every error message). For instance http://example.com/api/v1/errors/price-range-invalid.

The description. For instance “The current price is outside the allowed range. It should be superior to 0 and inferior or equal to 50000.”.

See also how other APIs handle the errors and what sort of information they provide. For instance, this is how Google+ API errors look like:

HTTP 403

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "ipRefererBlocked",
    "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
    "extendedHelp": "https://console.developers.google.com"
   }
  ],
  "code": 403,
  "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
 }
}

Don't provide too much information

Finally, make sure you don't include the exception itself in the details, since it may contain sensitive information and represent a path for a hacker to explore (including the stack trace).

For instance, some PHP websites, when encountering a database related error, just show the SQL query and the error to the user. For a hacker, this is very convenient. For a legitimate user, this is just unfriendly and unhelpful. Don't do that.


问:
Is there a (systematic) way to convert a recursive program to a version using user stack?
I have an image (an array of 1000 x 1000 pixels) of 1s and 0s. I was asked to do edge detection, so I wrote this program in C to traverse the figure. My idea was to convert every pixel surrounded by like pixels to white (1) and every pixel surrounded by at least one unlike pixel to black (0). And I used recursion.

This worked when the figure was small but I'm getting a "stack overflow" message with larger figures.

Is there some systematic technique to convert this to a "non-recursive" program - simulating recursion using a user defined stack?

答:
Read about call stack, tail calls, continuations, and continuation-passing style (CPS).

Then read about CPS conversion (or CPS transform). It a s systematic way to tranform a deep call stack into heap allocated structure and control.

There is no magic bullet here, CPS-conversion is just allocating the equivalent of call frames in the heap.

Read also Appel's book Compiling with Continuations and his old paper Garbage Collection can be Faster than Stack Allocation

In practical terms, you might be able to transform your naive C code by allocating most of the data in the heap.

Another way of thinking at that is to "invent" a specialized byte code (for your algorithm) and implement its stack based interpreter.

See also Gabriel Kerneis' Continuation Based C

The (Deutch-) Schorr Waite graph marking algorithm might also be inspirational.


答:
The only status codes you need from HTTP are 200 for Success and 500 for failure, so that you know whether you are having a successful conversation or not.  (Perhaps also 404 if your API is not the only application running on your server.)

Once a successful conversation has been established, then any other error that might happen has absolutely nothing to do with the communication protocol; it is an error which is specific to your application, so it should be communicated within your XML or JSON or whatever it is that you are using to implement your API.

Always keep this question in mind:

What if you were communicating over a medium other than HTTP?

Title: How should I provide detailed information about an error, if not through HTTP status codes?

Body:
This question comes from here. I believe it deserves to be on its own instead of being lost in a long question with multiple points.

I'm building an API and find myself limited by HTTP error codes. They are just:

Not specific enough (example: HTTP 403 Forbidden to indicate that the price is outside of the allowed range and the same HTTP 403 Forbidden to indicate that the identifier of the product has a wrong format), and at the same time:

Many of them are useless in my case (example: HTTP 402 Payment Required).

Specifically when exceptions are encountered, can I use my own HTTP response codes? If not, what are my options if I want to provide the client with information more specific than “HTTP 500 Sorry we failed but we won't tell you why”?

Note: I develop the server and the client at the same time, so there would be no other clients accessing the API.


答:
What you are doing is a variation on blob coloring or 8-way connectivity.

The traditional solution for this is recursive, and it can get into trouble with large blobs.

Years ago, a very brilliant young coworker came up with a way to do nonrecursive 8-way connectivity. It used two loops, one over the rows, one of the columns in each row, and a loop body that looked at the four "successor" pixels (East, Southeast, South, Southwest).

There was one catch and one minor gotcha.

The catch was that you had to maintain an auxiliary table of "equivalent colors", to handle the cases where two blobs that you thought were separate turned out to be connected.  (Imagine a large letter X.  Until you see the center of the X, you could be looking at a backslash and a slash.)

The minor gotcha was that the loop body had to be written in C macros, because subroutine call overhead was eating it alive.

This should give you something to think about.

Title: Is there a (systematic) way to convert a recursive program to a version using user stack?

Body:
I have an image (an array of 1000 x 1000 pixels) of 1s and 0s. I was asked to do edge detection, so I wrote this program in C to traverse the figure. My idea was to convert every pixel surrounded by like pixels to white (1) and every pixel surrounded by at least one unlike pixel to black (0). And I used recursion.

This worked when the figure was small but I'm getting a "stack overflow" message with larger figures.

Is there some systematic technique to convert this to a "non-recursive" program - simulating recursion using a user defined stack?


问:
How to represent hard-to-calculate "properties" of "objects" in functional code?
I have a polyline "class" in my Clojure program, which is represented by a vector of points. (It's not really a class or anything.)

The polyline's length (in the geometric sense) is something that is often needed for computations. It's also fairly slow to calculate every time it's needed.

In OO code, I'd just have the length as a property of the Polyline class.

But in functional code, I'm lost. Do I duplicate the OO pattern and make the polyline a map of {:points points, :length (length points)}? Do I make a length function and memoize it? Do I just depend on the compiler to cache the results?

答:
The most literal and direct answer to the asked question is "you don't."

More helpful but still not quite sufficient as an answer is "as function results."

Neither is completely enough when just starting out looking at things from a functional viewpoint though so let me share some things that helped me.

Functions are not methods — Functions operate on whatever is passed to them, not the 'attributes' of their 'object'. They are not bound to a thing. This is easy to grasp but equally easy to forget. In OO methods and functions are treated as synonyms.

The OO concept 'object' isn't helpful — data is a thing of its own and functions are things of their own. They are not bound together into a conceptual unit.

Data doesn't have 'properties' in the OO sense — Since your data isn't an instance it doesn't carry around details within that instance. And you probably don't want to subvert this. Doval and user39685 touch on why in their comments. I do also, below.

Looked at this way you don't really have a polyline 'class'. You have polylines as a concept and you have chosen to represent this concept as a vector of points. Since it is a vector you use it like any other vector!

If it was a vector of names and you needed how many, you'd call length. If it was a vector of airplanes and you needed how many, you'd call length, etc. all the same!

If performance is a problem then you start looking at changing the algorithm, datatype, or both. After profiling.

As user39685 said in his comment "beware of premature optimization." If it turns out you spend all your time calculating the length of points then you memoize or wrap the polyline up in a map with a :length key like you have (but think twice because now you have a special snowflake to support, see below).

If you don't rush to bundle your data up into ad-hoc objects you don't have to un-bundle to use all the primitive functions already written for you. Your functions then also tend to become smaller, simpler, and more general because you don't have to wrap and unwrap or parse and bundle data before operating on it.


问:
Determine exact coordinates for a map image?
My brother suggested that I should write a web app that lets students create and print blank maps. A blank map is a map that contains country borders, waters etc. but no text labels. The first use case is the following:

User selects 'Hungary' from a list. A blank map of Hungary appears on screen.

User enters a name of a Hungarian town or place in a textbox. A small marker appears on the map in the specified place, but without a text label.

User repeats step 2 as many times as he wishes, with different towns.

User prints the resulting image and uses it to practice for his upcoming history or geography exam. The exam task is the same: receiving a blank map with textless markers and you have to fill in the town names from memory.

So I started to write the app, and at step 1, I've ran into the first problem. I don't have a database of blank maps. In order to let the user select a blank map from a list, someone has to create and fill a database of blank maps, in which the maps table has the following (pseudo-)definition:

```<code> CREATE TABLE maps (
     name TEXT PRIMARY KEY,
     image BLOB,
     minlat FLOAT,
     minlon FLOAT,
     maxlat FLOAT,
     maxlon FLOAT
 );
</code>```

I decided to fill out one or two rows of this table myself, for testing. I downloaded this blank map of Hungary by a quick Google Search:

Now how on earth do I determine the coordinates? Let's try and create an overlay in Google Earth:

As you can see I didn't manage to position it precisely, the eastern borders are a bit off. So my question is:

Given an image file showing a map, how do I determine the exact lat/lon coordinates of its corners?

答:
It depends on the map. Cartographic maps are projections of a (nearly) spherical surface onto a flat, two dimensional surface. That is:

```<code>(X, Y) = Fproj(Lat, Long)
</code>```

where Fproj() is the projection function.

For instance, for a standard Mercator projection with the X axis on the equator, and the Y axis at the 0 Meridian:

```<code>X = Longitude
Y = ln(tan(Latitude) + sec(Latitude))
</code>```

If you know the type of map projection, and the lat/long of the corners of the map, you may be able to determine the lat/long based on the X,Y coordinates by doing an inverse projection.

Wolfram MathWorld has a good catalog of map projections and their inverses.

If you are interested in displaying maps based on existing latitude and longitude data, and you are willing to write your own map projection functions (most are really easy to implement), you can use any of the several sources of databases and flat files that contain country borders, lakes, rivers, etc. A short search with my favorite search engine turns up these two:

Natural Earth Data
ThematicMapping.org

If you do not know the map projection, but you know that Latitude,Longitude of several points on the map, you can use interpolation to estimate the Lat,Long of points on the map based on the Lat, Long of nearby registered points.

Body:
It depends on the map. Cartographic maps are projections of a (nearly) spherical surface onto a flat, two dimensional surface. That is:

(X, Y) = Fproj(Lat, Long)

where Fproj() is the projection function.

For instance, for a standard Mercator projection with the X axis on the equator, and the Y axis at the 0 Meridian:

X = Longitude
Y = ln(tan(Latitude) + sec(Latitude))

If you know the type of map projection, and the lat/long of the corners of the map, you may be able to determine the lat/long based on the X,Y coordinates by doing an inverse projection.

Wolfram MathWorld has a good catalog of map projections and their inverses.

If you are interested in displaying maps based on existing latitude and longitude data, and you are willing to write your own map projection functions (most are really easy to implement), you can use any of the several sources of databases and flat files that contain country borders, lakes, rivers, etc. A short search with my favorite search engine turns up these two:

Natural Earth Data
ThematicMapping.org

If you do not know the map projection, but you know that Latitude,Longitude of several points on the map, you can use interpolation to estimate the Lat,Long of points on the map based on the Lat, Long of nearby registered points.


问:
The right way to remove an item from a linked list
In this Slashdot interview Linus Torvalds is quoted as saying:

I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like

if (prev)

  prev->next = entry->next;

else

  list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common.

People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing a "*pp = entry->next".

As a PHP developer I have not touched pointers since Introduction to C in university a decade ago. However, I feel that this is a type of situation that I should at least be familiar with. What is Linus talking about? To be honest, if I were asked to implement a linked list and to remove an item, the above 'wrong' way is the way that I would go about it. What do I need to know to code as Linus says best?

I am asking here rather than on Stack Overflow as I'm not actually having an issue with this in production code.

答:
Using my L331 MS Paint skills:

The original solution is to point to Nodes via curr. In that case you check if the next node after curr has the delete value, and if so reset the curr node next pointer. The problem is that there is no node that points to the head of the list. That means there has to be a special case to check it.

What Linus (likely) proposes instead is not to save the pointer to the current examined node, but rather the pointer to the pointer to the current node (labelled pp). The operation is the same - if the pp pointer points to a node with the right value, you reset the pp pointer.

The difference comes in the very beginning of the list. While there is no Node that points to the head of the list, there is, in fact, a pointer to the head of the list. And it is just the same a pointer to a node, just as another nodes next pointer. Hence there is no need for a special clause for the beginning of the list.


问:
Does ORM promote database de-normalisation?
Doctrine and Propel both make use of single and concrete table inheritance to map object relationships. The former sees all possible fields in the class tree mapped to a single table - whereas the latter maps each class to a specific table, duplicating common fields in the inheritance hierarchy.

While this facilitates the ORM apparatus, it suggests bad database design to me. Are these bad design patterns to enforce on a database?

答:
As a rule of thumb, never model your data to meet the need of the developer (You can use Views or Sp for that, But not the Data Model).

The Data Model should be based on the Business rules of the application and performance needs.