问:
Trying to come up with a mapping convention for C# objects
so this is C# but it could apply to any OO language where different sets of objects exist across different layers of an application.

We have been trying to come up with a convention within the team for where to put the code when mapping objects in one layer to objects in another layer. For example; mapping a Data Transfer Object to a Service Object that is used by a WCF service, or something of the like.  I have the following methods that I have seen being used and am trying to decide which would be preferred by someone new looking at the code, and which of these fits best with the natural C# idioms.

These examples use AutoMapper to map an object Foo to an object Bar, but it applies to any mapping framework, or just manually creating Bar from Foo with an object initialiser.  Both these objects represent the same data, but they are in different assemblies:

1) Constructor on Bar

```<code>public class Bar
{
    public Bar(Foo foo)
    {
        Mapper.Map(foo, this);
    }
}
</code>```

2) Factory method on Bar

```<code>public class Bar
{
    public static Bar CreateFrom(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

3) Method on Foo to return Bar

```<code>public class Foo
{
    public Bar GetBar()
    {
        return Mapper.Map<Bar>(this);
    }
}
</code>```

4) Explicit type conversion operator on Foo so it can be casted to Bar

```<code>public class Foo
{
    public static explicit operator Bar(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

5) Some implementation of the factory pattern

```<code>public class BarFactory : IFactory<Bar>
{
    public Bar Create(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

6) Just doing it in the piece code you need it in

```<code>    public void SomeMethod()
    {
        Foo foo = fooRepository.GetFoo();

        //I need it to be bar now...
        Bar bar = Mapper.Map<Bar>(foo);

    }
</code>```

Disclaimer: I wish I hadn't used AutoMapper in this example.  Just imagine "AutoMapper" here reads "IMappingProvider" or "IObjectConverter" or something

答:
Normally I'd prefer #3 - GetBar is very obvious where its come from and what you're getting, but for this case, mapping classes I would often use the conversion operator.

But.. mapping doesn't seem like you're casting, you're really creating something new that is not contained within the object (where I'd use GetBar), just converting it (operator bar).

So in this case, I'd use the CreateFrom - its obvious you're making a new mapped object to represent something else that is related to Foo and not a Foo or a contained or inherited subset of Foo in any shape or form.


问:
How to deal with Interviews where HR is missing?
The situation:

Person X, who already has a full-time job, applies to Company A. Money is good at A, but the real reason X had applied is 'cause the work at A really excites X.

Next someone from the technical dept. from A calls up X, gives some assignment and holds a round of technical interview over phone. X does very well in all of it so far.

Finally, X asks the tech guy from A "What's next?" The guy says we'd get back to you in 3-4 days time and then doesn't call up in the next 3-4 days. X is confused. He's got the mail-id of the tech guy but not sure if he should inquire -- this is no HR after all. In fact HR was never anywhere in this process. What should he do?

My Take: Don't mail. You already have a full-time job and this shows desperation.

The Problem: This isn't me and people tell me that some companies wait for candidate to get back just to double check their interest level.

Update

Mailing the engineering team proved very useful, they apologized for being busy and now I am told the next round is early January.

答:
I recommend that you definitely email to follow up. But, follow up a day or two after the person said that they would follow up - if you're contacting before that point (3 or 4 days) then it looks desperate. In my experience a simple email with "Hey, thanks for taking the time to speak with me the other day. I'm definitely interested in learning more about the position. Do you have an update on next steps?"

Unfortunately, like others have said, hiring managers and hr managers are often doing 4 people's jobs at the same time, so these things slip through the cracks all the time. I've found that a simple reminder like the above will work.

Good luck!

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


答:
In all cases, I'd prefer #5.
In the 1-2-3-4 sample of code, I think that the domain object doesn't have to know DTO objects related to him.

Let's say you have

```<code>public class User
{
    ... some properties ...
}

public class UserThumbnail
{
    ... some properties ...
}
</code>```

A Domain Model object (User) doesn't have to know that a DTO object (UserThumbnail) is using User's properties, because it adds coupling between these classes, and the responsibility of creating the DTO object (UserThumbnail) is added to Domain object (User).

So if the use cases of your business doesn't specify that a User should be able to create a UserThumbnail, then I think that you should not do it. That's why classes like Factory should be used in this case: because DTO objects doesn't pollute domain objects. If a factory is used in that case, the domain object doesn't even know that DTO object exists.

For the #6, if you'd ever change AutoMapper to another mapping tool, then you'd have to search in your code. If you used a Factory, you know that all AutoMapper calls are there.

Mapper.Map is doing 2 things : Create instance and map properties. Factory Pattern is the solution if you want to isolate object creation code.

Title: Trying to come up with a mapping convention for C# objects

Body:
so this is C# but it could apply to any OO language where different sets of objects exist across different layers of an application.

We have been trying to come up with a convention within the team for where to put the code when mapping objects in one layer to objects in another layer. For example; mapping a Data Transfer Object to a Service Object that is used by a WCF service, or something of the like.  I have the following methods that I have seen being used and am trying to decide which would be preferred by someone new looking at the code, and which of these fits best with the natural C# idioms.

These examples use AutoMapper to map an object Foo to an object Bar, but it applies to any mapping framework, or just manually creating Bar from Foo with an object initialiser.  Both these objects represent the same data, but they are in different assemblies:

1) Constructor on Bar

```<code>public class Bar
{
    public Bar(Foo foo)
    {
        Mapper.Map(foo, this);
    }
}
</code>```

2) Factory method on Bar

```<code>public class Bar
{
    public static Bar CreateFrom(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

3) Method on Foo to return Bar

```<code>public class Foo
{
    public Bar GetBar()
    {
        return Mapper.Map<Bar>(this);
    }
}
</code>```

4) Explicit type conversion operator on Foo so it can be casted to Bar

```<code>public class Foo
{
    public static explicit operator Bar(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

5) Some implementation of the factory pattern

```<code>public class BarFactory : IFactory<Bar>
{
    public Bar Create(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

6) Just doing it in the piece code you need it in

```<code>    public void SomeMethod()
    {
        Foo foo = fooRepository.GetFoo();

        //I need it to be bar now...
        Bar bar = Mapper.Map<Bar>(foo);

    }
</code>```

Disclaimer: I wish I hadn't used AutoMapper in this example.  Just imagine "AutoMapper" here reads "IMappingProvider" or "IObjectConverter" or something

Body:
In all cases, I'd prefer #5.
In the 1-2-3-4 sample of code, I think that the domain object doesn't have to know DTO objects related to him.

Let's say you have

public class User
{
    ... some properties ...
}

public class UserThumbnail
{
    ... some properties ...
}

A Domain Model object (User) doesn't have to know that a DTO object (UserThumbnail) is using User's properties, because it adds coupling between these classes, and the responsibility of creating the DTO object (UserThumbnail) is added to Domain object (User).

So if the use cases of your business doesn't specify that a User should be able to create a UserThumbnail, then I think that you should not do it. That's why classes like Factory should be used in this case: because DTO objects doesn't pollute domain objects. If a factory is used in that case, the domain object doesn't even know that DTO object exists.

For the #6, if you'd ever change AutoMapper to another mapping tool, then you'd have to search in your code. If you used a Factory, you know that all AutoMapper calls are there.

Mapper.Map is doing 2 things : Create instance and map properties. Factory Pattern is the solution if you want to isolate object creation code.


问:
How to update a row in database without ID?
I've got a table with the following structure :

```<code>Col1 | Col2  | Col3
A    | B     | C
A    | C     | B
E    | D     | C
</code>```

The primary key is (Col1,Col2,Col3).

I get the data in another project and display it in view with a grid.
When the user edit a row in the grid, for example :  A,B,C -> A,B,E,  I get (A,B,E) and try to update the database. But I don't know which row must be updated if I don't have the original (A,B,C).

What's the proper way to resolve this issue ? Should I create a temporary ID on my second project ? I don't think create an specific ID in the database is a good idea.

答:
To update a row, you need to know which row to update - in this case you must store the original key somewhere. You could duplicate the key data in hidden columns in your grid control, or you could associate the a triple (or a struct) of the data with every row.

What is important is that the key for each row is saved somewhere that cannot be modified by the user (or even seen by the user). This will apply just as much if you use an identity column on your DB- you'll still need to store it, not let the user modify it, and use it to refer to the row that is changed.

When you update, you must refresh the key in your row - if you're using an id column this will not change, but if you use the 3 columns then as the user changes the data in them the DB gets updated but the key referenced in your grid must be updated too - think what happens if the user changes them again.


答:
This is one of the many instances where you should embrace the lesser evil that is Surrogate Keys. Whichever table has a primary key of (col1,col2,col3) should have an additional key created by the system, such as an identity or GUID.

You don't specify the data type of (col1,col2,col3), but if for some reason you're allergic to surrogate keys you can embrace the slightly greater evil of a "combined key", where instead of a database-created value your unique key field is derived from some other fields.  (In this instance, it'd be something like CONCAT(col1, '-', col2, '-', col3) ).

Should neither of the above be practical, you will be left with the greatest evil of having to manually specify all three columns each time you query a record.  Which means that any other object or table which references this one will need to have not one but three distinct fields to identify which record you're talking about.

Ideally, btw, you would have some business key in the actual data which you can guarantee by design will be unique, never-changing, and never-blank.  (Or at least changing so infrequently that the db can handle cascade updates reasonably well.)

You may wind up using a surrogate key for performance in such a case anyway, but that's an implementation detail rather than a data modeling requirement.

Title: How to update a row in database without ID?

Body:
I've got a table with the following structure :

```<code>Col1 | Col2  | Col3
A    | B     | C
A    | C     | B
E    | D     | C
</code>```

The primary key is (Col1,Col2,Col3).

I get the data in another project and display it in view with a grid.
When the user edit a row in the grid, for example :  A,B,C -> A,B,E,  I get (A,B,E) and try to update the database. But I don't know which row must be updated if I don't have the original (A,B,C).

What's the proper way to resolve this issue ? Should I create a temporary ID on my second project ? I don't think create an specific ID in the database is a good idea.


问:
Ways to modularize blocks of code in ASP Classic
I have one huge file.asp with all my reports. I have modularized the page using querystring, so this creates a lot of "virtual pages" with Report #1, Report #2, and so on.

I have some blocks of code I use more than once in the page. Actually I am repeating the code, but I already started to use Function to, for example format the date. But the block of codes are like panels with some selects in databases, tables, and so on... I mean, one panel can have more than 200 lines of code.

I would like to create some kind of function to reuse the code, instead of replicate it everytime. With classic asp, how many options I have? One that I have discarted is create one asp file per panel and in a master file include the panel where is necessary. I am really out of this approach. Is the Function the best approach?

答:
I was the sole author of a very large class ASP application for almost a decade. There were several things I learned along the way that improved the quality of code and speed at which I could spit it out greatly.

First of all, instead of rewriting code over and over again, create a simple function that does the heavy lifting. It sounds like you're already doing this. This allows you to write the code faster with fewer mistakes, but also allows you to change the behavior or look-and-feel of the entire application by changing a few lines of code. It was my goal to place anything that was ever repeated in a function.

Secondly was when I realized that, yes, classic ASP does support classes. Instead of writing HTML and code for each of the many many reports, I created a report class that encapsulated the functionality I needed. Then all I had to do was pass a record set to the class and the report would be generated with a couple lines of code. If I was displaying a lot of tables and later wanted to make the rows sort-able by clicking on a column header, it was a trivial thing to roll this feature out to the entire application by modifying a single class.

Here are some things I turned into classes:

Tables that displayed record sets

Form to edit database records

Database queries (I never wrote SQL inline again)

Record sets so I could convert them into tables and other display types

The last thing I did that substantially improved the quality of the application was give up on ASP completely. I use to think "I don't really need a IDE", "Debugging with print statements is good enough". How wrong I was. Now that I've transitioned to C# and MVC I could never imagine going back to classic ASP.


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答:
Like anything else in the programming world, you gotta get used to the syntax, and then it is (potentially) easier to read.

Like anything else in the programming world, there is the potential for spaghetti code or other abuses.

Like anything else in the programming world, you can either do it this way or another way.

Like anything else in the programming world, your mileage may vary.


问:
Use camera to analyze homogeneity
We are working with some screens whose in the production process change their state from a transparent state to a colored state. This colored state is achieved to block light transmittance.

In this process where the screen gets tinted, this tint must be applied homogeneously. This is a very important point of the process.

To check this homogeneity, I've been asked to develop a mobile app (Android) in which using the camera I could check if the tint is applied homogeneously.

I'm an android programmer so the knowledge about android is not a problem. But I've never worked with images this way so I ignore if such a thing like this could be done.

My first idea is to develop an app which using the camera takes a photo, this is the easy part. After this, I should process the image some way that I could identify non homogeneous parts, maybe convert the image to grey scales and check for clearer or darker tones.

I'm not asking about how should I programm that, as this is just a first idea on how could I achieve this, what I'm asking help for is to know how could I do that kind of image processing that could detect homogeneity.

答:
I'm not sure why you're being asked to develop this as an Android application.  If this is a real production facility, you probably want to use some kind of industrial solution.  I would suggest contacting someone from a machine vision company like Cognex and tell them about your application.  They might have an off-the-shelf product that does exactly what you want, or can be programmed to do what you want, and will be a lot easier to integrate into your automation equipment than some kind of Android device.

Now, on to your actual question, if I was attacking that problem, I would try executing a histogram function on it.  I'd look at many samples of "good" vs. "bad" product and what those histograms looked like, and see if there are some easy limits that could be setup to sort the good from the bad ones.

As with most machine vision applications, lighting is critical.  Don't believe you can just take a flash photo and have it be consistent.  You need to have very consistent lighting and you need to experiment with front, rear, and side lighting to see what brings out the most contrast of the characteristics you want to measure.  Also consider using color filters on the camera, or even going with an infrared or UV light and infrared/UV camera/filter to see if that makes it easier to detect the defects.

Title: Use camera to analyze homogeneity


问:
Weight based mapping algorithm
I am writing automatic assignment of tasks to the users. Every user has a weight (integer) and tasks should be distributed to the users according to their weights. For example
I have 10 tasks and User A with weight 5, User B with weight 3 and User C with weight 2.
Mapping function should assign User A with 5 task, B with 3 tasks, C with 2.
This example is very straightforward, but it is not that easy when it comes to 34 users and 230 tasks for example.
Is there any known algorithm i should look for?</p>

答:
The algorithm seems simple enough, apart from rounding errors.

Add up all the weights => Wt.

Allocate each user a number of tasks = N times user weight Wx / Wt, rounded down.

There should be about N/2 task left over due to rounding. Allocate 1 task to each user in descending order of magnitude of rounding error (or any other algorithm if you prefer).

Title: Weight based mapping algorithm


问:
What does neo4j's licensing guide mean?
There are three versions of Neo4j apparently, called Community, Advanced, and Enterprise.  Neo4j's Licensing Guide says that Community is GPL3 (which I confirmed from the LICENSE file in the tarball) and the Advanced/Enterprise seems to be dual licensed under AGPL3 and a proprietary license.  What exactly does statement of the guide mean?:

If you’re using Neo4j to build closed-source online applications that are central to your business, then you’ll want to talk to us about commercial licensing of Neo4j Advanced or Enterprise editions.

What exactly is meant by a closed source application in the context of server software?  Does writing software that merely talks to neo4j over RPC trigger the AGPL under Neo's interpretations? If so, that's vastly differently from how the 10gen treats MongoDB (AGPL).

The above wouldn't be as confusing if it weren't for the following statement:

... you’re free to use the Community edition of Neo4j Server under a GPL license – which means you can use it anywhere you would use something like MySQL. Used in this way, only changes you make to the Neo4j software itself should be open-sourced and shared with the community.

That last sentence is not required of GPL3 software modified for an organization but never distributed and only ever made available as a web application. In fact that's the exact reason AGPL3 was invented, to plug that gap.

Further, the following statement makes no sense since a public domain project is a project without copyright:

We love open source development: so you are free to use all Neo4j components for your open-source, public domain project under either the GPL (for Community edition) or the AGPL (for Advanced and Enterprise).

答:
My reading is that those quotes you provide from the guide are written by someone with a less than perfect grasp of copyright and software licensing issues, and possibly other motivations.

Your rights in using any piece of software not owned by you are strictly governed by the licence you hold for that software. If the actual licence that accompanies the software from an authorised distribution is GPL3 then you are obliged to adhere to the terms of that licence, and nothing you find elsewhere can change that. The licence with the software is the licence for the software.

It's hardly surprising that a commercial organisation will write words that encourage potential users of its sofware to choose a licence that provides them with revenue, rather than one that does not. Those words carry no force as far as licensing is concerned. They might have meaning from a contractual or trade description point of view, but that wasn't the question.

Title: What does neo4j's licensing guide mean?


问:
How to model a one-mandatory-of-many relationship
I have following class model that I'm quite happy with:

A Whole has a special mandatory Part. Furthermore it has a collection of parts, that contains at least the mandatory part, but may contain many more. In the OO model parts don't need to know where they belong.

So now I came up with this RDB model:

```<code>Whole:
   id - primary key
   special_part_id - non-nullable, unique, foreign key to Part

Part:
   id - primary key
   whole_id - non-nullable, foreign key to Whole
</code>```

The only constraint that is not checked here is Whole = Whole.special_mandatory_part.whole.

However, with this table layout I'm not even able to insert rows. Might be worth mentioning that I'm using an ORM, but even with plain SQL I would not know how to do it.

So my questions are:

Is this DB design bad, and if so why?

If not, how would you insert rows?

What design would you recommend and why?

I'm aware of this very similar question. However, because of the not null constraint my problem is slightly different (worse I'd say) and I'm not satisfied with the given answers.

UPDATE Just found an answer on how to insert rows with a table layout like this.

答:
First the evident errors:

special_part_id in Whole shouldn't exist

whole_id in Part should be a FK to Whole, not to user

That way the relationships is that Whole is comprised of one or more parts.

Now to clarify something:

Conceptually you can model a one-to-many relationship that is mandatory both ways, but physically it's imposible to implement. You can only implement it being mandatory on one side and not-mandatory in the other. In this case, it's mandatory on the Part side, but optional on the Whole side.


答: Send an e-mail asking for an update or discuss it over lunch somewhere.  A date may not be a bad idea if one wanted to get to know more about the place and other intelligence information.  X shouldn't get too emotionally invested in this though as sometimes things can happen like HR finding out and scolding the manager, the manager was sick, or any of 101 other things that could delay the news.</p>

Title: How to deal with Interviews where HR is missing?

Body:
The situation:

Person X, who already has a full-time job, applies to Company A. Money is good at A, but the real reason X had applied is 'cause the work at A really excites X.

Next someone from the technical dept. from A calls up X, gives some assignment and holds a round of technical interview over phone. X does very well in all of it so far.

Finally, X asks the tech guy from A "What's next?" The guy says we'd get back to you in 3-4 days time and then doesn't call up in the next 3-4 days. X is confused. He's got the mail-id of the tech guy but not sure if he should inquire -- this is no HR after all. In fact HR was never anywhere in this process. What should he do?

My Take: Don't mail. You already have a full-time job and this shows desperation.

The Problem: This isn't me and people tell me that some companies wait for candidate to get back just to double check their interest level.

Update

Mailing the engineering team proved very useful, they apologized for being busy and now I am told the next round is early January.


问:
What is the "1620's multiplication operation"?
I was stumbling through Wikipedia when I came across the entry for FLOPS, specifically the table in this section.

The first entry is for a computer from 1961, the comment on the right reads

The 1620's multiplication operation takes 17.7 ms.[46]

What is this operation?

I assume it means it can do multiplication in 17.7ms?

答:
From the previous column in that table, the "1620" is the IBM 1620.

https://en.wikipedia.org/wiki/IBM_1620

And yes it means multiplying two numbers.


答:
The IBM 1620 was an inexpensive (lower end model around $88k USD circa 1959) scientific computer that did all arithmetic (including addition and multiplication) via table look-up.  Thus multiplication, requiring multiple look-ups, was quite slow (many milliseconds per).  However, computers that could do arithmetic operations faster, at that time, were far more expensive.

See: http://en.wikipedia.org/wiki/IBM_1620

Title: What is the "1620's multiplication operation"?

Body:
I was stumbling through Wikipedia when I came across the entry for FLOPS, specifically the table in this section.

The first entry is for a computer from 1961, the comment on the right reads

The 1620's multiplication operation takes 17.7 ms.[46]

What is this operation?

I assume it means it can do multiplication in 17.7ms?


答:
The wikipedia section you posted has a reference which links to a document.

That document states that the IBM 1620 Data Processing System could multiply 10 digit numbers in 17,700 microseconds (17,7 ms)

Nor clear whether it's the multiplication of two ten-digit numbers or that the number of digits of both operands add up to ten ( like 1000 * 100000 ).


问:
Concurrency: How do you approach the design and debug the implementation?
I've been developing concurrent systems for several years now, and I have a pretty good grasp on the subject despite my lack of formal training (i.e. no degree).  There's a few new languages that have become popular to at least talk about lately that are designed to make concurrency easier such as Erlang and Go.  It appears that their approach to concurrency echoes my own experience as to how to make systems scalable and take advantage of multiple cores/processors/machines.

However, I find that there are very few tools to help visualize what you intend to do, and verify that you are at least close to your original vision.  Debugging concurrent code can be a nightmare with languages that are not designed for concurrency (like C/C++, C#, Java, etc.).  In particular, it can be near impossible to recreate conditions that happen readily on one system in your development environment.

So, what are your approaches to designing a system to deal with concurrency and parallel processing?  Examples:

How do you figure out what can be made concurrent vs. what has to be sequential?

How do you reproduce error conditions and view what is happening as the application executes?

How do you visualize the interactions between the different concurrent parts of the application?

I have my own answers for some of these, but I'd also like to learn a bit more.

Edit

So far we have a lot of good input.  Many of the articles linked to are very good, and I've already read some of them.

My personal experience with concurrent programming leads me to believe you need a different mindset than you do with sequential programming.  The mental divide is probably as wide as the difference between object oriented programming and procedural programming.  I'd like this set of questions to focus more on the thought processes necessary (i.e. theory) to systematically approach the answers.  When providing more concrete answers, it helps to provide an example--something you went through personally.

Goal for the Bounty

Don't tell me what I should do.  I already have that under control.  Tell me what you do.  Tell me how you solve these problems.

答:
Working in multi-threading environment is tough and needs the coding discipline. You need to follow the proper guideline for taking the lock, releasing lock, accessing global variables etc.

Let me try to answer your question one bye one

```<code>* How do you figure out what can be made concurrent vs. what has to be sequential?
</code>```

Use concurrency for

1) Polling :- need a thread to continuously poll something or send the update on regular basis. (Concepts like heart-bits, which send some data on regular interval to central server to say that I am alive.)

2) The operations which has heavy i/o could be made parallel. The best example is logger. The logger thread could be a separate thread.

3) Similar tasks on different data. If there is some task which happens on different data but very similar in nature, different threads can do this. Best example will be server requests.

