问:
Java & REST API: How do I check for duplicate before inserting record?
I am developing an application in Java to parse and upload records from a CSV to an online database, via a REST API.

While I know for sure that there are no duplicate records in each CSV file, I cannot be sure that each CSV file has only been processed once (*see clarification below), so I need to check for duplicates before inserting.

[CLARIFICATION] I cannot implement a solution by checking that each CSV file has only been processed once. The CSV files contain bank transaction records downloaded from a bank. Therefore I know that each individual CSV file does not contain duplicates. However, multiple CSV files could be downloaded for the same date range, or for overlapping date ranges, etc. - so I need to check for duplicates at the transaction level rather than the file level.

Unfortunately I have no control over the back-end database, and I can only use the methods available via the API. This means the usual solutions using SQL (e.g. this question) are not suitable.

Methods available from API (http://help.moneytrackin.com/index.php/REST_API):

listTransactions

editTransaction

insertTransaction

Methods available but probably not relevant:

listProjects

listWriteProjects

getBalance

getTags

newProject

deleteProject

listTagTransactions

deleteTransaction

listCurrencies

userData

It is not a huge database: only four columns, and a few thousand records.

It seems like my only option is to iterate over each record to be inserted and compare it to each record from the database:

```<code>get ListOfRecordsInDb from database using listRecords(). Store in HashMap,
    local database or similar data structure??

for each record to be inserted,
    iterate over ListOfRecordsInDb, checking none of them match
       the record to be inserted
    if no match found, insert record
</code>```

This seems very inefficient. Are there any other options? If not, what is the most efficient way to compare thousands of records, using Java?

Answers to comments/questions:

What happens if you call insertTransaction with a transaction that
  already exists? Does it duplicate it or does it fail?

The transaction is successfully inserted as a duplicate

Does the CSV file have an "id" column?

No. The available columns are Date, Description, Amount and Balance. The combination of these makes each record unique, so I could potentially create an ID based on these.

Does listRecords() allow pagination, or can it only return all of the
  records?

It only returns the records, in XML format.

答:
You are being squeezed in both directions, with tricky input and a tricky back-end. In an ideal world, you'd challenge some of these constraints, but I get the impression you won't get anywhere.

The algorithm you describe sounds like your only option, although I think it can be improved on a little.

Call listTransactions and store all transactions in a HashSet

Iterate through the CSV file:

If the line is in the HashSet, ignore

Otherwise, insertTransaction

With a few thousand rows only, I think it's acceptable to call listTransactions every time someone uploads a CSV. If the database was larger you would have to consider creating your own database, that mirrored the REST back-end, solely for the purpose of avoiding duplicates.

One thing I don't understand, although it's not that relevant, is how the REST API can have an editTransaction when the transactions don't have an ID.

Edit - ok, although the CSV file has no ID, the back-end REST service does have an ID.


问:
Should I prefer composition or inheritance in this scenario?
Consider an interface:

```<code>interface IWaveGenerator
{
    SoundWave GenerateWave(double frequency, double lengthInSeconds);
}
</code>```

This interface is implemented by a number of classes which generate waves of different shapes (for example, SineWaveGenerator and SquareWaveGenerator).

I want to implement a class that generates a SoundWave based on musical data, not raw sound data. It would receive the name of a note and a length in terms of beats (not seconds), and internally use the IWaveGenerator functionality to create a SoundWave accordingly.

Question is, should the NoteGenerator contain an IWaveGenerator or should it inherit from an IWaveGenerator implementation?

I'm leaning towards composition because of two reasons:

1- It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator, SquareNoteGenerator, etc.

2- There's no need for NoteGenerator to expose the lower-level interface defined by IWaveGenerator.

However I'm posting this question to hear other opinions regarding this, maybe points I haven't thought of.

BTW: I would say NoteGenerator is conceptually an IWaveGenerator because it generates SoundWaves.

答:
It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator, SquareNoteGenerator, etc.

That is a clear sign it would be better to use composition here, and not inherit from SineGenerator or SquareGenerator or (worse) both. Nethertheless, it will make sense to inherit a NoteGenerator directly from an IWaveGenerator if you change the latter a little bit.

The real problem here is, it is probably meaningful to have NoteGenerator with a method like

```<code>SoundWave GenerateWave(string noteName, double noOfBeats, IWaveGenerator waveGenerator);
</code>```

but not with a method

```<code>SoundWave GenerateWave(double frequency, double lengthInSeconds);
</code>```

because this interface is too specific. You want IWaveGenerators to be objects which generate SoundWaves, but currently your interface expresses IWaveGenerators are objects which generate SoundWaves from frequency and length exclusively . So better design such an interface this way

```<code>interface IWaveGenerator
{
    SoundWave GenerateWave();
}
</code>```

and pass parameters like frequency or lengthInSeconds, or a completely different set of parameters through the constructors of a SineWaveGenerator, a SquareGenerator, or whatever other generator you have in mind. This will allow you to create other kind of IWaveGenerators with completely different construction parameters. Maybe you want to add a rectangle wave generator which needs a frequency and two length parameters, or something like that, maybe you want to add a triangle wave generator next, also with at least three parameters. Or, a NoteGenerator, with constructor parameters noteName, noOfBeats, and waveGenerator.

So the general solution here is to decouple the input parameters from the output function, and make only the output function part of the interface.

ContentLicense: CC BY-SA 3.0

Body:
It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator, SquareNoteGenerator, etc.

That is a clear sign it would be better to use composition here, and not inherit from SineGenerator or SquareGenerator or (worse) both. Nethertheless, it will make sense to inherit a NoteGenerator directly from an IWaveGenerator if you change the latter a little bit.

The real problem here is, it is probably meaningful to have NoteGenerator with a method like

SoundWave GenerateWave(string noteName, double noOfBeats, IWaveGenerator waveGenerator);

but not with a method

SoundWave GenerateWave(double frequency, double lengthInSeconds);

because this interface is too specific. You want IWaveGenerators to be objects which generate SoundWaves, but currently your interface expresses IWaveGenerators are objects which generate SoundWaves from frequency and length exclusively . So better design such an interface this way

interface IWaveGenerator
{
    SoundWave GenerateWave();
}

and pass parameters like frequency or lengthInSeconds, or a completely different set of parameters through the constructors of a SineWaveGenerator, a SquareGenerator, or whatever other generator you have in mind. This will allow you to create other kind of IWaveGenerators with completely different construction parameters. Maybe you want to add a rectangle wave generator which needs a frequency and two length parameters, or something like that, maybe you want to add a triangle wave generator next, also with at least three parameters. Or, a NoteGenerator, with constructor parameters noteName, noOfBeats, and waveGenerator.

So the general solution here is to decouple the input parameters from the output function, and make only the output function part of the interface.


问:
How can I write unit tests that simplify feature implementation?
I'm a newbie to working in software development and I read a lot about how cool unit tests are. Now, I've made my first steps into a project where I'm working with a number of equally unexperienced programmers which is why we have produced a bit of spaghetti code. I'm trying to learn how to use testing and other techniques to improve the code quality but one of my newbie co-workers says that tests make things more difficult. Apparently, he has done internships in teams where unit tests were used.

He argued that tests were constantly in his way when he tried to implement a new feature. The tests would fail after he had changed the code. So he had to adapt the tests which of course increased his workload.

But that doesn't make sense to me. I thought tests were supposed to make things easier. So, I suspect that he either didn't implement the features correctly or that the unit tests were badly done. So, I'm wondering: How can I write unit tests so that they don't fail just because a new feature was implemented?

答:
He argued that tests were constantly in his way when he tried to implement a new feature. The tests would fail after he had changed the code. So he had to adapt the tests which of course increased his workload.

That is the number one way in which tests help implement new features.

The tests would fail after he had changed the code.

The code sucked. Possibly the test code sucked. More likely his code sucked. Either way, the code sucked.

Let's say that there's about a 95% chance that it was his code that sucked, 2% chance that the test code sucks on purpose ("we have to disallow case A because while it's generally perfectly fine it causes problems with strange legacy client-setup B so we're testing to make sure nobody hits it") and 3% chance that the test code sucks.

Now that's being very generous, but even if the rates were up to 99.99% this wouldn't say anything bad about that person's skill or craftsmanship. (Consider how often you hit a compiler error; that's code that sucked too bad to even run the tests, but your overall work that day may have been fantastic, as may the final product when you fixed the source of those compiler errors). Indeed, its not really generous to hit any percentages here, test code tends to be the code to blame less often just because it's changed less often so it has fewer chances to acquire new bugs. And remember we're talking about the case of an identified failure, not about how often these failures happen.

Anyway, with those percentages there is a 98% chance that something is incorrect that needs to be fixed, a 2% chance that something is incorrect outside of your control that needs to be catered for, and a 100% chance that you need to change something.

The 3% chance that the test is incorrect further break down into a few possibilities:

The test is buggy.

The test is no longer relevant.

The test is invalid for a particular case and is being applied generally.

As such, even when the test is to blame, it may not necessarily be "wrong" so much as out of date, some of the time.

In those 3% of cases, dealing with tests has cost you extra work that you wouldn't have had if you didn't use tests. But once that work is done it has added assistance to the 97% of the time when something else is to blame.

And in the 97% of times the test has led you to do more work right then but the result is that the non-test code doesn't suck any more (the 95% of the time) or deals with the external out-of-your-control issue fine (the 2% of the time). Note that the 2% not-your-fault case is still perceived by the user as "this software sucks".

So, 97% (realistically, more than that) of the time the test has made the code suck less.

Let's consider the alternatives for that 97% without the unit tests finding the flaws:

The code's problems were still there, but nothing ever hit the relevant code path in real life. (Hey, it happens).

The code's problems were found when other code wouldn't work with it.

The code's problems were found when another developer had to do something with it.

The code's problems were found in feature testing or application testing.

The code's problems were found in user-acceptance testing.

The code's problems were found after the product had been released, by annoyed users.

The code's problems were found after the product had been released, by delighted crackers who then made use of it to compromise your or your customers' security.

The code's problems weren't found, but did cause incorrect financial transactions, injury, loss of life, or continuance of enemy life. (Those last few are only applicable to increasingly specialised applications and may not apply to you, but they certainly do apply to some programmers).

Any professional programmer, and any amateur who releases their work, for that matter, will have experienced the first 6 of those cases happening. Some of us have experienced the final 2. They are the scenarios we most try to avoid, but they happen.

When items 2 through 5 happen, the impact on our workload is much greater than that of a failed unit test. Very often more time is spent dealing with these issues than developing. A great many projects have never gotten out of alpha because they never got past such issues.

For the later items in the list, the impact on workload may not be the worse thing about them.

The vast, vast majority of the time you have a failed unit test, you have been saved from one of the above scenarios. Unit testing won't save you from all of them, but it will save you from many of them.

Tests that pass are nice. They can give you a degree of confidence that at least certain bugs are not present in certain units, and that's great.

Tests that fail are the tests that have earned their keep.

One thing to note though:

The tests would fail after he had changed the code.

I hope there were also tests that failed before he had changed the code. All the tests related to the new feature should have started out failing, since the new feature wasn't implemented yet.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
I think skinning, auto-updaters that perpetually sit in the systray, applications that hijack file associations and other system settings, are straight evil.

Along with flash-only websites.

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


问:
In git, how to do versioning for a dozen libraries all worked at in parallel
We are doing projects, but we reuse a lot of code between the projects and have lots of libraries that contain our common code. As we implement new projects we find more ways to factor out common code and put it into libraries. The libraries depend on each other, and the projects depend on the libraries. Each project, and all libraries used in that project, need to use the same version of all the libraries they are referring to. If we release a piece of software we will have to fix bugs and maybe add new features for many years, sometimes for decades. We have about a dozen libraries, changes often cut across more than two, and several teams work on several projects in parallel, making concurrent changes to all these libraries.

We have recently switched to git and set up repositories for each library and each project. We use stash as a common repository, do new stuff on feature branches, then make pull requests and merge them only after review.

Many of the issues we have to deal with in projects requires us to do changes across several libraries and the project's specific code. These often include changes of library interfaces, some of which are incompatible. (If you think this sounds fishy: We interface with hardware, and hide specific hardware behind generic interfaces. Almost each time we integrate some other vendor's hardware we run into cases our current interfaces did not anticipate, and so have to refine them.) For example, imagine a project P1 using the libraries L1, L2, and L3. L1 also uses L2 and L3, and L2 uses L3 as well. The dependency graph looks like this:

```<code>   <-------L1<--+
P1 <----+  ^    |
   <-+  |  |    |
     |  +--L2   |
     |     ^    |
     |     |    |
     +-----L3---+
</code>```

Now imagine a feature for this project requires changes in P1 and L3 which change the interface of L3. Now add projects P2 and P3 into the mix, which also refer to these libraries. We cannot afford to switch them all to the new interface, run all the tests, and deploy the new software. So what's the alternative?

implement the new interface in L3

make a pull request for L3 and wait for the review

merge the change

create a new release of L3

start working on the feature in P1 by making it refer to L3's new release, then implement the feature on P1's feature branch

make a pull request, have this reviewed, and merged