And off course many others like this depending on application.

```<code>* How do you reproduce error conditions and view what is happening as the application executes?
</code>```

Using logs and debug prints in the logs. Try to log also the thread id so you can see what is happening in each thread.

One way to produce error condition is to put the deliberate delay (in debug code) in the places where you think the issue is happening, and forcefully stopping that thread. Similar things can be done in debuggers too, but I haven't done it so far.

```<code>* How do you visualize the interactions between the different concurrent parts of the application?
</code>```

Put the logs in your locks, so that you will know who is locking what and when, and who has tried for lock. As I said earlier try to put thread id in the log to understand what is going on in each thread.

This is just my piece of advice which is of around 3 years of working on multithread application, and hope it helps.

Body:
Working in multi-threading environment is tough and needs the coding discipline. You need to follow the proper guideline for taking the lock, releasing lock, accessing global variables etc.

Let me try to answer your question one bye one

* How do you figure out what can be made concurrent vs. what has to be sequential?

Use concurrency for

1) Polling :- need a thread to continuously poll something or send the update on regular basis. (Concepts like heart-bits, which send some data on regular interval to central server to say that I am alive.)

2) The operations which has heavy i/o could be made parallel. The best example is logger. The logger thread could be a separate thread.

3) Similar tasks on different data. If there is some task which happens on different data but very similar in nature, different threads can do this. Best example will be server requests.