(I just noticed that I forgot to switch L1 and L2 to the new release. And I don't even know where to stick this in, because it would need to be done in parallel with P1...)

This is a tedious, error-prone, and very long process to implement this feature, it requires to independent reviews (which makes it much harder to review), does not scale at all, and is likely to put us out of business because we get so bogged down in process we never get anything done.

But how do we employ branching and tagging in order to create a process that allows us to implement new features in new projects without too much overhead?

答:
Kind of putting out the obvious here, but maybe worth to mention it.

Usually, git repos are tailored per lib/project because they tend to be independent. You update your project, and don't care about the rest. Other projects depending on it will simply update their lib whenever they see fit.

However, your case seems highly dependent on correlated components, so that one feature usually affects many of them. And the whole has to be packaged as a bundle. Since implementing a feature/change/bug often requires to adapt many different libraries/projects at once, perhaps it makes sense to put them all in the same repo.

There are strong advantages/drawbacks to this.

Advantages:

Tracability: the branch shows everything changed in every project/lib related to this feature/bug.

Bundling: just pick a tag, and you'll get all the sources right.

Drawbacks:

Merging: ...it's sometimes already tough with a single project. With different teams working on shared branches, be ready to brace for impact.

Dangerous "oops" factor: if one employee messes up the repository by making some mistake, it might impact all projects & teams.

It's up to you to know if the price is worth the benefit.

EDIT:

It would work like this:

Feature X must be implemented

Create branch feature_x

All developers involved work on this branch and work paralelly on it, probably in dedicated directories related to their project/lib

Once it's over, review it, test it, package it, whatever

Merge it back in the master ...and this may be the tough part since in the meantime feature_y and feature_z may have been added too. It becomes a "cross-team" merge. This is why it is a serious drawback.

just for the record: I think this is in most cases a bad idea and should be done cautiously because the merge drawback is usually higher than the one you get through dependency management / proper feature tracking.


问:
New created custom list shape doesn't work in Microsoft Visio 2013 x64

Objective:

First, I should say what I want to do, and then I'll describe what I've done to achieve to my goal in the next (Descriptions) part.

I want to create a Custom List Master Shape from the Plain Container of the Diagram Parts section in the Insert tab of the ribbon. Then, I want to create another Master Shape that can use as the member shape for the Created Custom List Master Shape.

In other words, I want to add my Created Master Shape to my Custom List Master Shape like attaching the Member and Separator Master Shapes to the Class Master Shape of the UML Stencil.

So, I've faced with some problems in achieving to my goal that I've described them in the next parts.

Descriptions:

I've created some new Master Shapes in a "Visio Stencil (.vssx)" file as follows:

Figure 1 - New Created Master Shapes with used Master Shape

Property Master Shape (Green Box): that is created from the Member Master Shape of the UML Class Stencil (Blue Box).

Object Master Shape (Red Box): that is created from the Plain Container of the Diagram Parts section in the Insert tab of the ribbon.

The Property Master Shape is created to use as the member shape in the Object Master Shape like the Member Master Shape to use in the Class Master Shape of the UML Stencil.

Figure 2 - Class Master Shape with its Initial Members

The Property Master Shape that is created from Member Master Shape has changed as follows:

I added one Shape Data to it (Figure 3).

Figure 3 - "Shape Data" dialogue box of the Property Master Shape

I added one Data Graphic Item to it (Figure 4).

Figure 4 - "Data Graphic" and "Data Graphic Item" dialogue boxes of the Property Master Shape

I changed the "User.MemberName" Formula in the User-defined cells' section of the ShapeSheet window as follows (Figure 5):

=MID(SUBSTITUTE(TRIM(SHAPETEXT(TheText)),"[",""),1,FIND(" ",SUBSTITUTE(TRIM(SHAPETEXT(TheText)),"[",""))-1)

instead of:

=SHAPETEXT(TheText)

Figure 5 - "ShapeSheet" window of the Property Master Shape

The Object Master Shape that is created from the Plain Container has changed as follows:

I changed the contents of the cells in the User-defined cells' and Events sections of the ShapeSheet window as Figure 6:

Figure 6 - Cells in the User-defined cells' and Events sections of the ShapeSheet window after changing their contents

instead of:

Figure 7 - Cells in the User-defined cells' and Events sections of the ShapeSheet window before changing their contents

Questions:

1st Question:

Why isn't/aren't instance(s) of the Property Master Shape arranged and placed correctly after adding it/them to the instance(s) of the Object Master Shape like adding instance(s) of the Member Master Shape to the instance(s) of the Class Master Shape of the UML Stencil (Figure 8)?

Figure 8 - Comparing an instance of the Object Master Shape and one instance of the Property Master Shape with an instance of the Class Master Shape of the UML Stencil and its Initial Members

2nd Question:

Why do(es)n't instance(s) of the Object Master Shape add its Initial Members after attaching it/them to the page like adding Initial Members after adding Instance(s) of the Class Master Shape of the UML Stencil to the page (Figure 9)?

Figure 9 - Comparing an instance of the Object Master Shape with an instance of the Class Master Shape of the UML Stencil

I've added the following Formula for achieving to this objective; However, I think that it doesn't work:

=IF(LISTMEMBERCOUNT()=0,DOCMD(2270),0)

3rd Question:

Why isn't displayed a Bar in the instance(s) of the Object Master Shape to insert instance(s) of the Property Master Shape like displaying the Bar in the instance(s) of the Class Master Shape of the UML Stencil to insert its Members (Figure 10)?

Figure 10 - Comparing an instance of the Object Master Shape with an instance of the Class Master Shape of the UML Stencil for displaying the Bar to insert related Members

4th Question:

Why do(es) instance(s) of the Object Master Shape accept instance(s) of All Master Shapes except than only instance(s) of the Property Master Shape, instead of the instance(s) of the Class Master Shape of the UML Stencil that only accept(s) the instance(s) of the Member and Separator Master Shapes of the UML Stencil (Figure 11)?

Figure 11 - Comparing an instance of the Object Master Shape that accepts instance(s) of All Master Shapes with an instance of the Class Master Shape of the UML Stencil that only accepts the instance(s) of the Member and Separator Master Shapes of the UML Stencil

I've set =USE("Property") for the "User.msvSDListItemMaster" in the User-defined cells' section of the ShapeSheet window; However, I think that it doesn't work.

5th Question:

Why isn't/aren't displayed options for inserting Members on the added instance(s) of the Property Master Shape to the instance(s) of the Object Master Shape like attached instance(s) of the Member and Separator Master Shapes of the UML Stencil to the instance(s) of the Class Master Shape of the UML Stencil (Figure 12)?

Figure 12 - Comparing an instance of the Object Master Shape and one instance of the Property Master Shape with an instance of the Class Master Shape of the UML Stencil and its Members for displaying Options of the inserting members on the added members

6th (Final) Question:

Why do(es) instance(s) of the Object Master Shape behave and act like the Container while I've changed its/their Master Object to a List?

答:
Answer of 1st Question:

This problem always is for don't attend to the "Category" word. In most cases, people don't attend to that word and use the "Shape Master Name" instead of "Shape Category"; however, they're different with each other.

In my case, I was being entered the Shape Master Name (Property) for User.msvSDContainerRequiredCategories (A semicolon-delimited list of category names. Other shapes must have at least one matching name to be allowed as container members.) and User.msvSDListRequiredCategories (A semicolon-delimited list of category names. Other shapes must have at least one matching name to be allowed as list members.) instead of Shape Category (User.msvShapeCategories = Member).

Figure 1 - Comparing "Shape Master Name" with "Shape Category"

Answer of 2nd Question:

For solving this problem, we must be attended to two things:

First, We must add the shapes that we want to be added them automatically after instantiate the master shape. So, we must add the row(s) for each shape that we want to be added with name User.msvSDListItemMaster[Index] (The name or UniqueID of the master shape to create an instance of for Insert commands. The value must be placed inside a USE() function.).

As you can see, I want to add only one shape. So, I must change the name of the User.msvSDListItemMaster row to User.msvSDListItemMaster1. If I want to add more shapes in instantiate time, I must add another row like User.msvSDListItemMaster2, User.msvSDListItemMaster3 and so on.

Second and the last thing, we must add a formula to the "EventDrop" cell of "Events" section. As you can see, I've added it to my Custom List Shape as what mentioned in here and here:

Specifying an Insertion Shape

There are several ways to add a shape to a list: dragging and dropping the shape, clicking the blue insertion triangle that appears near the list edge, or right-clicking an existing member and inserting a shape. Clicking the insertion triangle and right-clicking to insert a shape both use the User.msvSDListItemMaster cell to determine what shape to add to the list. The name of the master is placed in quotes inside a USE() function (for example, USE("List member master")). If no shape is specified in User.msvSDListItemMaster, Visio will duplicate an adjacent shape in the list when inserting the shape.

It is also possible to automatically populate the list with some member shapes when the list is first dropped on the page. To do this, put the following formula in the EventDrop cell of the list, repeating the DOCMD(2270) once for each member to be added:

IF(LISTMEMBERCOUNT()=0,DOCMD(2270)+DOCMD(2270)+DOCMD(2270),0)

2270 is the command for inserting before an item in a list (visUiCmds.visCmdListInsertBefore). It is also possible to use 2271, the command for inserting after an item in a list (visUiCmds.visCmdListInsertAfter).

The problem is for 2270 number. I don't know why it doesn't work; however, when I checked the above-mentioned cell in the "Events" section of the Class Master Shape of the UML Stencil, I saw that have been used 2499 instead of 2270. So, I used that number in my formula, and it worked. If I have more than one shape for User.msvSDListItemMaster[Index] rows, I must add +DOCMD(2499) for every shape after shape 1.

Answer of 3rd Question:

This problem will solve if the problem of the 1st question be solved.

Answer of 4th Question:

This problem will solve if the problem of the 1st question be solved. As what mentioned in here and here:

Controlling List Membership

Lists have their own cells to govern list membership. Use the User.msvSDListRequiredCategories and User.msvSDListExcludedCategories cells to restrict what shapes can become list members. Because lists are also containers, it is possible for shapes to become container members of the list. The standard User.msvSDContainerRequiredCategories and User.msvSDContainerExcludedCategories cells determine this behavior. By default, Visio will attempt to add a shape to a list as a list member, but if that fails it may try to add it as a container member. The difference between a list member and a container member is that only list members will be arranged by the list and affect its size. Shape designers should manage both sets of membership cells to ensure the right results.

It's better that we use both User.msvSDListRequiredCategories and User.msvSDContainerRequiredCategories rows to get best efficiency.

Answer of 5th Question:

This problem will solve if the problem of the 1st question be solved.

Answer of 6th (Final) Question:

The answer is (here and here):

Custom Lists

Any shape that has a value of "List" for the User.msvStructureType cell is treated by Visio as a list. A list orders and arranges its member shapes automatically. Note that lists are also considered to be containers, and they have similar capabilities such as automatically moving, copying, or deleting member shapes. All of the previously mentioned container cells apply to list shapes.

Table 1. ShapeSheet container properties

User.msvSDContainerMargin

```<code>      The distance between the container boundary and member shapes.
</code>```

User.msvSDContainerResize

```<code>      The automatic-resize behavior for the shape:
</code>```

0 = No automatic resize.

1 = Expand as needed.

2 = Always fit to contents.

User.msvSDContainerStyle

```<code>      A one-based index value for the current visual style of the container.
</code>```

User.msvSDContainerStyleCount

```<code>      The total number of visual styles that the container supports.
</code>```

User.msvSDHeadingStyle

```<code>      A one-based index value for the current visual style of the container heading.
</code>```

User.msvSDHeadingStyleCount

```<code>      The total number of visual styles that the container heading supports.
</code>```

User.msvSDContainerLocked

```<code>      A Boolean value that prevents membership changes in the container.
</code>```

User.msvSDContainerRequiredCategories

```<code>      A semicolon-delimited list of category names. Other shapes must have at least one matching name to be allowed as container members.
</code>```

User.msvSDContainerExcludedCategories

```<code>      A semicolon-delimited list of category names. Other shapes with at least one matching name are disallowed as container members.
</code>```

User.msvSDContainerNoHighlight

```<code>      A Boolean value that suppresses the container highlighting when member shapes are selected or added to the container.
</code>```

User.msvSDContainerNoRibbon

```<code>      The automatic-resize behavior for the shape:
</code>```0

User.msvSDContainerHeadingEdge

```<code>      The automatic-resize behavior for the shape:
</code>```1

User.msvSDMembersOnHiddenLayer

```<code>      The automatic-resize behavior for the shape:
</code>```2

Body:
Answer of 1st Question:

This problem always is for don't attend to the "Category" word. In most cases, people don't attend to that word and use the "Shape Master Name" instead of "Shape Category"; however, they're different with each other.

In my case, I was being entered the Shape Master Name (Property) for User.msvSDContainerRequiredCategories (A semicolon-delimited list of category names. Other shapes must have at least one matching name to be allowed as container members.) and User.msvSDListRequiredCategories (A semicolon-delimited list of category names. Other shapes must have at least one matching name to be allowed as list members.) instead of Shape Category (User.msvShapeCategories = Member).

Figure 1 - Comparing "Shape Master Name" with "Shape Category"

Answer of 2nd Question:

For solving this problem, we must be attended to two things:

First, We must add the shapes that we want to be added them automatically after instantiate the master shape. So, we must add the row(s) for each shape that we want to be added with name User.msvSDListItemMaster[Index] (The name or UniqueID of the master shape to create an instance of for Insert commands. The value must be placed inside a USE() function.).

As you can see, I want to add only one shape. So, I must change the name of the User.msvSDListItemMaster row to User.msvSDListItemMaster1. If I want to add more shapes in instantiate time, I must add another row like User.msvSDListItemMaster2, User.msvSDListItemMaster3 and so on.

Second and the last thing, we must add a formula to the "EventDrop" cell of "Events" section. As you can see, I've added it to my Custom List Shape as what mentioned in here and here:

Specifying an Insertion Shape

There are several ways to add a shape to a list: dragging and dropping the shape, clicking the blue insertion triangle that appears near the list edge, or right-clicking an existing member and inserting a shape. Clicking the insertion triangle and right-clicking to insert a shape both use the User.msvSDListItemMaster cell to determine what shape to add to the list. The name of the master is placed in quotes inside a USE() function (for example, USE("List member master")). If no shape is specified in User.msvSDListItemMaster, Visio will duplicate an adjacent shape in the list when inserting the shape.

It is also possible to automatically populate the list with some member shapes when the list is first dropped on the page. To do this, put the following formula in the EventDrop cell of the list, repeating the DOCMD(2270) once for each member to be added:

IF(LISTMEMBERCOUNT()=0,DOCMD(2270)+DOCMD(2270)+DOCMD(2270),0)

2270 is the command for inserting before an item in a list (visUiCmds.visCmdListInsertBefore). It is also possible to use 2271, the command for inserting after an item in a list (visUiCmds.visCmdListInsertAfter).

The problem is for 2270 number. I don't know why it doesn't work; however, when I checked the above-mentioned cell in the "Events" section of the Class Master Shape of the UML Stencil, I saw that have been used 2499 instead of 2270. So, I used that number in my formula, and it worked. If I have more than one shape for User.msvSDListItemMaster[Index] rows, I must add +DOCMD(2499) for every shape after shape 1.

Answer of 3rd Question:

This problem will solve if the problem of the 1st question be solved.

Answer of 4th Question:

This problem will solve if the problem of the 1st question be solved. As what mentioned in here and here:

Controlling List Membership

Lists have their own cells to govern list membership. Use the User.msvSDListRequiredCategories and User.msvSDListExcludedCategories cells to restrict what shapes can become list members. Because lists are also containers, it is possible for shapes to become container members of the list. The standard User.msvSDContainerRequiredCategories and User.msvSDContainerExcludedCategories cells determine this behavior. By default, Visio will attempt to add a shape to a list as a list member, but if that fails it may try to add it as a container member. The difference between a list member and a container member is that only list members will be arranged by the list and affect its size. Shape designers should manage both sets of membership cells to ensure the right results.

It's better that we use both User.msvSDListRequiredCategories and User.msvSDContainerRequiredCategories rows to get best efficiency.

Answer of 5th Question:

This problem will solve if the problem of the 1st question be solved.

Answer of 6th (Final) Question:

The answer is (here and here):

Custom Lists

Any shape that has a value of "List" for the User.msvStructureType cell is treated by Visio as a list. A list orders and arranges its member shapes automatically. Note that lists are also considered to be containers, and they have similar capabilities such as automatically moving, copying, or deleting member shapes. All of the previously mentioned container cells apply to list shapes.

Table 1. ShapeSheet container properties

User.msvSDContainerMargin

      The distance between the container boundary and member shapes.

User.msvSDContainerResize

      The automatic-resize behavior for the shape:

0 = No automatic resize.

1 = Expand as needed.

2 = Always fit to contents.

User.msvSDContainerStyle

      A one-based index value for the current visual style of the container.

User.msvSDContainerStyleCount

      The total number of visual styles that the container supports.

User.msvSDHeadingStyle

      A one-based index value for the current visual style of the container heading.

User.msvSDHeadingStyleCount

      The total number of visual styles that the container heading supports.

User.msvSDContainerLocked

      A Boolean value that prevents membership changes in the container.

User.msvSDContainerRequiredCategories

      A semicolon-delimited list of category names. Other shapes must have at least one matching name to be allowed as container members.

User.msvSDContainerExcludedCategories

      A semicolon-delimited list of category names. Other shapes with at least one matching name are disallowed as container members.

User.msvSDContainerNoHighlight

      A Boolean value that suppresses the container highlighting when member shapes are selected or added to the container.

User.msvSDContainerNoRibbon

      A Boolean value that hides the Container Tools contextual tab in the ribbon for this container.

User.msvSDContainerHeadingEdge

      A string that designates the location of the interior of the container from the perspective of the container heading. Must be "Left", "Right", "Top", or "Bottom".

User.msvSDMembersOnHiddenLayer

      A Boolean value that determines whether Visio severs container relationships when the container or member is placed on a hidden layer. If True, Visio allows relationships to exist on the hidden layer. If False, Visio severs the relationships.

ContentLicense: CC BY-SA 4.0


问:
How to handle the problem of modified encrypted files
I have a simple encryption/decryption application that I am testing to learn more about security. I found out that if the user modifies the encrypted file, then decryption fails because the hashing algorithm doesn't generate back the original content. What are the common practices that deal with the problem of encrypted files modified by users either intentionally or unintentionally? The only thing I can think of is timestamp checking, but I am not sure how useful that is. </p>

<p>About my last statement, I guess I am not sure if there is a way to trick the OS so that the new timestamp is set back to the exact old time stamp although the content is modified. </p>

答:
... if the user modifies the encrypted file, then decryption fails ... What are the common practices that deal with the problem of encrypted files modified by users

Smack the user.

Figuratively?  Physically?  Depends on [how well you know] the user.  And how often they cause you this problem.

You can do exactly the same sort of thing with executables that aren't installed in "protected" directories; open them up in, say, Notepad, save them again and, surprise surprise, they don't work any more.

Perhaps the question should be - why are the users even aware this file exists?  It's not as if they can do anything [useful] with it.
If you save it in "My Documents" and they'll be all over it.  Drop it into "%USERPROFILE%\AppData\Roaming\ CompanyName \ AppName \" and they'll never go within a mile of it.


问:
Licensing - Restrictive Open Source License OR Custom License
I have some source code I want to release but I'm unsure of the best license to put on it. From my research such licenses as MIT and GNU are horrible as they offer little to no protection towards crediting the original authors nor controlling distribution. GPL seems to provide some protection, but users are still allowed to modify the code and redistribute it as their own and I don't want that.

What I want is relatively simple from my stand point.

User/Licensee can:

```<code> - Use source code
 - Compile source code
 - Modify source code for personal use
</code>```

User/Licensee MUST (If I [Author] Allow distribution upon request):

```<code> - Credit original author
 - Credit original hosting site
 - Link original hosting site's page with the code
 - NEVER claim or alter any credits, licenses, copyrights, etc, etc
</code>```

User/Licensee cannot:

```<code> - Distribute source code/Distribute it without author's written consent
 - Modify source code and release it
 - Create derivative works with source code
 - Use source code in other software
 - Remove/Alter copyrights, credits, licenses, etc, etc.
 - Sell source code
 - Sue/hold liable the original author in ANY way shape or form for anything (standard legal disclaimer and disclosure agreement - similar to MIT and others)
</code>```

This may seem unreasonably restrictive, but it's mostly to protect credits as I've had numerous people use my code in the past and claim it as their own or alter credits/copyrights or post it on sites that I don't want my work on.

I've looked up some licenses that seem correct to implement, but from what I can see there are problems.

MS-RSL - Restricts a lot of the clauses I have, but the user can't use the source code or can they? As it says, it's just reference material, yet they can use it for debugging/etc only. Can this license (or any) be slightly tweaked in it's terms/clauses?

No License - Just a copyright, but this seems like an oxymoron in some degrees, what notice or other conditions does it specify so the user/licensee knows what's allowed/not? Can I specify my own clauses? Is this legal? Wouldn't this be tantamount to writing my own license?

I found a site called "Binpress" where you can create your own licenses (or it seems so), but are these enforceable? There are clauses about payments and such which seem to contradict conditions. Licensees are allowed to distribute the code even when one selects "No distribution" so the conditions seem to be negligible. Anyone use this before?

Anyone know of a license that will satisfy above requirements or any advice?

P.S.

I did read other topics on the matter, but found most to be circumstantial or very vague on some matters. I read an article by Jeff Atwood, but the article "Pick a License, Any License" seemed to just regurgitate everything I already know or found out via other sites. It doesn't offer any deep in-detail information, explain each license in-depth, or explain anything related to altering/using licenses. He compared licenses to other licenses which is useless because if I don't know what license X is then comparing to license Y is about as useful as speaking Chinese to me.

Any advice or if anybody can answer the above questions it would be deeply appreciated. If you need me to give more detail then please let me know, but I think I have explained things well enough. :)