And off course many others like this depending on application.

* How do you reproduce error conditions and view what is happening as the application executes?

Using logs and debug prints in the logs. Try to log also the thread id so you can see what is happening in each thread.

One way to produce error condition is to put the deliberate delay (in debug code) in the places where you think the issue is happening, and forcefully stopping that thread. Similar things can be done in debuggers too, but I haven't done it so far.

* How do you visualize the interactions between the different concurrent parts of the application?

Put the logs in your locks, so that you will know who is locking what and when, and who has tried for lock. As I said earlier try to put thread id in the log to understand what is going on in each thread.

This is just my piece of advice which is of around 3 years of working on multithread application, and hope it helps.


问:
How do I fix an "emergent" bug?
I'm writing a PDE solver, and I have a bug that only shows up in very large test cases. That is, with small grids the program gives correct answers, but there's a large amount of unaccounted-for error (I've accounted for roundoff, discretization, and other standard types of error that unavoidably occur) that creeps in when my test cases get into the days-to-finish range.

I can't run this in a debugger, that would take weeks. And printing out intermediate results is not particularly useful given that I can't manually inspect the output to see what's wrong.

How can I find and fix this "emergent" bug?

答: Examine a passing test case that closely resembles the failing situation.  Then look at what do they do differently.  Maybe even modify the passing test so it is closer in behavior to the failing test.  If it suddenly starts failing then you know where to start looking.</p>

Title: How do I fix an "emergent" bug?


答:
Some suggestions:

One thing you can do is to try to narrow down the problem through geometric bisection.  (I've used this fairly successfully in investigating CAD regeneration failures for extremely complex geometric features.)  The idea here is to cut your failing model in half, then see if the problem reproduces itself on each half.  By doing this you may be able to narrow down a specific volume of your model that causes your solver to go out of control.

Secondly, most debuggers can attach to an already-running process.  If you can somehow add a test into your solver to detect when errors are beginning to go out of control (this test could be hardcoded to the specific model & simulation that exhibits the problem), the test code can pause execution (by putting up a "problem found, press OK" dialog if nothing else), and you can then attach the debugger to see what has happened.

Relatedly, can you make a test case which is so mathematically trivial that it is analytically solvable, and run that test case against a very large grid?  You may be able to see how errors accumulate given that you know the correct answer in advance.

Is part of the problem here that your workstation is slow and somewhat obsolescent?  You might be able to make a case to your management that your hardware needs to be upgraded to enable debugging of realistic customer simulations.

Title: How do I fix an "emergent" bug?

Body:
I'm writing a PDE solver, and I have a bug that only shows up in very large test cases. That is, with small grids the program gives correct answers, but there's a large amount of unaccounted-for error (I've accounted for roundoff, discretization, and other standard types of error that unavoidably occur) that creeps in when my test cases get into the days-to-finish range.

I can't run this in a debugger, that would take weeks. And printing out intermediate results is not particularly useful given that I can't manually inspect the output to see what's wrong.

How can I find and fix this "emergent" bug?


答:
First of all, resign yourself to the fact that this will probably take a long time to solve.  I had a bug a few years ago that took almost a year to fix, because it was so time consuming to reproduce.

One tip is to make sure your code compiles without warnings, and passes static analysis.  Get a peer review as well.  You might have something like a race condition with a 0.001% chance of occurring.  Static analysis tools can help you find those types of bugs.

Make sure your code is super clean.  Eliminate all the repetition, and make your functions small.  Take out any and all optimizations you may have done, and replace it with code that is so dead simple to read, any bugs will stick out like a sore thumb.  Only after your code works should you put optimizations back in, one by one with a test in between each.  The code that is hardest for you to read is the code most likely to contain a bug.

Write a ton of unit tests, that cover all your boundary cases of your accounted-for error.  The most likely scenario is you accidentally made a mistake with one of them.

The next thing you can do is write some extra code to help you detect and narrow down the bug.  Load it up with assertions and log entries.  Automate the detection of the bug in your intermediate results, perhaps by comparing it with a slower but more reliable algorithm.  Write code to check for conditions that should be impossible to hit, then set a breakpoint if it does.  Make it possible to save and restart your algorithm from an intermediate state.

Another interesting technique I recently saw demonstrated to great effect in this excellent TED talk is to create a visualization.  The human brain can find patterns and anomalies much, much more easily in visual form.

I will emphasize again the need to be patient.  If you try to rush and try to take shortcuts, it will likely take you longer.  Don't be afraid to make big changes for the sole purpose of debugging.  You won't waste your previous effort, that's what source control is for.

Title: How do I fix an "emergent" bug?


问:
Why can't C arrays have 0 length?
The C11 standard says the arrays, both sized and variable length "shall have a value greater than zero."  What is the justification for not allowing a length of 0?

Especially for variable length arrays it makes perfect sense to have a size of zero every once and a while.  It is also useful for static arrays when their size is from a macro or build configuration option.

Interestingly GCC (and clang) provide extensions that allow zero length arrays.  Java also allows arrays of length zero.

答: The issue I would wager is that C arrays are just pointers to the beginning of an allocated chunk of memory. Having a 0 size would mean that you have a pointer to...  nothing? You can't have nothing, so there would have had to be some arbitrary thing chosen. You can't use null, because then your 0 length arrays would look like null pointers. And at that point every different implementation is going to pick different arbitrary behaviors, leading to chaos.

Title: Why can't C arrays have 0 length?


问:
Repository pattern implementation that knows nothing about the database table and column names
I've seen around the Internet and Github, implementations for the design pattern Repository that knows about database table and column names. I was think, if I want to work with the database as a plugin, that I can unplug and plug another respecting Open/Closed for the rest of my code, my repository should not know about the column names of the database I'm using. So how to implement this pattern in a way that it can transform the result from the database into a Entity of my domain, without knowing about the database table and column names?

As my main language is PHP, I saw that in Doctrine\ORM you can easily pass different yamls or xmls config files, mapping the column names to property names on the Entity, but... I cant be a hostage of a library implementation, if I want to implement raw PDO, or any other library for my repositories that doesn't make this hydration out-of-the-box, my implementation should do, so how?

Update

Update 2

Please, take a look at: http://leocavalcante.github.io/patterns/2014/07/11/repository-pattern-and-database-schema.html

答:
The purpose of the repository is to provide an adapter around the database. It "knows about the database" so the rest of your code doesn't have to.

So it seems quite reasonable to me that if you change your database schema, you'll have to change (or altogether replace) your repositories. The point is that you only have to replace the repositories, because the implementation is hidden from the application by the interface.

If you have lots of aggregates and a repository for each of them, so replacing them wholesale is hard, you might be able to get help from an ORM, depending on the technologies you're using. A generic Repository<T> seems to be pretty common in C#, for example.

Of course, even if you're using an ORM, there still has to be some code, somewhere, which knows about the database schema. But this way it's usually tucked away in an XML mapping file (which of course has its own advantages and disadvantages).

Edit in response to your comments:

I don't really see what you're trying to achieve. In your design, it looks like the 'Hydration' objects take on the responsibility of communicating with the database and returning a domain object. So if you change your database schema, you still have to change all the Hydration objects. Your proposal does not solve your perceived problem: there has to be some code somewhere which knows about the database schema.

But your design is so much more complicated: there's an extra layer (the Repository itself) which basically does nothing.

```<code>public class FooRepository
{
    private IFooHydration _fooHydration;

    public FooRepository(IFooHydration fooHydration)
    {
        _fooHydration = fooHydration;
    }

    public Foo Get(int id)
    {
        return _fooHydration.Get(id);
    }

    public void Save(Foo entity)
    {
        _fooHydration.Save(entity);
    }
}
</code>```

It's much simpler to use an IRepository, and write different implementations of that for your different persistence methods. In short, the Repository is what you plug-in when you change databases.

ContentLicense: CC BY-SA 4.0

Body:
The purpose of the repository is to provide an adapter around the database. It "knows about the database" so the rest of your code doesn't have to.

So it seems quite reasonable to me that if you change your database schema, you'll have to change (or altogether replace) your repositories. The point is that you only have to replace the repositories, because the implementation is hidden from the application by the interface.

If you have lots of aggregates and a repository for each of them, so replacing them wholesale is hard, you might be able to get help from an ORM, depending on the technologies you're using. A generic Repository<T> seems to be pretty common in C#, for example.

Of course, even if you're using an ORM, there still has to be some code, somewhere, which knows about the database schema. But this way it's usually tucked away in an XML mapping file (which of course has its own advantages and disadvantages).

Edit in response to your comments:

I don't really see what you're trying to achieve. In your design, it looks like the 'Hydration' objects take on the responsibility of communicating with the database and returning a domain object. So if you change your database schema, you still have to change all the Hydration objects. Your proposal does not solve your perceived problem: there has to be some code somewhere which knows about the database schema.

But your design is so much more complicated: there's an extra layer (the Repository itself) which basically does nothing.

public class FooRepository
{
    private IFooHydration _fooHydration;

    public FooRepository(IFooHydration fooHydration)
    {
        _fooHydration = fooHydration;
    }

    public Foo Get(int id)
    {
        return _fooHydration.Get(id);
    }

    public void Save(Foo entity)
    {
        _fooHydration.Save(entity);
    }
}

It's much simpler to use an IRepository, and write different implementations of that for your different persistence methods. In short, the Repository is what you plug-in when you change databases.


答:
Lambda Expressions leads to less readable code if queries are too long.
However it's much better than too many nested loops.

It's better with a mixture of the two.

Write it in Lambda if it's faster (you need it to be fast) or easier to read.

Title: Does the usage of LINQ and Lambda Expressions lead to less readable code?

Body:
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?


问:
MySQL Database design - Opinions
I'm working on a web application for our business with my brother. Our application is pretty simple, and will be developed with php and mysql.

Clients and providers ABMs

Articles Inventory (we do not manage stock, because we resell from our providers)

Purchases

Account balance for our clients and providers

I'm stuck on accounting tables... Here is my model:

I'm in doubt about the account table; I'm thinking about use a trigger when purchases change Status (delivered to client) then updating the Account balance but I don't know if this model is good for managing Accounts for my Clients.

I'm looking for opinions about my mistakes!! Thank you.

答: You could use the two foreign keys as a combined primary in providers articles.  This to make sure you only have one of each provider article. Otherwise you could get duplicates with just a different ID. And try to use human readable IDs (like email addresses). Besides that I don't really see anything besides maybe the decimal-float thing. </p>

Title: MySQL Database design - Opinions


问:
Can Excel be a strong development platform?
We are a group of enthusiast engineers who are developing a series of application using Excel as our front end. We are using VBA but plan to start doing in VB.net. Some people in IT have questioned the wisdom of using Excel as a platform because it crashes, it's unsafe, difficult maintain, slow, etc.</p>

答:
If the end product that the users want is tabular data that they can edit or perform ad-hoc analysis on, then developing in Excel may be suitable or even advantageous.

The last Excel application I wrote was in a DNA sequencing lab. The application queried an Oracle database for a list of experiments to perform, organized the needed primers into 96-well plates, generated the primer ordering form, and created the table that was the input to the robot that performed the experiment. I personally wouldn't have picked Excel to do any of that, but the vendors required a spreadsheet as their order form, the robots could read Excel files, and the lab techs loved having spreadsheets to organize the thousands of experiments they had to run every month.

All that made Excel a reasonable choice for that task, but be wary of having a hammer and going in search of a nail.


答:
Have a think about how you manage all the other stuff that goes on around projects that isn't programming.  Source control, release management, merging changes from multiple developers, code reviews, testing, bug fixing, controlling user access to data & their ability to change that data, data quality management, storage backups, disaster recover etc. etc.  If you can manage all that in Excel / VBA then I would count it as a "strong development platform".

So is Excel right for your application?  Do you need the other things that Excel offers - user manipulation of the results, user-defined formatting and graphing, the ability to embed into Word documents etc., is your user community tied to the Office look and feel and resistant to change.  If yes then Excel, else no.

Finally, is Excel right for you right now.  I'd suggest you take an Agile approach to this.  You think Excel might be good.  Run with it for now.  Get a couple of iterations together and then have another think.  It provides an out-of-the-box user interface, some input validation, elementary forms layout (which will let you prototype a "real" application).  All things you will need but won't have to learn right away if you use Excel.  As you move your code to .Net you may discover a different UI will suit better.  Arrange your code in proper problem-related classes (rather than tool-related code fragments) and you should be able to re-package easily and call it from any front end you choose.

As for the problems your IT group lists, they're all true, and they will be true for any software that anyone writes, to a greater or lesser extent.  To my mind the question is whether this alternative is any more or less buggy, safe, maintainable and suited to the known requirements than that alternative.

We use Excel extensively in our business, but in a targeted way where we draw on its strengths, not as a general purpose platform.

Title: Can Excel be a strong development platform?

Body: We are a group of enthusiast engineers who are developing a series of application using Excel as our front end. We are using VBA but plan to start doing in VB.net. Some people in IT have questioned the wisdom of using Excel as a platform because it crashes, it's unsafe, difficult maintain, slow, etc.</p>


答:
Agree with Charles. There are limited conditions where programming in Excel first is a good idea. I've haven't run into one yet.
It is almost as easy to create the .NET app first and use the Excel engine for your output. Calculations / Formatting or anything you can do in VBA can be done using .NET and the Excel interface. VBA and VB.NET have the same base language but the methods of getting from A to B can be very different and in some cases radically. Initially, when I started programming in VB6 and using VBA, I did some programming in Word, Access and Excel using VBA. I found it somewhat cumbersome in comparison to just creating the VB6 app to do the same thing.</p>


问:
What does 'stage' mean in git?
I find git hard to understand as I could not find the meaning of the words used for the actions. I have checked the dictionary for the meaning of 'stage' and none of the meanings were related to source control concepts.

What does 'stage' mean in the context of git?

答:
With most other version control systems, there’s 2 places to store data: your working copy (the folders/files that you’re currently using) and the datastore (where the version control decides how to pack and store your changes). In Git there’s a third option: the staging area (or index). It’s basically a loading dock where you get to determine what changes get shipped away.

source: http://gitready.com/beginner/2009/01/18/the-staging-area.html

Title: What does 'stage' mean in git?


答: If you want a pointer to a memory address, declare one.  An array actually points at a chunk of memory you have reserved.  Arrays decay to pointers when passed to functions, but if the memory they are pointing at is on the heap, no problem.  There is no reason to declare an array of size zero.</p>

Title: Why can't C arrays have 0 length?

Body:
The C11 standard says the arrays, both sized and variable length "shall have a value greater than zero."  What is the justification for not allowing a length of 0?

Especially for variable length arrays it makes perfect sense to have a size of zero every once and a while.  It is also useful for static arrays when their size is from a macro or build configuration option.

Interestingly GCC (and clang) provide extensions that allow zero length arrays.  Java also allows arrays of length zero.


问:
How Jetbrain Phpstorm IDE is working without installed java?
As far as I know Jetbrains PHPStorm is programmed in Java but while I don't have Java installed in my Windows 7 PC, PHPstorm is installed and working without any problem.

How It's done?

答:
JetBrains bundles the version of the JDK that the IDE needs with it.  This is true for all of the different IDEs that they make.

The reason for this is to make sure that they are running with the JDK that the IDE is designed for.  If you look in the location where the IDE is installed (IDE_HOME) you will find the JRE that it is bundled with in the JRE directory.

It is recommended to use the JDK that is bundled with it unless there are specific issues that need to be handled (IT security policy, bug fix for a specific bug critical to the application).

Both running too new a JDK or to old a JDK can cause problems.  For example, at one time the JDK 1.7 from Oracle didn't support retina graphics on the Mac and would cause JetBrains products to not launch (from SO - the comments seem to imply that there are still font issues with recent versions).

So, by bundling the JDK one can be sure that its there and is the right version. That everything works as intended and that when someone calls in with a support question you can ask "Have you set the JDK to a different version than it was bundled with?" instead of "What version of the JDK are you running with?"

All this fits together to make a better user experience (you didn't have to go about trying to find the proper version of the JDK to download and install and configure the environment path... or juggle the environment path) and supportability.

As noted in this Jetbrains KB document this isn't universally true, because some operating systems (Mac OS X in particular) have a JDK bundled with them that the application can count on being there and being the version that the application is built against.


答:
Entity names should be singular (client, purchase, etc. not clients, purchases, etc. )

Relationship from purchase_article to purchase should be one to many ( being purchase the one end )

Relationship from purchase_article to article should be one to many ( being article the one end )

Relationship from provider_article to article should be one to many ( being article the one end )

Relationship from provider_article to provider should be one to many ( being provider the one end )

provider_article Pk should be (idProvider, idArticle), if you insist on using a surrogate then be sure to create an unique constraint on (idProvider, idArticle)

What's the difference between Phone and Telephone ? Seems like violating 1FN to me

What's the difference between unitPrice and Price ?

Are you sure relationship between Purchase and Account is not inverted ?

If you insist on having a surrogate PK on client, provider, etc., be sure to create unique constraint on business key to avoid duplicates.

Title: MySQL Database design - Opinions

Body:
I'm working on a web application for our business with my brother. Our application is pretty simple, and will be developed with php and mysql.

Clients and providers ABMs

Articles Inventory (we do not manage stock, because we resell from our providers)

Purchases

Account balance for our clients and providers

I'm stuck on accounting tables... Here is my model:

I'm in doubt about the account table; I'm thinking about use a trigger when purchases change Status (delivered to client) then updating the Account balance but I don't know if this model is good for managing Accounts for my Clients.

I'm looking for opinions about my mistakes!! Thank you.


问:
Multivariable decisions
I am running into a situation where my program can have different outcomes depending on the state of some variables. 4 variables are involved and they can all have different ( 3 to 4 different states). All the possible combinations are leading me to about 48 different cases which would be resolved using a 4 level deep nested if/else structure. So, I have a couple of questions,

Is there a better technique to draw logic or decision tables or some other structure so that you can model a decision tree for this many outcomes? When a decision is dependent on only 2 variables you can easily model this on a spreadsheet which is two dimensional by its nature but how do you deal with a case like the one I mentioned?

Other than a 4 level deep nested if/else structure is there a better programming technique to deal with this?

答:
I think what you're looking for is a 'decision table'

it's tedious to fill it out, but it forces you to consider all possibilities - and you may see patterns in the variable values and/or outputs that will let you write more compact if-logic

Title: Multivariable decisions


问:
What would truly happen if java.lang.String weren't final?
I'm a long time Java developer and finally, after majoring, I have time to study it decently in order to take the certification exam... One thing that has always bothered me is String being "final". I do understand it when a read about the security issues and related stuff... But, seriously, does anyone have a true example of that?

For instance, what would happen if String weren't final? Like it's not in Ruby. I haven't heard any complaints coming from the Ruby community... And I'm aware of the StringUtils and related classes that you have to either implement yourself or search over the web to just implement that behavior (4 lines of code) you're willing to.

答:
Another advantage to String being final is that it ensures predictable results, just like immutability.  String, though a class, is meant to be treated in a few scenarios, like a value type (the compiler even supports it via String blah = "test").  Therefore, if you make a string with a certain value, you expect it to have certain behavior that is inherit to any string, similar to expectations you'd have with integers.

Think about this: What if you sub-class java.lang.String and over-rode the equals or hashCode methods?  Suddenly two Strings "test" could no longer equal each other.

Imagine the chaos if I could do this:

```<code>public class Password extends String {
    public Password(String text) {
        super(text);
    }

    public boolean equals(Object o) {
        return true;
    }
}
</code>```

some other class:

```<code>public boolean isRightPassword(String suppliedString) {
    return suppliedString != null && suppliedString.equals("secret");
}

public void login(String username, String password) {
    return isRightUsername(username) && isRightPassword(password);
}

public void loginTest() {
    boolean success = login("testuser", new Password("wrongpassword"));
    // success is true, despite the password being wrong
}
</code>```

Body:
Another advantage to String being final is that it ensures predictable results, just like immutability.  String, though a class, is meant to be treated in a few scenarios, like a value type (the compiler even supports it via String blah = "test").  Therefore, if you make a string with a certain value, you expect it to have certain behavior that is inherit to any string, similar to expectations you'd have with integers.

Think about this: What if you sub-class java.lang.String and over-rode the equals or hashCode methods?  Suddenly two Strings "test" could no longer equal each other.

Imagine the chaos if I could do this:

public class Password extends String {
    public Password(String text) {
        super(text);
    }

    public boolean equals(Object o) {
        return true;
    }
}

some other class:

public boolean isRightPassword(String suppliedString) {
    return suppliedString != null && suppliedString.equals("secret");
}

public void login(String username, String password) {
    return isRightUsername(username) && isRightPassword(password);
}

public void loginTest() {
    boolean success = login("testuser", new Password("wrongpassword"));
    // success is true, despite the password being wrong
}


问:
HDD Failure Paranoia
HDD Failure Paranoia

I tend to make small programs for myself. Whenever I make an application I use a database application like MS Access or MySQL. I can CRUD my data as I want. No problem in finishing a task.

The problem is when I try exploring more into File IO. I have heard of HDD crashes due to high read/write operations. I used to think that these happened only on server machines. But then I came to know that it happens on desktop machines too! So I now I have this huge mental blockage. Whenever I try converting my former software into ones with raw FILE IO, I lose the "mental drive/motivation" and freeze. I get thoughts like "OMG this task will cause this many reads/writes to the disk". I fear for loosing my hard disk. My goodness! It has happened so many times that I wish that the computer engineers had redesigned the internals of the computer to fix the problem and so I curse them a lot. A lot of my time gets wasted remotivating myself and the projects never get completed.

Ya, ya, I know that behind the scenes the database  applications use raw File IO to do their work! But who thinks of that when using them. All you are mostly thinking of is SQL and the resulting table in the resultset/recodset. The database applications are like a black box to raw File IO.

Does anyone else think the same? Are my fears valid? What should I do? Any views/ consolations? Help! This makes me mad and unproductive!

答:
There's a lot of discussion of this and it's actively studied (obviously). The key terms are "mean time between failure" and "average failure rate", MTBF and AFR. Those failures are usually driven by how many times the drive is power cycled, not by read-write loads. Even finding numbers for read-write cycles on legacy drives is hard.

Seagate numbers here and an Ars Technica article giving stats across brands. The short version is: don't worry about it. As long as you do regular backups you'll be fine.

With solid state drives (SSDs) it's more complex. Solid state memory does often fail through write cycle exhaustion, but there is a lot of circuitry and software in the drive to stretch the 10,000 cycles of the chips out to 10x or more for the drive as a whole. Then If you don't fill the drive right up then you do the maths it usually works out that you'd need to continually rewrite a patch of disk for a year to get close to the wear limit. There are articles like this PCWorld one on what you can do to help.

Finally, your operating system is likely to be buffering your writes, and your database engine definitely is. Especially when you re-write a lot quickly the data is unlikely to end up on your disk every time. I suggest putting the database into "in memory database" mode before worrying about a ramdisk, because then the database is doing the work and it's usually easy to also go "write the whole database to disk" in one easy operation.

Title: HDD Failure Paranoia


答:
I wouldn't comment on minor details that you can fix later.
There are several structural issues here:

Why do you have a PurchaseUnitPrice in Purchase? This should be on purchaseArticle

Similarly why do you have a PurchaseQuantity in Purchase? This should also be on purchaseArticle

Some thing tells me UnitPrice is the price you got from the provider and price is the price you sell. If that is true, do NOT put in article the profit, if you want an argument, we can talk further to explain

Purchase status shouldn't be a boolean. You might want to have several options later such as 'unpaid', 'partial-paid', 'returned', etc

I assume you have a table providerArticle because an article might come from several providers. This way, make sure PurchaseArticle has a relationship with ProviderArticle not Article because you want to know the exact provider providing the article that you just sold. If my assumption is not true, simply make a many-to-many relationship between the article and the provider

Account should have a one-to-one relationship with Client' not withPurchase`

If you really want to keep track of the payments of each purchase, put a one-to-many relationship from Purchase to Payment (a new table entity)

Title: MySQL Database design - Opinions


问:
Assigning strings to pointer in C
My question is about pointers in C. As far as I've learned and searched, pointers can only store addresses of other variables, but cannot store the actual values (like integers or characters). But in the code below the char pointer c actually storing a string. It executes without errors and give the output as 'name'.

```<code>#include <stdio.h>
main()
{
  char *c;
  c="name";
  puts(c);
}
</code>```

Can anyone explain how a pointer is storing a string without any memory or if memory is created where it is created and how much size it can be created?

I tried using it with the integer type pointer

```<code>#include <stdio.h>
main()
{
  int *c;
  c=10;
  printf("%d",c);
}
</code>```

but it gave an error

```<code>cc     test.c   -o test
test.c: In function ‘main’:
test.c:5:3: warning: assignment makes pointer from integer without a cast   [enabled by default]
c=10;
^
test.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d",c);
^
</code>```

Pointers stores the address of variable then why is integer pointer different from character pointer?

Is there something I am missing?

答:
This is just the way string literals work in C. String literals like "name" are arrays of characters, it is equivalent to the five element array {'n', 'a', 'm', 'e', '\0'}. For the code

```<code>char *c;
c="name";
</code>```

the environment reserves memory for the above array already at initialization time, when the program is loaded from disk into memory. At run time, the adress of the beginning of that array is assigned to c.

Note the first piece of code of yours is not equivalent to the second, because in the first piece you assign a string literal (and not a character like 'n') to a char* variable. In the second, you try to assign an int (and not an int array) to an int*.

Here is a tutorial on strings and pointers in C with a more detailed explanation.

Title: Assigning strings to pointer in C

Body:
This is just the way string literals work in C. String literals like "name" are arrays of characters, it is equivalent to the five element array {'n', 'a', 'm', 'e', '\0'}. For the code

char *c;
c="name";

the environment reserves memory for the above array already at initialization time, when the program is loaded from disk into memory. At run time, the adress of the beginning of that array is assigned to c.

Note the first piece of code of yours is not equivalent to the second, because in the first piece you assign a string literal (and not a character like 'n') to a char* variable. In the second, you try to assign an int (and not an int array) to an int*.

Here is a tutorial on strings and pointers in C with a more detailed explanation.


问:
Why does this method return 2 values if I only ask for one and there is no sort of conditional statement anywhere?
I'm writing this very simple program from this one PDF called Think AP Java, and I can't seem to wrap my head around this:

When I write

```<code>public static double method_1(double x)
{
    double result =( x*(Math.exp(-x)  )    ) + (Math.sqrt(1-Math.exp(-x) )    );

    System.out.println(result);

    return result;
}
</code>```

I get the output of:    1.1629395387920924

But when I write:

```<code>public static double multAdd(double a, double b, double c)
{

    double result = (a*b) +c;

    System.out.println(result);
    return result;
}
</code>```

and

```<code>public static double method_2(double x)
{

    double result_1 =  (multAdd(1.0,  (Math.exp(-x)), 0.0)) ;
    double result_2 = (Math.sqrt(1.0-Math.exp(-x)));

    double final_result =  result_1 + result_2;
    System.out.println(final_result);

    return final_result;
}
</code>```

The output for method_2 is:    0.36787944117144233 AND 1.1629395387920924, printed directly over one another.

What can explain the cause of this?
Any help will be greatly appreciated, as I'm only just a beginner.

答:
When you call method_2, you are also implicitly calling multAdd. As per the definition of multAdd, you are printing the result of (a*b) + c). Once that method_2 is done with the call to multAdd, the execution will proceed with the remainder of the code in your method.

Eventually, it will reach the print statement (similar to what you have in the multAdd method). Once it hits this line, the program will print the second line. This is why you have two print statements when you call method_2.

If you want to show just one result, what you would need to do would be to omit the print statements from your methods and work with the returned value. As you can notice, all of your methods are retuning the value that they are printing.

So, you could do something like so: System.out.println(method_1(arg1)); and System.out.println(method_2(arg1));

The above code should print only two values, which are the ones you are really after.


问:
Linking to MIT-Licensed dll
I'm currently working on some closed-source proprietary software that makes use of a library (SharpAVI) distributed with the MIT License. The SharpAVI source isn't being used directly anywhere in my project, only the unchanged .dll provided for download on the codeplex site linked above.

The .dll is referenced in one very small distinct project inside a much larger solution (consisting of a single wrapper class around the functionality provided by SharpAVI).

I'm particularly concerned about this wording:

The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

Does the license need to be included in a file with my code, which is linked to the licensed code by .dll, and includes none of the original source? Would this make my wrapper code an MIT-licensed product (that would seem to go against the non-viral nature of the license)? If my wrapper needs to become licensed under the MIT License, wouldn't that propagate to any other code that references it as well?

How do I properly attribute the license information for a linked MIT-Licensed .dll without releasing my own code under the MIT License?

答:
Sounds like you need a "licenses.txt" file or similar in which you place suitable text, wording similar to suggested by Robert Harvey.

If you have a GUI you can have a Help->About menu item, which might have a nice display in which you can click a button "licenses" that in turn opens a window showing the licenses.txt file - or whatever other method you might like to use.

What you need to do is have a reasonable accessible means of showing the attribution (that you uses MIT licensed s/w).

If you have a printed or PDF user manual you might also place an attribution in some fairly obvious place: inside the front or back cover, for example. Again it only needs to be a sentence.

Title: Linking to MIT-Licensed dll


问:
when to use a scaled/enterprise agile software development framework and when to let agile processes 'emerge'?
There are quite a few enterprise agile software development frameworks available:

Scott Ambler: Disciplined Agile Delivery

Dean Leffingwell: Scaled Agile Framework

Alan Shalloway: Enterprise Agile Book

Craig Larman: Scaling Lean and Agile

Barry Boehm: Balancing Agility and Discipline

Brian Wernham: Agile Project Management for Government - DSDM, Scrum and others

I've also spoken with people that state that your enterprise agile processes should just 'emerge' and that you shouldn't need or use a framework because they constrain you.

Question 1: When should one choose an enterprise agile software development framework, and when should one just let their agile processes 'emerge'.

Question 2: If choosing an enterprise agile software development framework, how does one select the appropriate framework to use for their organisation?

Please provide evidence of your experience or research when answering questions rather than just presenting opinions.

答:
Thanks for listing my book in your top 5.

"Agile Project  Management for Government" takes a fresh approach in that I describe real life, fully attributed agile successes. These are case studies at Enterprise scale.

I do not favor DSDM (although the book starts with a DSDM case on a breakthrough in UK battlefield tech development). The spectacular use of Scrum at the FBI in the USA to save their previously failing $750m Sentinel project is a must read also. Many other examples from USA, UK and around the world.

So my recommendation is to use whichever prescriptive framework you like from the other 4 authors - but if you need to convince your management to go agile, use my book to back up your arguments with evidence.

Brian Wernham

bit.ly/Brians-Blog

London


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答:
I think it depends in most cases (except when doing something very bizarre) on if you mean "readable" as someone getting the idea of what is going on or if they can easily find all the tiny little details.

I think link helps with the former, but often (especially when debugging) hurts the latter.

IMHO when I am looking at code I am unfamiliar with the former is hugely more important than the latter, so I find it much more readable.


问:
How can I test a search engine for an uncommon human language?
We are writing a search engine from scratch in a quite uncommon language, Aramaic, mostly for learning purposes but also because few resources are available in given language.

The engine is/will be written in Python, and:

It is a human language search engine.

It's not about paying someone to do the tests, but trying to find a way to resolve the issue programmatically (if even possible) for learning purposes mostly.

We would like to test automatically if the search engine works efficiently but without knowing the language we were wondering if there were maybe tools or ways to test it get statistics. If we had users who spoke the language we could ask them to evaluate the search results but not having that, what are the other ways to test a search engine?

答:
This is a very hard problem. You are asking for an Artificial intelligence piece of software to fully comprehend the target language's semantics and culture in order to determine the results' relevance. There are a few workarounds:

Use Google/Bing/whatever other search engines exist out there for learning and testing. In effect, you would try to duplicate the ranking algorithm in a 'black box' fashion, using statistical methods to see whether the results 'align' according to some error metric.

Advertise for target language speakers online (Mechanical Turk or any other outsourcing marketplace), always checking whether the reviewers really speak kiswahili or whatever language you need.

EDIT: since this is for texts in Aramaic (I presume Old Aramaic), I'd suggest looking at  Biblical Hermeneutics.SE (hat tip to TRiG), Christianity.SE and Mi Yodeya.SE for links to online communities. There are quite a few people who are very well versed in the language.


答:
I think you need to to do a bit more analysis as to how time affects your model.

An offer to sell is at the current price

An item (or group of items) is sold at a particular price that won't ever change.

You seem to be heading down the right track with the total price being in the purchases table, but then purchases_articles links to a table that has price and profit fields that may no longer be relevant.

What I am highlighting is that it is necessary to copy fields into "logging" tables, even though this looks like denormalisation. Classical data modelling theory tends to ignore this inconvenient reality..

Title: MySQL Database design - Opinions


问:
Programming for future use of interfaces
I have a colleague sitting next to me who designed an interface like this:

```<code>public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}
</code>```

The problem is, right now, we are not using this "end" parameter anywhere in our code, it's just there because we might have to use it some time in the future.

We are trying to convince him it's a bad idea to put parameters into interfaces that are of no use right now, but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

Now, my question is, are there any sources that are handling a topic like this of "respected" coding gurus that we can link him to?

答:
[Are there] "respected" coding gurus that we can link him to [to persuade him]?

Appeals to authority are not particularly convincing; better to present an argument that is valid no matter who said it.

Here's a reductio ad absurdum that should persuade or demonstrate that your co-worker is stuck on being "right" regardless of sensibility:

What you really need is

```<code>getFooList(String fooName, Date start, Date end, Date middle,
           Date one_third, JulianDate start, JulianDate end,
           KlingonDate start, KlingonDate end)
</code>```

You never know when you'll have to internationalize for Klingon, so you better take care of it now because it will require a lot of work to retrofit and Klingons are not known for their patience.

OwnerDisplayName: sveri

Body:
[Are there] "respected" coding gurus that we can link him to [to persuade him]?

Appeals to authority are not particularly convincing; better to present an argument that is valid no matter who said it.

Here's a reductio ad absurdum that should persuade or demonstrate that your co-worker is stuck on being "right" regardless of sensibility:

What you really need is

getFooList(String fooName, Date start, Date end, Date middle,
           Date one_third, JulianDate start, JulianDate end,
           KlingonDate start, KlingonDate end)

You never know when you'll have to internationalize for Klingon, so you better take care of it now because it will require a lot of work to retrofit and Klingons are not known for their patience.

OwnerDisplayName: msw


答:
Invite him to learn about YAGNI. The Rationale part of Wikipedia page may be particularly interesting here:

According to those who advocate the YAGNI approach, the temptation to write code that is not necessary at the moment, but might be in the future, has the following disadvantages:

The time spent is taken from adding, testing or improving the necessary functionality.

The new features must be debugged, documented, and supported.

Any new feature imposes constraints on what can be done in the future, so an unnecessary feature may preclude needed features from being added in the future.

Until the feature is actually needed, it is difficult to fully define what it should do and to test it. If the new feature is not properly defined and tested, it may not work correctly, even if it eventually is needed.

It leads to code bloat; the software becomes larger and more complicated.

Unless there are specifications and some kind of revision control, the feature may not be known to programmers who could make use of it.

Adding the new feature may suggest other new features. If these new features are implemented as well, this could result in a snowball effect towards feature creep.

Other possible arguments:

“80% of the lifetime cost of a piece of software goes to maintenance”. Writing code just in time reduces the cost of the maintenance: one has to maintain less code, and can focus on the code actually needed.

Source code is written once, but read dozens of times. An additional argument, not used anywhere, would lead to time wasted understanding why is there an argument which is not needed. Given that this is an interface with several possible implementations makes things only more difficult.

Source code is expected to be self-documenting. The actual signature is misleading, since a reader would think that end affects either the result or the execution of the method.

Persons writing concrete implementations of this interface may not understand that the last argument shouldn't be used, which would lead to different approaches:

I don't need end, so I'll simply ignore its value,

I don't need end, so I'll throw an exception if it is not null,

I don't need end, but will try to somehow use it,

I'll write lots of code which might be used later when end will be needed.

But be aware that your colleague may be right.

All previous points are based on the fact that refactoring is easy, so adding an argument later won't require much effort. But this is an interface, and as an interface, it may be used by several teams contributing to other parts of your product. This means that changing an interface could be particularly painful, in which case, YAGNI doesn't really apply here.

The answer by h.j.k. gives a good solution: adding a method to an already used interface is not particularly hard, but in some cases, it has a substantial cost too:

Some frameworks don't support overloads. For example and if I remember well (correct me if I'm wrong), .NET's WCF doesn't support overloads.

If the interface has many concrete implementations, adding a method to the interface would require going through all the implementations and adding the method there too.

Title: Programming for future use of interfaces

Body:
I have a colleague sitting next to me who designed an interface like this:

```<code>public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}
</code>```

The problem is, right now, we are not using this "end" parameter anywhere in our code, it's just there because we might have to use it some time in the future.

We are trying to convince him it's a bad idea to put parameters into interfaces that are of no use right now, but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

Now, my question is, are there any sources that are handling a topic like this of "respected" coding gurus that we can link him to?


答:
but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

(some time later)

```<code>public class EventGetter implements IEventGetter {

    private static final Date IMPLIED_END_DATE_ASOF_20140711 = new Date(Long.MAX_VALUE); // ???

    @Override
    public List<FooType> getFooList(String fooName, Date start) throws Exception {
        return getFooList(fooName, start, IMPLIED_END_DATE_ASOF_20140711);
    }

    @Override
    public List<FooType> getFooList(String fooName, Date start, Date end) throws Exception {
        // Final implementation goes here
    }
}
</code>```

That's all you need, method overloading. The additional method in the future can be introduced transparently without affecting calls to the existing method.

Body:
but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

(some time later)

public class EventGetter implements IEventGetter {

    private static final Date IMPLIED_END_DATE_ASOF_20140711 = new Date(Long.MAX_VALUE); // ???

    @Override
    public List<FooType> getFooList(String fooName, Date start) throws Exception {
        return getFooList(fooName, start, IMPLIED_END_DATE_ASOF_20140711);
    }

    @Override
    public List<FooType> getFooList(String fooName, Date start, Date end) throws Exception {
        // Final implementation goes here
    }
}

That's all you need, method overloading. The additional method in the future can be introduced transparently without affecting calls to the existing method.


问:
Are there any problems with implementing custom HTTP methods?
We have a URL in the following format

/instance/{instanceType}/{instanceId}

You can call it with the standard HTTP methods: POST, GET, DELETE, PUT. However, there are a few more actions that we take on it such as "Save as draft" or "Curate"

We thought we could just use custom HTTP methods like: DRAFT, VALIDATE, CURATE

I think this is acceptable since the standards say

"The set of common methods for HTTP/1.1 is defined below. Although this set can be expanded, additional methods cannot be assumed to share the same semantics for separately extended clients and servers."

And tools like WebDav create some of their own extensions.

Are there problems someone has run into with custom methods? I'm thinking of proxy servers and firewalls but any other areas of concern are welcome. Should I stay on the safe side and just have a URL parameter like action=validate|curate|draft?

答:
I would prefer to design these as subresources, onto which you perform a POST request.

Consider you have a resource at /instance/type/1, I would have the representation of that resource convey a couple of links to 'actions' that can be performed on the resource, such as /instance/type/1/draft and /instance/type/1/curate. In JSON, this could be as simple as:

```<code>{
    "some property":"the usual value",
    "state": "we can still inform the client about the current state",
    "draft": "http://server/instance/type/1/draft",
    "curate": "http://server/instance/type/1/curate"
}
</code>```

This allows the client to be very explicit about what needs to happen, during the POST request to the link provided by the curate member. The resource posted there could include arguments that detail the event that would, perhaps, inflict a state transition.

Going with the 'naive' approach of moving between the possible states on a resource has the disadvantage of not capturing what events led to these transitions.

State transitions usually occur in response to specific events, and I'd rather capture those events than let the client decide that something is now in a specific 'state'. It also makes validation a lot harder. Plus, you wouldn't be able to capture any 'arguments' unless you describe those in the state itself as well. And then it gets all icky when some code changes those without real state transition, and the validation required, and the whole thing quickly becomes a mess.

Body:
I would prefer to design these as subresources, onto which you perform a POST request.

Consider you have a resource at /instance/type/1, I would have the representation of that resource convey a couple of links to 'actions' that can be performed on the resource, such as /instance/type/1/draft and /instance/type/1/curate. In JSON, this could be as simple as:

{
    "some property":"the usual value",
    "state": "we can still inform the client about the current state",
    "draft": "http://server/instance/type/1/draft",
    "curate": "http://server/instance/type/1/curate"
}

This allows the client to be very explicit about what needs to happen, during the POST request to the link provided by the curate member. The resource posted there could include arguments that detail the event that would, perhaps, inflict a state transition.

Going with the 'naive' approach of moving between the possible states on a resource has the disadvantage of not capturing what events led to these transitions.

State transitions usually occur in response to specific events, and I'd rather capture those events than let the client decide that something is now in a specific 'state'. It also makes validation a lot harder. Plus, you wouldn't be able to capture any 'arguments' unless you describe those in the state itself as well. And then it gets all icky when some code changes those without real state transition, and the validation required, and the whole thing quickly becomes a mess.


问:
Why isn't there a next operation on enums?
In most popular programming languages like Java and C# there is a way to define enums, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek.

The problem is, given a value, e.g. DayOfWeek.Monday, how do I get the next value of the enum, in this particular case DayOfWeek.Tuesday?

I realize that not all enums are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next operation would be sufficient in most cases. In fact, since the set of values in a enum is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.

So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next value for a enum? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.

I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place.

答:
Before Java there was C, C++ and Pascal. Enumerations in C and C++ could have wildly different values - they did not need to be contiguous integers. This had the advantage that you could define an enum for things like Windows message codes, which were a sparse set of non-contiguous integers.

(Borland) Pascal took the other approach, where all enumerations had contiguous ordinal values starting from zero. This meant set arithmetic was easy (e.g. Define Jan..Dec as an enum, then SummerMonths as a set of months (July, Aug, September). It was then legal to write if (month in SummerMonths)... It was also memory efficient, since enums could be bit-mapped.

For better or worse, Java went down the C/C++ route. For that reason, a next() operation does not make good sense.


问:
Why not apply Interface Segregation Principle to "extreme"
Providing that clients would typically consume just one method, though methods would be conceptually related, why not always apply the Interface Segregation Principle to the extreme and have [many] single-method interfaces? Is there an objective rule against this? Not something like "oh it feels wrong" or "but you will have so many types, it's hard to read and manage" but rather something logical and clear. (Still want to name contracts clearly, so functions are not a good fit?).

Example:

```<code>IGeometryManager
{
   Shape CreateTriangle();
   Shape CreateCircle();
   Shape CreateSquare();
   Shape CreateEllipse();
   Shape CreateCurve();
   Shape CreateLine();
   void RemoveAll();
}
</code>```

Result:

```<code>ITriangleCreator
{
   Shape CreateTriangle();
}

ICircleCreator
{
   Shape CreateCircle();
}

ISquareCreator
{
   Shape CreateSquare();
}

IEllipseCreator
{
   Shape CreateEllipse();
}

ICurveCreator
{
   Shape CreateCurve();
}

ILineCreator
{
   Shape CreateLine();
}

IShapeRemover
{
   void RemoveAll();
}
</code>```

This is a relevant blog post, but I am not 100% persuaded by the authors logic: http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional

答:
No, there isn't any objective rule.

If there were objective rules, someone could automate them and you'd be out of a job. Such decisions are always trade-offs between pressures that are pretty obvious in themselves, but have different relative strengths in different situations. So far, only (some) humans can properly judge such multidimensional optimization problems.


问:
Implementing a priority queue with a circular array
[If this fits more to stackoverflow then transfer it there please.]

Hi, I'm trying to implement a priority queue in C.
The easiest way I found to do it is with a circular array (rather than using a linked list).
I have an array of fixed size, the index for the first element in the queue and the index for the next free place in the queue.
But I'm struggling with dequing the maximum value...
I know how to get the maximum value, but not how to move next and first so that the queue stays contiguous in the array (the only way I know of it working).

How should I do this? Or do you have a suggestion for a better implementation?

Thanks

答:
As a simple fix you can swap the max element with first and then pop as normal.

However I suggest using a max-heap structure. This has the advantage of having only O(log n) time complexity for push and pop and can fit in your fixed size array.

Popping a value involves putting the last element in the head and shifting it down. Pushing a value involves pushing to the end and shifting it up (or recursively shifting the direct parent down until it is in place).


答:
The problem with using an array (circular or not) as underlying data structure for a priority queue is that you must always copy elements around to create a hole where a new element should be inserted or to fill the hole created by removing an element.

In a very naive implementation, using your circular array, you could use the following scheme:

When adding an element, always add it at the position indicated by next and increment next.

When removing an element, copy the element indicated by first to the position just vacated and increment first.

This scheme is easy to implement, but has the large drawback that you must loop over the entire (used portion of the) array to find the element with the highest priority.

For learning exercises, that is not a big deal, but you definitely want to avoid that in production code.

In production code, it is better to use a data structure that is continuously kept ordered on the priority of the items, so that the item with the highest priority is always at the front. This can be done with arrays (preferably regular, non-circular arrays) or linked lists. Linked lists may have a performance advantage because it is easier to add elements to the middle and to remove the first element without having to touch a bunch of other elements.

Title: Implementing a priority queue with a circular array

Body:
[If this fits more to stackoverflow then transfer it there please.]

Hi, I'm trying to implement a priority queue in C.
The easiest way I found to do it is with a circular array (rather than using a linked list).
I have an array of fixed size, the index for the first element in the queue and the index for the next free place in the queue.
But I'm struggling with dequing the maximum value...
I know how to get the maximum value, but not how to move next and first so that the queue stays contiguous in the array (the only way I know of it working).

How should I do this? Or do you have a suggestion for a better implementation?

Thanks


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答: That computers are essentially pattern matchers, nothing more. Everything boils down to the Turing Machine - the classic Computer Scienceconcept of explaining pattern maching.</p>