答:
The basic idea behind open-source licensing is that anyone who has (legally) obtained a copy of the source code also has the right to make modifications and the right to distribute the modified or original work. The main difference between open-source licenses is in what rights you must give away when re-distributing the work.

With one or two exceptions, all licenses require that at least the copyright and license statements must be kept intact. At most, you may add your own copyright statement if you made modifications1. The exceptions are when the work is placed in the public domain or an equivalent license (like CC0). Even a very permissive license like MIT requires that the license and copyright remain intact.

If people don't respect the license terms, then it is possible to  take legal action against them for violating your Intellectual Property rights. At the very least, you can request them to re-instate your copyright and/or license.

1. Copyright statements could be removed it it can be proven that all contributions by that copyright holder have been removed from the code.

If you don't like that basic principle behind open-source that everyone can share the code, then you should use a proprietary/closed-source license. These licenses are typically specific for a particular product or manufacturer and are not easy to re-use by someone else. Your best option is to have a lawyer write a license that exactly fits your desires.


答: You have a solid case for composition.  You may have a case to also add inheritance.  The way to tell is by looking at the calling code.  If you want to be able to use a NoteGenerator in existing calling code that expects an IWaveGenerator, then you need to implement the interface.  You're looking for a need for substitutability.   Whether it conceptually "is-a" wave generator is beside the point.

Title: Should I prefer composition or inheritance in this scenario?

Body:
Consider an interface:

```<code>interface IWaveGenerator
{
    SoundWave GenerateWave(double frequency, double lengthInSeconds);
}
</code>```

This interface is implemented by a number of classes which generate waves of different shapes (for example, SineWaveGenerator and SquareWaveGenerator).

I want to implement a class that generates a SoundWave based on musical data, not raw sound data. It would receive the name of a note and a length in terms of beats (not seconds), and internally use the IWaveGenerator functionality to create a SoundWave accordingly.

Question is, should the NoteGenerator contain an IWaveGenerator or should it inherit from an IWaveGenerator implementation?

I'm leaning towards composition because of two reasons:

1- It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator, SquareNoteGenerator, etc.

2- There's no need for NoteGenerator to expose the lower-level interface defined by IWaveGenerator.

However I'm posting this question to hear other opinions regarding this, maybe points I haven't thought of.

BTW: I would say NoteGenerator is conceptually an IWaveGenerator because it generates SoundWaves.


问:
Access modifier of abstract class constructors
What access modifier should I use for my constructors in an abstract class, given that the class cannot be instantiated?  It seems like the access modifier is superfluous and should be implicitly protected since it can only be used from within a derived class' constructor via base().

答:
As you mentioned, your options are protected and private.

protected seems like a good default, but don't forget about the case where you don't want your sub classes to invoke a specific constructor.  For example:

```<code>public abstract class AbstractBase
{
    private AbstractBase(int foo, double bar)
    {
        this.CalculatedProperty = someComplexCalculation(foor, bar);
    }

    protected AbstractBase(string XXX, string YYY, int foo, double bar)
        : this(foo, bar)
    {
        this.XXX = XXX;
        this.YYY = YYY;
    }

    protected AbstractBase(string XXX, int foo, double bar)
        : this(XXX, "There is no YYY.  There is only XXX.", foo, bar)
    {
    }

// *snip*

}
</code>```

In this (overly simplified) example, we guarantee that the values for foo, bar, and XXX are always specified and that CalculatedProperty and XXX are always set.

The private constructor allows us to have shared construction logic without code duplication.  And, because it's private, sub-classes can't accidentally partially construct themselves.

Body:
As you mentioned, your options are protected and private.

protected seems like a good default, but don't forget about the case where you don't want your sub classes to invoke a specific constructor.  For example:

public abstract class AbstractBase
{
    private AbstractBase(int foo, double bar)
    {
        this.CalculatedProperty = someComplexCalculation(foor, bar);
    }

    protected AbstractBase(string XXX, string YYY, int foo, double bar)
        : this(foo, bar)
    {
        this.XXX = XXX;
        this.YYY = YYY;
    }

    protected AbstractBase(string XXX, int foo, double bar)
        : this(XXX, "There is no YYY.  There is only XXX.", foo, bar)
    {
    }

// *snip*

}

In this (overly simplified) example, we guarantee that the values for foo, bar, and XXX are always specified and that CalculatedProperty and XXX are always set.

The private constructor allows us to have shared construction logic without code duplication.  And, because it's private, sub-classes can't accidentally partially construct themselves.


答:
Submodules

You should give a try to git submodules, as suggested in one comment.

When project P1 refers to the three submodules L1, L2 and L3, it actually stores a reference to particular commits in all three repositories: those are the working versions of each libraries for that project.

So multiple projects can work with multiple submodules: P1 might refer to the old version of library L1 while project P2 used the new version.

What happens when you deliver a new version of L3?

implement new interface in L3

commit, test, make pull request, review, merge, ... (you cannot avoid this)

ensure L2 works with L3, commit, ...

ensure L1 works with new L2, ...

ensure P1 works with the new versions of all libraries:

inside P1's local working copy of L1, L2 and L3, fetche the changes you are interested in.

commit changes, git add L1 L2 L3 to commit the new reference to modules

pull request for P1, test, review, pull request, merge ...

Methodology

This is a tedious, error-prone, and very long process to implement
  this feature, it requires to independent reviews (which makes it much
  harder to review), does not scale at all, and is likely to put us out
  of business because we get so bogged down in process we never get
  anything done.

Yes, it requires independent reviews, because you change:

the library

libraries that depend on it

projects that depend on multiple libraries

Would you be put out of business because you deliver crap? (Maybe not, actually). If yes, then you need to perform tests and review changes.

With appropriate git tools (even gitk), you can easily see which versions of the libraries each project use, and you can update them independantly according to your needs. Submodules are perfect for your situation and won't slow your process down.

Maybe you can find a way to automate part of this process, but most of the steps above require human brains. The most effective way to cut time would be to ensure your libraries and projects are easy to evolve. If your codebase can handle new requirements gracefully, then code reviews will be simpler and take little of your time.

(Edit)
another thing that might help you is to group related code reviews.
You commit all changes and wait until you propagated those changes down to all the libraries and projects that use them before sumbitting pull requests (or before you take care of them). You end up doing a bigger review for the whole dependency chain. Maybe this can help you save time if each local change is small.

Title: In git, how to do versioning for a dozen libraries all worked at in parallel

Body:
We are doing projects, but we reuse a lot of code between the projects and have lots of libraries that contain our common code. As we implement new projects we find more ways to factor out common code and put it into libraries. The libraries depend on each other, and the projects depend on the libraries. Each project, and all libraries used in that project, need to use the same version of all the libraries they are referring to. If we release a piece of software we will have to fix bugs and maybe add new features for many years, sometimes for decades. We have about a dozen libraries, changes often cut across more than two, and several teams work on several projects in parallel, making concurrent changes to all these libraries.

We have recently switched to git and set up repositories for each library and each project. We use stash as a common repository, do new stuff on feature branches, then make pull requests and merge them only after review.

Many of the issues we have to deal with in projects requires us to do changes across several libraries and the project's specific code. These often include changes of library interfaces, some of which are incompatible. (If you think this sounds fishy: We interface with hardware, and hide specific hardware behind generic interfaces. Almost each time we integrate some other vendor's hardware we run into cases our current interfaces did not anticipate, and so have to refine them.) For example, imagine a project P1 using the libraries L1, L2, and L3. L1 also uses L2 and L3, and L2 uses L3 as well. The dependency graph looks like this:

```<code>   <-------L1<--+
P1 <----+  ^    |
   <-+  |  |    |
     |  +--L2   |
     |     ^    |
     |     |    |
     +-----L3---+
</code>```

Now imagine a feature for this project requires changes in P1 and L3 which change the interface of L3. Now add projects P2 and P3 into the mix, which also refer to these libraries. We cannot afford to switch them all to the new interface, run all the tests, and deploy the new software. So what's the alternative?

implement the new interface in L3

make a pull request for L3 and wait for the review

merge the change

create a new release of L3

start working on the feature in P1 by making it refer to L3's new release, then implement the feature on P1's feature branch

make a pull request, have this reviewed, and merged

(I just noticed that I forgot to switch L1 and L2 to the new release. And I don't even know where to stick this in, because it would need to be done in parallel with P1...)

This is a tedious, error-prone, and very long process to implement this feature, it requires to independent reviews (which makes it much harder to review), does not scale at all, and is likely to put us out of business because we get so bogged down in process we never get anything done.

But how do we employ branching and tagging in order to create a process that allows us to implement new features in new projects without too much overhead?


问:
Should one use many small configuration files for script or a single large configuration file?
I have a script which starts from cron with regular interval and sources in around 10 variables. Should I keep those 10 variables in one configuration file in file system or is it a better practice to keep a separate configuration file for each variable? What are the advantages of one approach over another?</p>

答:
I would tell you to go to the single file approach, because the other approach (many single-variable files) is at least extremely unorthodox.

The advantage of the single file approach, which has been used successfully for decades, is that all configuration settings of a program (or aspect of a program*) can be moved together to another location, compared with another version of the file, etc.

As Kilian Foth mentioned:

Using one file for each value is essentially abusing the file system as a data base. Don't do that. Both files systems and databases are good at what they do, and not so good at doing the other's job.

I would summarize it by stating that ease of use, ease of implementation and ease of maintenance are the main advantages of grouping related config settings in a single file compared to having many files, each containing one single setting.

(*) some programs have multiple conf files, but each one contains a set of related settings, not just one setting.


问:
High-Load Java Server for Multiplayer
I am making a multiplayer game. Now I am trying to choose the technology to connect the android devices to the server. The clients run on Android, and the game is MMORPG. I would like to write the server in java. Right now I have only 3 ideas for it:

1) creating multithreading environment with plain java and sockets. In this way it will be easier to perform full-duplex connection between the game client and the server. But I have the following concerns:

1.1) The game is MMORPG with a large number of objects, and I am not sure how such solutions are scaled if there are for example 5000 people playing at the same time. How many threads will I be able to run on java Machine? How can I approximately calculate that? In case 1 thread is reading for each socket and 1 thread is writing to the socket (so 2 threads for 1 player).

1.2) When the number of players grows, how will I be able to scale my self-written jar-archive to distribute over several servers? Maybe there is some special trick to do that?

1.3) A lot of programming overhead - sockets API is quite low level.

2) Creating a Servlet-interface for serving HTTP requests.

2.1) Easy to control sessions (and authorization) as long as each player has his/her own session.

2.2) can connect to java EE EJB or whatever - a lot of complications with system-level programming are taken away. So I can concentrate on writing business logic.

2.3) Can serve all types of clients with HTTP - mobile devices + browsers.

2.4) High-speed - even 1 servlet container can serve a few thousand requests per second so it will be really fast.

2.4) But this approach cant provide a full-duplex communication. I will have to send requests every 1 second to check for updates. 1 second delay does not make a lot of difference for the game as it is turn-based, but still it generates a lot of traffic. Is it feasible when there are many players playing? I heard about some COMET technology, but it seems like if the server has to push many messages in row, I will still have to send requests every time + this technology is not well established yet.

3) Creating sockets and connecting them through JMS to the java EE server.

3.1) Cool because allows for full duplex communication between clients and server + provides all cool features of java EE. Later can be extended to browser through servlet interface.

3.2) It seems like some kind of overengineering. Is it really how people would do that? I mean is it even the correct way? Would any sane developer do it like that?

I would like you to help me out with the choice please. I dont have much experience with doing some work like that. And would like to stick to the best practices.

答:
1.1) you can't think in term of one Thread by user. Depending of machine configuration but you could load thousands of threads but it will not scale and lose a lot of time in Thread context switch. Better think NIO  Netty like framework with few incoming and outcoming Thread pool executor that perform incoming messages under milli second execution.

1.2) You can simply scale by putting in front of you game server a loadbalancer component that can forward incoming player to right server according their load

1.3) NIO can handle thousands to to millions connection on a single box. Don't worry with this.

2.1) Manage your player sessions and 2.2) be away of EJB architecture. It will eat all your box power instead of allocating power to your game which is your goal.

2.3) HTTP can serve all clients but if you run realtime game i encourage to use binary socket and  keep HTTP only for loadbalancing , login , stats  and fallback when can't establish a socket connection.

2.4) Socket based server can handle hundred thousands incoming message per second. This is the property of low latency system

While it's very interesting to dive in building such system. What is your goal? Learn to build such system or succeed your game?

Many java multiplayer game server technology framework already exist. SmartFox Server, ElectroTank...

We have our own java high load  Nuggeta multiplayer crossplatform java game server that addresses all points discussed above and much more. If you wanna try it it's free.

If your goal is to write a game server it's awesome venture that can takes long time but very exciting.
If your goal is to succeed your game. Pick up among Java game server SDK already existing.

Title: High-Load Java Server for Multiplayer


问:
specification regarding a text file
I have a specification I need to follow (for a little project) and I want to ask if they my way of thinking on how to tackle this spec is correct. It's regarding C#.

Specification:

consume a TEXT file (.txt) from a local folder

Provide the ability to:

strip all vowels

remove all non-alpha characters

replace a specific string (using a regular expression) with xxxxxx

Processing requirements:

import the entire file into memory

parse the contents and remove / strip / replace

Output requirements

write out a single TEXT file as OriginalName + Parsed.txt

The text file should contain

Original file (unprocessed), at the end of this section add a summary with count of ALL words and characters.

divider --------------- to separate the unprocessed from the processed

the processed data, at end of section add summary with count of ALL words and characters.

OK here is my way of tackling it:

import a blank text file which will be saved as OriginalName + _Parsed.txt and include the same line in the text file with the summary...
then the divider ------...
then the processed line where the vowels, non alpha characters are removed, and specific string is replaced with xxxxx. Also includes it summary
Does that seem like the right way going about it? I want to ask what is a regular expression and what should the final line look like so I can match it?

Also one final thing, it says ensure the compiled version of the application can be tested on windows 8.1.64bit that does not have visual studio installed. I'm doing it on visual studio but should I perform the application on C# console application so they can see it without needing Visual Studio? It does say debug with command line and no GUI involved.

答:
Seeing as you need(ed) it for "a job placement", I've provided a VB.NET LinqPad "program" that does not address some of the spec, and yet it also highlights some issues with the spec:

Sub Main
    Dim Filename = "T:\Temp\SomeTextFile.txt"
    Dim content = ReadFile(Filename)
    Using output=CreateFile(ParsedName(Filename))
        WriteContentWithSummary(output,content)
        output.WriteLine("---------------")
        WriteContentWithSummary(output,Parse(content))
        output.Close
    ENd Using
End Sub

' Define other methods and classes here
Function ReadFile(ByVal Filename as String) As IEnumerable(Of String)
  Return File.ReadAllLines(Filename)
End Function

Function CreateFile(ByVal Filename as String) As TextWriter
  Return File.CreateText(Filename)
End Function

Function ParsedName(ByVal Filename as String) As String
  Return Path.Combine(Path.GetDirectoryName(FileName), _
    Path.GetFileNameWithoutExtension(Filename) & "_Parsed" _
      & Path.GetExtension(Filename))
End Function

Sub WriteContentWithSummary(ByVal Output as TextWriter, _
                            ByVal Content As IEnumerable(Of String))
  Dim words = 0
  Dim chars = 0
  For each line in Content
    words+=Regex.Matches(line,"\w+").Count
    chars+=line.Length
    Output.WriteLine(line)
  Next
  Output.WriteLine()
  Output.WriteLine("Words: {0} Chars: {1}", words, chars)
  Output.WriteLine()
End Sub

Function Parse(ByVal Content As IEnumerable(Of String)) As IEnumerable(Of String)
  Return From l In Content _
         Let noVowels = StripVowels(l), _
             onlyAlpha=StripNonAlpha(noVowels) _
         Select Regex.Replace(onlyAlpha,"BDWRD","xxxxxx")
End Function

Function StripVowels(Byval Line As String) As String
  Return Regex.Replace(Line,"[AEIOUaeiou]+", "")
End Function

Function StripNonAlpha(Byval Line As String) As String
  Return Regex.Replace(Line,"[^A-Za-z]+", "")
End Function
```

The main issue it highlights is that if you don't read the spec as requiring parameters to choose which of point 2's abilities are applied, then the number of words for the parsed text should be 0 or 1 because really the newlines should go too.

Title: specification regarding a text file

Body:
Seeing as you need(ed) it for "a job placement", I've provided a VB.NET LinqPad "program" that does not address some of the spec, and yet it also highlights some issues with the spec:

Sub Main
    Dim Filename = "T:\Temp\SomeTextFile.txt"
    Dim content = ReadFile(Filename)
    Using output=CreateFile(ParsedName(Filename))
        WriteContentWithSummary(output,content)
        output.WriteLine("---------------")
        WriteContentWithSummary(output,Parse(content))
        output.Close
    ENd Using
End Sub

' Define other methods and classes here
Function ReadFile(ByVal Filename as String) As IEnumerable(Of String)
  Return File.ReadAllLines(Filename)
End Function

Function CreateFile(ByVal Filename as String) As TextWriter
  Return File.CreateText(Filename)
End Function

Function ParsedName(ByVal Filename as String) As String
  Return Path.Combine(Path.GetDirectoryName(FileName), _
    Path.GetFileNameWithoutExtension(Filename) & "_Parsed" _
      & Path.GetExtension(Filename))
End Function

Sub WriteContentWithSummary(ByVal Output as TextWriter, _
                            ByVal Content As IEnumerable(Of String))
  Dim words = 0
  Dim chars = 0
  For each line in Content
    words+=Regex.Matches(line,"\w+").Count
    chars+=line.Length
    Output.WriteLine(line)
  Next
  Output.WriteLine()
  Output.WriteLine("Words: {0} Chars: {1}", words, chars)
  Output.WriteLine()
End Sub

Function Parse(ByVal Content As IEnumerable(Of String)) As IEnumerable(Of String)
  Return From l In Content _
         Let noVowels = StripVowels(l), _
             onlyAlpha=StripNonAlpha(noVowels) _
         Select Regex.Replace(onlyAlpha,"BDWRD","xxxxxx")
End Function

Function StripVowels(Byval Line As String) As String
  Return Regex.Replace(Line,"[AEIOUaeiou]+", "")
End Function

Function StripNonAlpha(Byval Line As String) As String
  Return Regex.Replace(Line,"[^A-Za-z]+", "")
End Function

The main issue it highlights is that if you don't read the spec as requiring parameters to choose which of point 2's abilities are applied, then the number of words for the parsed text should be 0 or 1 because really the newlines should go too.


问:
Best resources to really understand run-time complexity
I'm familiar with the basics of run-time analysis such as what makes certain types of code O(n) and O(n^2).  But I'm having real trouble learning, understanding, and really remembering how to analyze pieces of code that run in other complexities such as O(n log n) or O(2^n).  I'm looking for resources that explain in simple terms how these other complexities work and some practice problems to really force my understanding.</p>

答:
What you can try is to find the analytical expression that is equal to the cost of the algorithm you are working with.

In many cases, this expression might be a sum (usually for nested loops). However, for a recursive algorithm, you might express it's cost with a recursive formula that you will have to solve. For example, the cost of a binary search may be expressed with the formula T(n) = floor(T(n/2)) + 1 (worst case). By solving the formula we find that the answer is Θ(log(n)).

For sorting algorithms, we will usually have Θ(n^2) or Θ(n log(n)) average case (quicksort is Θ(n log(n)) average case but Θ(n^2) worst case!!). Sometimes the cost found by solving a recursive formula might even be exponential (see Tower of Hanoi problem), and that is something to worry about.

Finally, by using the Master Theorem when its possible, you can estimate the runtime complexity without explicitly solving the recursion, which is very useful.


答:
Analyzing complex algorithms requires lot mathematical background. For a refresher on analysis of standard algorithms you can refer to books.

If you need a starting point for analysis of algorithms i would suggest to read some books on algorithms. The best book i can refer for analyzing algorithms is Introduction to Algorithms.

If you would like to attend lectures than reading there are plenty of videos on this subject. Such as MIT Lectures.

Title: Best resources to really understand run-time complexity

Body: I'm familiar with the basics of run-time analysis such as what makes certain types of code O(n) and O(n^2).  But I'm having real trouble learning, understanding, and really remembering how to analyze pieces of code that run in other complexities such as O(n log n) or O(2^n).  I'm looking for resources that explain in simple terms how these other complexities work and some practice problems to really force my understanding.</p>


答:
So what i understand is you for P1 you want to change L3 interface but you want the other P2 and P3 which depend on L3 interface to change right away. This is a typical case of backward compatibility. There is a nice article on this Preserving Backward Compatibility

There are several ways you can solve this:

You have to create new interfaces each time which can extend the old interfaces.

OR

If you want to retire old interface after some time you can have several version of interfaces and once all dependent projects move you remove the older interfaces.


问:
An approach to multilingual db design
My boss is planning on a new db and wants to support multilingual data in this manner:

LocalizedDescs (Guid / LanguageGuid being the primary key)

Cluster

Guid

LanguageGuid

Desc

ProductCategories

Cluster

Guid

(...)

Products

Cluster

Guid

CategoryGuid

DetailedDescGuid

(...)

The way it works is that every table is having a Guid field, used as the primary key. The LocalizedDesc table's Guid field, in turn, corresponds to any guid used in tables throughout the db, making it a parent table to every table in the system.

In rare cases where a table record needs another localized resource, an additional field is used in the table that will also point to a LocalizedDesc record. As an example, the Products table has a DetailedDescGuid that is meant to contain a throughout, longer description of a product. This way we have both a summary description and a detailed description, both of which can be localized to different languages.

Originally, we were supposed to have a LocalizedDescGuid field in each table needing a description. But my boss claims the db indexes will be smaller if we do this the other way.

Design-wise, what is this solution's worth? Was it better when it used an additional field in each table? Or are we doing this all wrong?

答:
I would suggest the following structure due to my experiences in some other applications.

First of all I would build a language table:

```<code>language_id (PK)
iso_country_code
iso_language_code
codepage
translation_id (FK)
</code>```

The language_id would represent the primary key. Each available language is added to this table.
iso_country_code can contain the ISO country code (GB - Britain, DE - Germany, ...).
iso_language_code can be used to cover different located languages (e.g. en_US, en_GB,...)
codepage is the codepage which will be sent out.
translation_id more on this later on.

The second thing should be a translation table. The translation table should hold back all translations for every translatable term.

```<code>translation_id PK
language_id PK (FK -> language)
term
</code>```

The table consists of an combined primary key over translation_id and language_id which will prevent double insertion.
language_id will refer to the language table.
term itself will just be the translated term (e.g.: Table in german -> Tabelle)

The next thing will happen on each table which holds translatable items. For example a Table which holds your products for example called products.

```<code>product_id PK
product_information
product_price
...
translation_id (FK)
</code>```

Only the translation_id is needed. It will refer to the translation table and retrieve the correct translation. The application can give or user session can be joined into the statement to filter the proper language for the logged in user.

The other positive thing on this solution is that if you have multiple translations in different tables which all means the same but in a different context and all can have the same translation_id, they already can share the same translation_id which will reduce your data weight and will improve the translation.

Hopefully this will give you a good hint and help you to improve your solution.

Title: An approach to multilingual db design

Body:
I would suggest the following structure due to my experiences in some other applications.

First of all I would build a language table:

language_id (PK)
iso_country_code
iso_language_code
codepage
translation_id (FK)

The language_id would represent the primary key. Each available language is added to this table.
iso_country_code can contain the ISO country code (GB - Britain, DE - Germany, ...).
iso_language_code can be used to cover different located languages (e.g. en_US, en_GB,...)
codepage is the codepage which will be sent out.
translation_id more on this later on.

The second thing should be a translation table. The translation table should hold back all translations for every translatable term.

translation_id PK
language_id PK (FK -> language)
term

The table consists of an combined primary key over translation_id and language_id which will prevent double insertion.
language_id will refer to the language table.
term itself will just be the translated term (e.g.: Table in german -> Tabelle)

The next thing will happen on each table which holds translatable items. For example a Table which holds your products for example called products.

product_id PK
product_information
product_price
...
translation_id (FK)

Only the translation_id is needed. It will refer to the translation table and retrieve the correct translation. The application can give or user session can be joined into the statement to filter the proper language for the logged in user.

The other positive thing on this solution is that if you have multiple translations in different tables which all means the same but in a different context and all can have the same translation_id, they already can share the same translation_id which will reduce your data weight and will improve the translation.

Hopefully this will give you a good hint and help you to improve your solution.


问:
Has-A or Is-A or some strategy pattern?
I am developing a web based application which is about tracking Fleet units.

Actually i have already developed the system but in the last six years things changed a bit. Ordinary the software specification was about monitoring vehicles in real time and then doing various reports.

How ever during the years we got so many clients in Europe that some of them wanted custom behaviour like inputing the date when various licenses were bought and the date when they expirse so they get a notification for each vehicle when it's time to buy new licence, vignette, insurance and so on..

All seemed to be very good until the time some clients decided that they will buy only 100 GPS devices but they still want to have the rest of 27 (for example) vehicles entered into the system so they get notifications about the vignette, insurance and licence expiration dates. So I had to add new variable like

```<code>boolean hasGps;
</code>```

Things got even worse. Some clients wanted to attach GPS devices to the trailers of the vehicles so they can monitor them to. So the only way to make this possible is to register the trailers as Vehicles and use the same class where i had to add a new field variable like:

```<code>boolean isTrailer;
</code>```

Well... again things got really ugly when a company liked the flow meter system that we attach to the vehicles and keep track of the spent fuel so they wanted to have a GPS device and a flow meter device integrated in their GAS station. Again i had to add a new variable like:

```<code>boolean isGasTank;
</code>```

These days the boss decided that the company will start selling personal tracking devices for security guards and dogs.

So... I decided to re-write the business logic and have the code more clean. However in a real world scenario it seems really difficult to make a good OOP design.

Lets say we have the following fleet units types where a gps device can be attached:

Vehicle, Trailer, GasStationTank, Ship, Person, Animal

All of this units have no behaviour. They only has a state and definition fields.

The only exception where a gps device may not be attached is the Vehicle object because as i mentioned we enter some ghost vehicles where the only tracking is about the expiration dates of various licences, vignette and insurance.

The Vehicle class has most fields where as the other classes have only id and alias fields. Some of the vehicle's fields are:

maxSpeed, fuelPer100, revolutions, flowMeter, fuelNorms. tanks, digitalEvents, analogEvents, parkingDefinition, workingDefinition,

Here is what I have made so far:

```<code>public enum FleetUnitType {

    VEHICLE, TRAILER, NONE_GPS_UNIT, GAS_STATTION_TANK, MOVING_NON_VEHICLE_UNIT

}
</code>```

Abstract class

```<code>public abstract class FleetUnit {

    private final String id;

    private String alias;

    private String group;

    private Optional<GpsDevice> gpsDevice;

    private long dateTimeAddedToSystem;

    private FleetUnit linkedFleetUnit;

    public FleetUnit(String id, String alias, String group) {

        if(id == null) throw new NullPointerException();
        else
        {
            this.id = id;
        }

        this.alias = (alias == null ? id : alias);
        this.group = group;

    }

    public abstract FleetUnitType getType();

}
</code>```

Vehicle class that implements FleetUnit class

```<code>public class Vehicle extends FleetUnit {

    public static final double VBAT_CONST = 0.175;

    private int maxSpeed;

    private double urbanFuel100;
    private double suburbanFuel100;
    private double fuelPerHour;

    double maxAccumulatorValueForZeroRevolution;

    private Optional<Revolutions> revolutions;

    private Optional<FlowMeter> flowMeter;

    private Optional<FuelNorm> fuelNorm;

    private final Map<Integer, FuelTank> fuelTanks;

    private final Map<Integer, DigitalEvent> digitalEvents;

    private ParkingDefinition parkingStartDefinition;

    private WorkingDefinition workingStartDefinition;

    public Vehicle(String id, String alias, String group, VehicleMetaData vMetaData) {
        super(id, alias, group);

        this.fuelTanks = new HashMap<>();
        this.digitalEvents = new HashMap<>();

        parkingStartDefinition = ParkingDefinition.ENGINE_OFF;
        workingStartDefinition = WorkingDefinition.ENGINE_ON;
    }

    @Override
    public FleetUnitType getType() {

        if(super.getGpsDevice().isPresent()) return FleetUnitType.VEHICLE;

        return FleetUnitType.NONE_GPS_DEVICE;
    }

    public static enum EngineState
    {
        MOVING, PARKED, STOPPED, WORKING, CONTACT, UNKNOWN
    }

    public static enum ParkingDefinition
    {
        ENGINE_OFF, TACHOGRAPH
    }

    public static enum WorkingDefinition
    {
        ENGINE_ON, MIN_DISTANCE_TRAVELED
    }

    public static enum MotoHoursCalculation
    {
        ACCUMULATOR, KANSHINA
    }

}
</code>```

As you can see these objects has no behaviour but simply a state which is useful for various reports like how much distance is traveled today or what is the spent fuel and so on...

So finally the question is, should I keep this design and then make the rest of the concrete classes to implement FleetUnit class or I should do something completely different?

答:
Personally, I would design a property bag of sorts on my base class implementation. It looks like you are using Java so pardon my C#, but I think the idea can still be conveyed.

```<code>public abstract class FleetUnit
{
    public IDictionary<string, object> Properties { get; set; }

    public FleetUnit()
    {
        Properties = new Dictionary<string, object>();
    }
}

public class Guard : FleetUnit
{
    protected GpsDevice Gps { get; private set; }

    public Guard(GpsDevice gps)
        : base()
    {
        Gps = gps;
        Properties.Add("Gps", gps);
    }
}
</code>```

Accessing the properties from the base class becomes a TryGetValue call to the dictionary now.

```<code>public static GpsDevice GetGps(FleetUnit unit)
{
    GpsDevice gps = null;

    unit.Properties.TryGetValue("Gps", out gps);
    return gps; //If no property called Gps exists it returns null.
}
</code>```

This allows you to deal with components of a FleetUnit without needing to know about the implementation of every type. The down side of course is you need to deal with units as a composition of different properties (Gps, Identity, so on)

You could alternatively use interfaces to describe the minimum of features or properties a unit requires to match a method signature which is the more pure OOP impementation, but that would require lots of additional methods to handle each interface and may end up with more complex branching (if-else, switch-case).

Title: Has-A or Is-A or some strategy pattern?

Body:
Personally, I would design a property bag of sorts on my base class implementation. It looks like you are using Java so pardon my C#, but I think the idea can still be conveyed.

public abstract class FleetUnit
{
    public IDictionary<string, object> Properties { get; set; }

    public FleetUnit()
    {
        Properties = new Dictionary<string, object>();
    }
}

public class Guard : FleetUnit
{
    protected GpsDevice Gps { get; private set; }

    public Guard(GpsDevice gps)
        : base()
    {
        Gps = gps;
        Properties.Add("Gps", gps);
    }
}

Accessing the properties from the base class becomes a TryGetValue call to the dictionary now.

public static GpsDevice GetGps(FleetUnit unit)
{
    GpsDevice gps = null;

    unit.Properties.TryGetValue("Gps", out gps);
    return gps; //If no property called Gps exists it returns null.
}

This allows you to deal with components of a FleetUnit without needing to know about the implementation of every type. The down side of course is you need to deal with units as a composition of different properties (Gps, Identity, so on)

You could alternatively use interfaces to describe the minimum of features or properties a unit requires to match a method signature which is the more pure OOP impementation, but that would require lots of additional methods to handle each interface and may end up with more complex branching (if-else, switch-case).


问:
How to choose NOT to use a framework (Caliburn.Micro, etc.) in a given MVVM application?
I have once started a MVVM/WPF project, which was eventually built and deployed, and for that I studied a lot of the Caliburn.Micro MVVM Framework. The fact is: I ended up not using Caliburn.Micro for that, and ended up implementing some MVVM concepts myself (specifically, just the ViewModelBase and RoutedCommand classes).

Now I was assigned to a somewhat larger project along the same lines: a "Single-User Rich Client Offline Desktop Application", so to say, and I decided to use Caliburn.Micro. And that's where my "problem" begins.

I have read in this famous blog post, whose title says that "If you're using MVVM then you need a framework", that:

"Trying to do something like MVVM without a framework is a huge amount of work. Tons of duplicate code, reinventing the wheel, and retraining people to think differently.

At least with a framework you avoid the duplicate code and hopefully don’t have to reinvent the wheel – allowing you to focus on retraining people. The retraining part is generally unavoidable, but a framework provides plumbing code and structure, making the process easier."

I would agree upon first reading but my actual experience with Caliburn.Micro (CM) in my actual application is being of cluelessness and disorientation. That is, the framework didn't make the process easier at all, quite the opposite. Reading the ever-repeating examples provided by Rob Eisenberg in the rather (too) informal documentation, and trying to infer usage patterns from the convoluted provided samples, and their utterly indirect class and interface relationships, where things seem to be designed to work based on side-effects, seems humanly impossible unless you are a seasoned genius (sorry for the rant, but I guess you know what I mean).

Not to mention that any above-trivial scenario seems to involve IoC containers, which is something I have never worked with, and which seem to solve a problem I might not even have. I don't feel like spending more project hours learning those things instead of thinking about my problem and application domains. I just wanted a banana, but CM gave me a gorilla (IoC) holding a basket of bananas.

Now that I am considering to move back to my homespun MVVM framework - composed only of the handful of MVVM-specific classes I actually want to implement - I would like at least to give CM a chance, in case I am losing something here, or just plainly doing things "the wrong way" out of sheer inexperience and ignorance. And so the question is:

There are widespread consensus that "frameworks make things easier and more natural", but if I happen to be experiencing quite the opposite, does this mean that I shouldn't use the framework, or that I am trying to learn it the wrong way? Is there a clue that I shouldn't even be using a framework in the first place? Or is there some "right" way to figure out how to use CM for simple MVVM development?

答:
It is important to realize what MVVM is. It is not some shared bit of functionality that you do not have to reimplement (parsing a JPEG file or connecting to a given SQL database server), it is a pattern--a pattern for how one may choose to implement a rich GUI. So, if your implementation of the pattern is simple and straightforward, I do not think you need feel any shame in using it rather than a framework.

Indeed, I believe the whole patterns-as-frameworks idea has gone much too far. For anything to be a pattern it has to be the general shape of a class of solutions. Because this is so, it is to be expected that patterns will need to be tailored to the systems that use them and you cannot do that if you try to use a one-size-fits-all pattern. It would be far more constructive to leave pattern implementation to the application designer and provide libraries that encapsulate functionality, rather than architecture.


问:
Using auto-increment clustered key and guid primary key together
My boss is the db administrator in a new software project and he came up with that design where every table will have both a auto-increment clustered key and a guid primary key (or possibly composite guid keys on some rare cases). Every relations between tables will still use pk as references, making the clustered field never used in views, procedures, functions or any code at all.

I'm no db guru, but I wonder if in this scenario it's even worth having a clustered index at all? I mean, won't records systematically be added to the end of tables? If so then why would I need this field?

答:
Well as already stated in the comments of the other question, this is nonsense if you won't query using the id at all. If you use just the GUIDs then leave out the clustered index and just setup the no clustered index on the GUIDs.

But never use the GUIDs as clustered index unless you want to have a stress test on your I/O subsystem. ;-)


答:
If I am getting your problem right:

your have 4 inter-related modules, P1 and L1 to L3

you need to make a change to P1 which ultimately will affect L1 to L3

it counts as a process failure if you have to change all 4 together

it counts as a process failure if you have to change them all 1 by 1.

it counts as a process failure if you have to identify in advance the chunks in which changes have to be made.

So the goal is you can do P1 and L1 in one go, and then a month later do L2 and L3 in another.

In the Java world, this is trivial, and perhaps the default way to work:

everything goes in one repository with no relevant use of branching

modules are compiled + linked together by maven based on version numbers, not the fact that the are all in the same directory tree.

So you can have the code on your local disk for L3 that wouldn't compile if it was compiling against the copy of the P1 in the other directory on your disk; luckily it isn't doing so. Java can straightforwardly do this because compiling/linking tales place against compiled jar files, not source code.

I'm not aware of a pre-existing widely-used solution to this problem for the C/C++ world, and I'd imagine you hardly want to switch languages. But something could easily be hacked together with make files that did the equivalent thing:

installed libraries + headers to known directories with embedded version numbers

changed compiler paths per module to the directory for the appropriate version numbers

You could even use the C/C++ support in maven, although most C developers would look at you strangely if you did...


问:
Source control branch design for deployed environments
I currently work with a young team of developers using ASP.NET, TeamCity and Octopus Deploy. One of our developers thinks that our system is flawed and introduces the inability to test production hotfixes. What is the best solution to this problem?

We have three environments: development, staging and production. Basically, our workflow only goes forward.

Git push to master -> TeamCity Build -> Octopus Deploy (Dev) -> Promote to Staging -> Promote to Prod

His solution is to have three branches: master (development), staging (staging) and prod (production). We do all active development in our master branch, do any QA in staging and merge from staging to prod when we need to perform a release. When a bug occurs in production, we make the change in staging, and then remerge into production, leaving our development branch alone. We eventually merge all development changes into the production branch once we are ready to release new features.

I don't think this is necessarily right however. My solution is to have the latest production version in the master branch. All development occurs in feature branches. When we've tested a feature branch, we merge back to production. Simple.

So what is the best solution to this problem? Also, some follow-up questions:

Should we improve our QA process? Should we be doing QA on feature branches or on full releases?

How should we set up our continuous integration? Should we have servers deployed for every version?

I'd love to hear some examples or suggestions you guys may have regarding this scenario. Thanks!

答:
This is the solution I've come up with.

All projects which need to be kept in different deployed server environments will have two branches: master and development. The master branch will be the branch with the latest production version. The development branch will contain all active development.

Our CI will be hooked up to both the development and master branch. When the development branch is updated, a build will be created and then deployed to the development server. QA will be performed on the development server. Once the QA is done, the development branch will be merged to the master branch.

When the master branch is updated, a build will be created and then deployed to the staging server. From the staging server someone will need to promote the build to production. This extra step is done to ensure that nothing goes in production that shouldn't be there.

When hot fixes need to happen, a branch of master will be created, developed on, and once that hotfix has been tested locally it will be merged back into the master branch. Here someone can test the hotfix in the staging environment and from there promote it to production.

Hope this helps anyone.


问:
Is blocking an entire web-client due to compatibility a reasonable request?
A little bit of background, we've made an electronic POS system for registered vendors of items of a well known brand. The vendors are required to login to use the system.

Recently, IE has been giving us lots of painful maintenance problems than before. Our boss is getting worried about running into further maintenance problems, so he has asked me to find out a way to automatically install & launch chrome if they try to login with any other browsers (For the record, nearly all of the issues are related to some feature working fine on FF/Chrome/Opera/Safari but doesn't on IE).

Let us put aside the ridiculousness of running an external .exe from Javascript, which is practically impossible (And rightfully, I told him so. But he insisted it was possible, so whatever).

So my questions are:

Is this request technically viable? Is there a guaranteed way to block requests from all browsers except for allowed ones?

Is this request reasonable? IMO, From the standpoint of users, limiting accessibility does more harm than good, but maintenance issue is definitely a valid business concern.

Has there ever been a case like this where other websites explicitly blocked certain browsers?

Edit: Thanks for the answers. We're supporting IE 7+ at the moment and indeed, 7/8 were the ones that caused most of the grief. Just dropping those two will make maintenance significantly easier but my boss thinks the problem has to do with IE itself, not necessarily the versions. I'm going to try to see if I can convince him, but I have a strong feeling he's going to stick by what he thinks.

答:
If I, as an end user, use a widely used browser without employing any clever tricks, then you can detect which browser I am using, and your server code can easily block my browser (display a website saying "please use a different browser").

If I detect that your website doesn't support my browser, and I want to use your website and not change my browser, then it is likely that I as an end user, or someone more clever than me, can set up my browser so that it gets past your code. If let's say IE version 7 pretending to be Safari for iOS doesn't work, I'd say I have only myself to blame; other users might be less reasonable. Trying to block out people using unsupported browsers while pretending to be different browsers is pointless IMO.

Later versions of Internet Explorer have much better compatibility with other browsers, and are widely used. If your boss decides to exclude all versions of Internet Explorer, I could imagine that he will get some serious complaints from customers. That's his or her problem (unless it's so bad that your salary cannot be paid anymore).


问:
Packaging structure of Java collections (java.util) - why does Iterable sit in java.lang?
As per the below diagram, except for interface Iterable, all the remaining constructs (interface / class / abstract class) sit in same package java.util

Why does Iterable sit in java.langpackage?

Note: The intention is to understand the packaging aspect of java programming.

答:
Because a lot of things implement the interface Iterable or extend it as a sub interface.

The implementing classes are:

java.util

AbstractCollection

AbstractList

AbstractQueue

AbstractSequentialList

AbstractSet

...

concurrent

ArrayBlockingQueue

ConcurrentLinkedDeque

...

java.beancontext

BeanContextServicesSupport

BeanContextSupport

...

java.sql

BatchUpdateException

DataTruncation

...

javax.management

AttributeList

javax.print.attribute.standard

JobStateReasons

...

...

This is a huge list. And it touches on all sorts of packages out there.

Furthermore, you want to minimize circular package dependencies.  If a class in package A depends on a class in package B which depends on a class in package A, you've got a circular dependency.  They're not always bad that they exist - but they lead to other circular dependencies and that can be a bad thing.  Its not bad by itself, but it is a design smell that indicates that the coupling between two classes or packages is too tight. It is the start of technical debt accumulating.

The solution to this is to say "yes, the Iterable interface is something that is depended on in a wide variety of classes and packages throughout the entirety of the java and javax structure.  It should be in the most base of the language libraries - java.lang."

And that is where you will find it.

Related reading:

Java Dependency Analysis and Modularization

Avoid cyclic dependencies between packages