问:
When to create a custom exception in C#
I'm writing a class to interface with a simple hardware device over a COM port.  The device can configured to use various modes, so my class has a SetOperatingMode function, that takes in an enum of type UsbDeviceMode.  It looks something like this:

```<code>class UsbDevice
{
    public void SetOperatingMode(UsbDeviceMode mode)
    {
     byte[] buffer = new byte[4];
     buffer[0] = 0x5A;
     buffer[1] = 0x02;
     buffer[2] = (byte)mode;
     buffer[3] = 0x00; //IO_TYPE is always 0 in this case.

     _port.Write(buffer, 0, 4);
     int read = _port.Read(buffer, 0, 2);
     bool successfulSet = (read == 2 && buffer[0] == 0xFF && buffer[1] == 0x00);
    }
}

enum UsbDeviceMode
{
  IO_MODE = 0x00,
  IO_CHANGE = 0x10,
  I2C_S_20KHZ = 0x20,
  I2C_S_50KHZ = 0x30,
  I2C_S_100KHZ = 0x40,
  I2C_S_400KHZ = 0x50,
  I2C_H_100KHZ = 0x60,
  I2C_H_400KHZ = 0x70,
  I2C_H_1000KHZ = 0x80,
  SPI_MODE = 0x90,
  SERIAL = 0x01
};
</code>```

There is the distinct possibility that this operation might fail due to any number of reasons:  The COM port might no longer exist, the device might have locked up or failed, or for whatever reason, the operation failed.

A failure would be unexpected, but not uncommon.  There's two distinct modes of failures:  The COM port throws an exception (TimeoutException and InvalidOperationException being the expected ones).  Or I could read back a failure indicator the device.

In any case, if SetOperatingMode() fails, then the device or the communication is broken somehow, and this class can't do anything about it.

I have 2 questions:

Should I "pre-throw" the InvalidOperationException if the port is closed?  From the MSDN documentation, SerialPort.Write and SerialPort read will throw if the port is closed.  I can check that at the very top of the function, or I can just let _port.Write() throw it.

Should there be an entirely new exception type thrown when successfulSet is false? If successfulSet is false, there's nothing that this class can do to.  Should there be some sort of SetOperatingModeFailedException exception to distinguish between the COM port failing or the device failing? It seems rather time consuming to create an entire exception class just for this one spot.

答:
Use a custom exception when you want users to be able to programmatically distinguish between certain error conditions.  If that situation does not exist, you can throw a more "general" exception, and avoid creating the custom exception class.

In the specific case of your SetOperatingMode() example, unless you need to call out specific ways that this method call might fail, you're better off using a more general exception.  In other words, if it's your intention to throw a SetOperatingModeFailedException exception as a possible result of calling SetOperatingMode(), but not to programmatically distinguish what kind of operating mode failure occurred, then you can dispense with creating a custom exception (since it's the only one that might be thrown), and simply throw an InvalidOperationException, which is probably the closest existing exception.

If you still want to create a custom exception, create one that is reusable across different methods, like OperationFailedException.

Title: When to create a custom exception in C#


答:
Creating a class is easy.  It's not a time consuming process at all.  Debugging code which hides the problems is hard.  And time consuming.

When deciding to create an exception or not the question you should be asking yourself is "is this behaviour normal, expected behaviour, or is this behaviour exceptional".

In this case, the expected behaviour is that the operating mode is always set.  Therefore, I would suggest that exceptions need to be thrown.  I would allow any exceptions from the write operation bubble up.  I would also create a SetOperatingModeFailedException if the last line reveals an error has occurred.

In this case your method really only has the responsibility for trying to set the operating mode.  It doesn't have the responsibility to manage the connection.  That's someone else's responsibility and if it hasn't been done properly, an exception should be thrown.

ContentLicense: CC BY-SA 3.0

Title: When to create a custom exception in C#

Body:
I'm writing a class to interface with a simple hardware device over a COM port.  The device can configured to use various modes, so my class has a SetOperatingMode function, that takes in an enum of type UsbDeviceMode.  It looks something like this:

```<code>class UsbDevice
{
    public void SetOperatingMode(UsbDeviceMode mode)
    {
     byte[] buffer = new byte[4];
     buffer[0] = 0x5A;
     buffer[1] = 0x02;
     buffer[2] = (byte)mode;
     buffer[3] = 0x00; //IO_TYPE is always 0 in this case.

     _port.Write(buffer, 0, 4);
     int read = _port.Read(buffer, 0, 2);
     bool successfulSet = (read == 2 && buffer[0] == 0xFF && buffer[1] == 0x00);
    }
}

enum UsbDeviceMode
{
  IO_MODE = 0x00,
  IO_CHANGE = 0x10,
  I2C_S_20KHZ = 0x20,
  I2C_S_50KHZ = 0x30,
  I2C_S_100KHZ = 0x40,
  I2C_S_400KHZ = 0x50,
  I2C_H_100KHZ = 0x60,
  I2C_H_400KHZ = 0x70,
  I2C_H_1000KHZ = 0x80,
  SPI_MODE = 0x90,
  SERIAL = 0x01
};
</code>```

There is the distinct possibility that this operation might fail due to any number of reasons:  The COM port might no longer exist, the device might have locked up or failed, or for whatever reason, the operation failed.

A failure would be unexpected, but not uncommon.  There's two distinct modes of failures:  The COM port throws an exception (TimeoutException and InvalidOperationException being the expected ones).  Or I could read back a failure indicator the device.

In any case, if SetOperatingMode() fails, then the device or the communication is broken somehow, and this class can't do anything about it.

I have 2 questions:

Should I "pre-throw" the InvalidOperationException if the port is closed?  From the MSDN documentation, SerialPort.Write and SerialPort read will throw if the port is closed.  I can check that at the very top of the function, or I can just let _port.Write() throw it.

Should there be an entirely new exception type thrown when successfulSet is false? If successfulSet is false, there's nothing that this class can do to.  Should there be some sort of SetOperatingModeFailedException exception to distinguish between the COM port failing or the device failing? It seems rather time consuming to create an entire exception class just for this one spot.


问:
Why use a bool over more domain specific abstractions
Booleans are often used to model domain specific dichotomies. The most common example I can think of is the success or failure of an operation. It seems to me that a boolean must be interpreted in the context in which it is used as opposed to something more specific to the domain of the function. What is the advantage to returning a boolean from a function over returning something like a enumeration of named values?

Assume the programming language we are using succinctly deals with both booleans and enumerations so readability is not an issue.

答:
Because the domain answer is just another boolean.  LetterSent, BillPaid, AccountIsPastDue, SubscribedToAutoPay, etc...

When you talk to the domain experts, that is how they think of the situation -- the main difference is that they typically think in terms of yes/no and not true/false, but creating an object for that would be silly -- basically a lot of extra work for a simple ToString method.


问:
Pair Rotation in a team for effective pair programming
We follow pair programming in our company and always face the issue of balanced and effective pair rotation within the developers on stories.

We follow a simple metrics in which every developer's name is mapped with every other developer and we mark the respective intersection whenever two developers are pairing.

This is not working out well, we cannot track how much time a pair has spent pairing and people forget to update the metrics many times. Tracking the pair rotation is helpful because we want the project knowledge to be shared across the team, and not just one pair. So usually what happens is, whoever is pairing keeps pairing till the entire story is completed (given they have better context), and no body else knows about what is being done & if the story or a regression/production bug comes back, the same pair has to pick it up (leaving whatever they are currently doing), which is what creates a bottleneck.

Are there any known metrics that can be used for tracking the pair rotations.

答:
Assign a pair anchor that will be on the task from start to the end. A task estimation should not be longer then 2/3 days.

Switch pair every half a day. Thomas description of breaking flow would be correct if there was no anchor left.

If you want a visual feedback keep a pairing table on your whiteboard and let the anchor update who he paired with.

Beware not everybody is happy to switch that often, some people prefer to see a feature from the start to the end often with the same person. I think this creates knowledge silos and requires for long code review processes.


问:
Best way to centralise a php project (except bitbucket)
The structure is as follows:

A: this is the live/production website

B: this is the staging, which is a copy of live

C: this is the testing environment for designers

2 developer and 2 designers. Only developers are allowed to push changes to A. The designers work only with C, developers take the needed changes from C and push them to B and if everything is ok, then they push the changes to A. Everything is done manually as of now.

What is the best way to centralise the files so that multiple people can work on same files etc. As in, designers can work on the same css file and developers can work on same php files, if possible. The solution can have internet dependency, it is not an issue.

答:
First, lets start out with "there is no on line provider that allows per brach access control lists as part of its base service."  It doesn't exist as such.

What does exist, is the ability to do add commit hooks.  For example, in git you could put a pre-receive hook on the server.  This hook would check to see if the person doing the commit is one of the authorized committers for the branch and reject it if not.  This doesn't imply any sort of centralized server and it appears that github (for example) doesn't do arbitrary pre-receive hooks.  You could do this in house with a git server - just say "that one there is the master of masters" and go from there.

Lets instead look at what you are trying to accomplish.  You want some people to be able to commit to a specific area of code that gets published to production.  You could do this on github by setting access levels on the repo and having the devs be part of the write access team for that repo and the designers be part of the read access team.  The designers would then fork the repo (which then they would have access to) and submit pull requests to the main repo for changes that are moved in.  How staging and production are handled from this is an implementation detail.

On the other hand, if you are willing to shell out some money (you would if you are going for a github organization with private repos...) you may wish to look at Atlasssian Stash (I'm surprised this wasn't considered given you are already using another atlassian product).

Atlasssian stash claims under its "enterprise: security" blurb:

Stash's permissions levels make sure that the right people always have access to the right code. The simple yet powerful user interface makes it easy to manage permissions.

Set high-level global permissions, then fine tune them at the project, repository, or even branch levels with read/write/admin restrictions.

And, well, thats what you are describing you want.  Stash is in essence an enterprise grade in house bitbucket server.  As your enterprise is less than 10 users, the pricing for this is $10. Not $10/month, or $10/user.  $10. Which is fairly hard to beat as a price.

So set up your branches, set who can commit to them, set up the pull request / code review feature and approval conditions or however you want the workflow to work and do it.  For such a small organization I'd really be looking at stash as a viable alternative, especially if you aren't already tied to other incompatible systems (a former employer considered it, but was already integrated with how github issues worked and so that didn't go anywhere).


问:
Black box or white box testing - which do you do first?
On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>

答:
I like to start with black box testing, then use code coverage information or the debugger to figure out what I'm doing and analyze what's happening.

But the real answer is it depends. I'm likely to dive into the code sooner (ore even first) if I'm doing API testing, but much later if my goal is to look at some large end to end scenarios.

ContentLicense: CC BY-SA 2.5


问:
Best practice A.I. - check all possible moves or pick an objective?
I'm looking for some general guidance on how to produce best practice A.I.

The way I understand it, the way A.I. works for games like Go, Chess etc is by considering all possible moves (combinations of moves multiple turns in advance) and deciding which possible move maximises some given score/utility.

However, I very much suspect that this isn't how, lets say, Starcraft works. I am assuming that the A.I. here would not, for each iteration of code, have hundreds of possible directions a given worker/drone can head (and count up the utility derived from being closer to resources, being protected, having increased scouting etc for each of these possible moves).

I am assuming that instead, the game abstracts down the drones options into specific goals, such as: Gather resource X, gather resource Y, scout, fight, flee and determine the expected utility from each of these, and that once the goal has been chosen, the game calculates a simple rule for meeting the goal, which in most cases would simply be move towards the closest resource source, away from the closest enemy etc.

So, questions:

1) Is the above mostly correct? Or are there other ways that best practice A.I. generally works.

2) What is the primary reason for going with an abstraction, instead of considering utility of all possible moves? i.e. computational load, easier to program, tradition etc.

3) How would one go about deciding whether to build a chess style A.I. or a Starcraft style A.I. for a particular purpose? What sort of considerations come to mind?

答:
There is no such thing as "best practice" with AI. There is what works and what does not work for a given purpose. There are techniques that may apply to a given task, which you did a good job of summarizing in your question.

Taking an RTS such as StarCraft 2 for example, different units have different capabilities. Gathers gather resources: they are assigned to pick up resources spent elsewhere. The AI simply needs to figure out "is there another resource nearby if my current one is busy or depleted?" which is a fairly simple task.

Military units may have commands queued up: move here, attack this, stand around and attack anything nearby, etc. The biggest challenge with these types is pathing: how to get somewhere, not what to do.

Finally there is the AI that may control multiple units, which is what comes into play when you play against a computer opponent either in free play or the campaign. These AIs tend to be a combination of preassigned orders (campaign), build orders (free play), and an AI separate from that used for individual units that acts like a player would be issuing commands to multiple units. This is the most interesting of them all, but unfortunately most of these AIs are proprietary and we may not know for sure how they work.

Real-time simulations certainly have time constraints, and an AI algorithm must be powerful enough to act "smart enough" while fast enough not to impact gameplay performance.

To your first point, yes, you summarized things fairly well. To your next two points, the tradeoff is what I described above: does the computer have the time to consider all moves, or at least a large number of moves? Is there an acceptable tradeoff between speed and intelligence? Are there constraints that help with this, such as specific game entities only performing certain actions? Can a player impact this by e.g. giving instructions to units and allowing limited autonomy?


问:
OOP Practice: how to best handle dependent dependencies
I have a problem with the design shown in the picture. My Section class has some TextBlocks (or simply Blocks). The section should be drawn on a page (a Bitmap as device context). It sets the blocks of the page and calls page.DrawBlocks(). The page sets the Graphics object of each block and calls block.Draw()

Graphics could not be set in the constructor of each TextBlock when I introduce them in the Section because the page may not be initialized. However, I know it's better to introduce dependencies in the constructor.

How can I redesign my classes to solve this problem? Should I pass the Graphics to the Draw() function? I prefer not, because some other functions in the class also need Graphics.

答:
Should I pass the Graphics to the Draw() function?

Well, when I saw this design, first thing which came into my mind was "why the heck does the TextBlock have a Graphics attribute at all? Should it not be possible to draw the same block on two different graphics contexts? Should the TextBlock object not have a lifetime which may be longer than the lifetime of the Graphics object?"

So my answer is yes - it does not make much sense to me not to have a Graphics parameter in the Draw function. This will imply to pass the Graphics parameter into the DrawBlocks method of the Page, and some other method in your Section, of course, but that is probably the correct design.

In fact, when your TextBlock has more than a half dozen private methods, all called directly or indirectly from Draw, and all of them use the same Graphics object, it may be more convenient to buffer the Graphics object passed by the Draw method in a member variable, so you do not need to have the same Graphics parameter in all of those methods. So keeping this attribute as a member might make sense (but this cannot be deciced from the small part of the text block class we see in your current model). And if you decide to keep this attribute, make sure you add a comment when this attribute is set and how long it is valid. The code then will look like this

```<code>   void Draw(Graphics g)
   {
      graphics=g;
      // ...
      // call some members depending on "graphics"
      // ...
      graphics=null; // just in case, to avoid accessing an invalid graphics object
   }
</code>```

Alternatively, you could consider to introduce a helper class TextBlockDrawer, which  gets the Graphics object and the TextBlock passed as a constructor parameter, and encapsulates the whole drawing process. That way, you won't need a Graphics member in your TextBlock class any more, only in TextBlockDrawer, and this attribute can be initialized in the constructor of that class. This design also makes a better separation between the data (TextBlock) and the drawing process. The resulting code will look either like this:

```<code>class TextBlock
{
   public void Draw(Graphics g)
   {
      var tbDrawer = new TextBlockDrawer(this,g);
      tbDrawer.Draw();
   }
}
</code>```

or, by omitting the Drawmethod in the TextBlock completely, and reuse the TextBlockDrawer for different text blocks:

```<code>class Page
{
   // ...
   public void DrawBlocks(Graphics g)
   {
      var tbDrawer = new TextBlockDrawer(g);
      foreach(var tb in MyTextBlocks())
          tbDrawer.Draw(tb);
   }
}
</code>```

Body:
Should I pass the Graphics to the Draw() function?

Well, when I saw this design, first thing which came into my mind was "why the heck does the TextBlock have a Graphics attribute at all? Should it not be possible to draw the same block on two different graphics contexts? Should the TextBlock object not have a lifetime which may be longer than the lifetime of the Graphics object?"

So my answer is yes - it does not make much sense to me not to have a Graphics parameter in the Draw function. This will imply to pass the Graphics parameter into the DrawBlocks method of the Page, and some other method in your Section, of course, but that is probably the correct design.

In fact, when your TextBlock has more than a half dozen private methods, all called directly or indirectly from Draw, and all of them use the same Graphics object, it may be more convenient to buffer the Graphics object passed by the Draw method in a member variable, so you do not need to have the same Graphics parameter in all of those methods. So keeping this attribute as a member might make sense (but this cannot be deciced from the small part of the text block class we see in your current model). And if you decide to keep this attribute, make sure you add a comment when this attribute is set and how long it is valid. The code then will look like this

   void Draw(Graphics g)
   {
      graphics=g;
      // ...
      // call some members depending on "graphics"
      // ...
      graphics=null; // just in case, to avoid accessing an invalid graphics object
   }

Alternatively, you could consider to introduce a helper class TextBlockDrawer, which  gets the Graphics object and the TextBlock passed as a constructor parameter, and encapsulates the whole drawing process. That way, you won't need a Graphics member in your TextBlock class any more, only in TextBlockDrawer, and this attribute can be initialized in the constructor of that class. This design also makes a better separation between the data (TextBlock) and the drawing process. The resulting code will look either like this:

class TextBlock
{
   public void Draw(Graphics g)
   {
      var tbDrawer = new TextBlockDrawer(this,g);
      tbDrawer.Draw();
   }
}

or, by omitting the Drawmethod in the TextBlock completely, and reuse the TextBlockDrawer for different text blocks:

class Page
{
   // ...
   public void DrawBlocks(Graphics g)
   {
      var tbDrawer = new TextBlockDrawer(g);
      foreach(var tb in MyTextBlocks())
          tbDrawer.Draw(tb);
   }
}


答:
If the application uses C#, there is also an element not mentioned by Doc Brown which makes Graphics as property a bad choice (it may probably be relevant for Visual Basic and partially relevant for Java as well).

Graphics implements IDisposable. This means that if you pass it to Draw(), the code looks straightforward:

using (var g = new Graphics(...))
{
    foreach (var block in this.Blocks)
    {
        block.Draw(g);
    }
}
```

<p>On the other hand, if you use a property, it becomes very difficult to:</p>

<ul>
<li><p>Determine inside the caller class when should you actually dispose the <code>Graphics</code> object,</p></li>
<li><p>Find inside <code>TextBlock</code> class whether the <code>Graphics</code> object is already disposed.</p></li>
</ul>

<p>You'll end up with something which looks like:</p>

<pre class="lang-cs prettyprint-override"><code>using (var g = new Graphics(...))
{
    foreach (var block in this.Blocks)
    {
        block.Graphics = g;
        block.Draw();
        block.Graphics = null;
    }
}
</code>```

Do you use Code analysis? I would be surprised if you have zero errors with the actual approach.

Title: OOP Practice: how to best handle dependent dependencies

Body:
I have a problem with the design shown in the picture. My Section class has some TextBlocks (or simply Blocks). The section should be drawn on a page (a Bitmap as device context). It sets the blocks of the page and calls page.DrawBlocks(). The page sets the Graphics object of each block and calls block.Draw()

Graphics could not be set in the constructor of each TextBlock when I introduce them in the Section because the page may not be initialized. However, I know it's better to introduce dependencies in the constructor.

How can I redesign my classes to solve this problem? Should I pass the Graphics to the Draw() function? I prefer not, because some other functions in the class also need Graphics.

Body:
If the application uses C#, there is also an element not mentioned by Doc Brown which makes Graphics as property a bad choice (it may probably be relevant for Visual Basic and partially relevant for Java as well).

Graphics implements IDisposable. This means that if you pass it to Draw(), the code looks straightforward:

using (var g = new Graphics(...))
{
    foreach (var block in this.Blocks)
    {
        block.Draw(g);
    }
}

On the other hand, if you use a property, it becomes very difficult to:

Determine inside the caller class when should you actually dispose the Graphics object,

Find inside TextBlock class whether the Graphics object is already disposed.

You'll end up with something which looks like:

using (var g = new Graphics(...))
{
    foreach (var block in this.Blocks)
    {
        block.Graphics = g;
        block.Draw();
        block.Graphics = null;
    }
}

Do you use Code analysis? I would be surprised if you have zero errors with the actual approach.


问:
How to make one test depend on the results of another test?
Let's say there is a utility class that provides some common static methods used everywhere in your code by many other classes.

How would you design your unit tests for the consumers of the utility so that their tests fail if any one of the utility tests do not pass? Can you do it or do you have to check it yourself whether the utility class tests are all green?

For example I have a message-splitter utility that is used (or rather its output) by a message-parser. I'd like to be sure that the message-splitter works correctly before the message-parser gets tested.

I have written tests for both of them but is there a way to link them and make one test depend on the result of some other test?

I couldn't find a suitable tag for this but I'm using Visual Studio's unit test engine.

答:
There is no point to making sure that every defect in your system trips exactly one test.

A test suite has one job: verifying that there are no known defects. If there is a defect, it doesn't matter if one test fails or 10. If you get used to your test suite failing, if you try to gauge how "bad" your program is by counting the failing tests, you're not using regression testing the right way. The test suite should pass all tests before you publish code.

The only valid reason for skipping tests is if they test incomplete functionality and take an inordinate amount of time that you could put to better use while implementing the thing they're supposed to test. (That is only an issue if you don't practice strict test-driven development, but that's a valid choice, after all.)

Otherwise, don't bother trying to make your test suite into an indicator telling you precisely what's wrong. It will never be exact, and it's not supposed to be. It's supposed to protect you from making the same mistake twice, that's all.


问:
What programming technique is this?
I have two Java classes. The first one is called "Index", and the second one, temporarily, I called it "IndexCache":

```<code>public class IndexCache {
    private static Map<String, Index> map = null;

    static {
        map = new HashMap<String, Index>();
    }

    @Override
    public Index getIndexString(key) {
        Index index = map.get(key);

        if (index == null) {
            index = new Index("yadayadayada");
            map.put(key, index);
        }

        return index;

    }

}
</code>```

As you can see, IndexCache keeps a map of the Index objects to avoid to create the same object once and again.

Well, what programming technique is this? What would be its name?

答:
It's called a cache, the technique is called caching.

A cache is something that stores data in order to speed up further requests for that same data. That data may be the result of some expensive computation and thus be cached to avoid repeating that costly computation. It might also be a copy of some data that is already pre-computed elsewhere but is costly to retrieve (e.g. caching filesystem blocks from a slow harddisk in RAM or caching HTTP documents from a remote server on a local proxy cache).

A cache is populated dynamically with different values each time, and may also grow and shrink.

This is different from a lookup table, which is populated statically, always with the same values, often even hardcoded into the source code or pre-computed at compilation time.

Memoization is a special case, it refers specifically to caching the results of function application with the same arguments.

Title: What programming technique is this?


答:
Not an AI expert, but I do know some things about AIs in general, and about chess AIs.

First, let's indeed note that there is no "best practice" for AIs, they can work in many different ways. Some approaches are better suited to some problems, and some problems have many viable approaches.

Now, no, games like chess are definitely not played by considering every possible move up to a certain depth. The problem is that exponential growth is something that's easy to underestimate, but the amount of positions becomes too large to compute. After two full moves in chess (white and black have moved), there are almost 9000 possible positions, and over 9 million after six moves. Considering all the possible moves even up to a fairly small depth is not feasible.

On chess AIs

Therefore the major issue in chess AI is in fact that of which moves not to consider. There are many different approaches again to that problem, one very notable approach being the combination of minimax and alpha-beta pruning. You can read about these on Wikipedia for a simple introduction or other sources for more in-depth considerations. Minimax is essentially an algorithm for considering moves up to a certain depth and then choosing the best move in the current situation, and alpha-beta pruning is an algorithm that removes certain paths from minimax. Then there are further smart improvements like considering moves in a specific order so that some paths may be cut from evaluation sooner. In practice advanced refinements of these techniques are used.

Advances in these heuristics have, in recent years, made chess AIs far more powerful than before. Consider that not so long ago it took a supercomputer to beat a top human. Deep Blue beat Kasparov in 1996, and it was a purpose-built computer. But ten years later, in 2006, Kramnik was playing versus Deep Fritz, and it ran on a powerful Xeon-based computer, but it wasn't a supercomputer or anything special-built, it was a typical high-performance computer like what might be used for a server. And since 2009, the HIARCS chess engine has been able to provide strong results running on mobile devices, almost entirely due to smarter algoritms - the amount of positions considered was very low. By now, only the top tier chess players would stand a chance at beating the best programs available for Android. On a decent desktop computer, even top grandmansters do not stand a chance.

One example of such huge recent advantages is the null-move heuristic. It lets a chess AI consider a null move (that is, not moving anything, which is illegal in chess). The basic idea is that if you could make a null move and still have a strong position, then making a move would likely give an even better position.

Note: end-game tables do get used by chess AIs. For end-game positions with few remaining pieces, they have been solved exhaustively, and so optimal play can be looked up. A current chess AI will always play optimally in a six- or seven-piece endgame position.

On StarCraft

All of this is completely different from how something like StarCraft works. A StarCraft AI is largely about pathfinding (a very challenging problem, and anyone who's played RTS games has probably seen AI "misfires" such as units getting stuck or running around in circles), and about some real-time estimation of the situation. The nature of a RTS game forces the AI to be able to think fast. So the AI would be using various formulas for rough estimation. For example, given its army against an opposing army, it would have some kind of formula that can be quickly used to calculate the expected outcome, and then the AI makes a decision to fight or withdraw based on that. In the meanwhile, the AI aims to keep training workers as long as it's not utilizing resources in the maximum possible way.

Of course, a StarCraft AI can also follow different strategies. It can aim to maximize resources, which would result in something like a fast expansion, or it can aim to minimize time to an attack, which would be a rush. Then there are also other techniques used such as calculation of "danger areas". The AI consders some areas to be in danger, and others to be defended. This guides, for instance, its construction of anti-air turrets.

Chess and StarCraft provide a very good example of how AIs can be very different. A chess AI will sacrifice speed for intelligence - it's normal under tournament conditions to consider a move for minutes. A StarCraft AI will sacrifice intelligence for speed - it has to think quickly enough to provide an enjoyable real-time gameplay experience. A chess AI puts a lot of effort into evaluating positions, a StarCraft AI will do a much more rough estimation of which force is stronger. In chess, the entire position on the board is always known, in StarCraft, there are unknown elements.

StarCraft (both games) has been quite interesting for AI. AIs like Overmind that won the 2010 AIIDE are interesting from a research perspective. You could Google for "Stanford Starcraft AI" to find a few interesting AI projects for StarCraft and the sequel.

Title: Best practice A.I. - check all possible moves or pick an objective?

Body:
I'm looking for some general guidance on how to produce best practice A.I.

The way I understand it, the way A.I. works for games like Go, Chess etc is by considering all possible moves (combinations of moves multiple turns in advance) and deciding which possible move maximises some given score/utility.

However, I very much suspect that this isn't how, lets say, Starcraft works. I am assuming that the A.I. here would not, for each iteration of code, have hundreds of possible directions a given worker/drone can head (and count up the utility derived from being closer to resources, being protected, having increased scouting etc for each of these possible moves).

I am assuming that instead, the game abstracts down the drones options into specific goals, such as: Gather resource X, gather resource Y, scout, fight, flee and determine the expected utility from each of these, and that once the goal has been chosen, the game calculates a simple rule for meeting the goal, which in most cases would simply be move towards the closest resource source, away from the closest enemy etc.

So, questions:

1) Is the above mostly correct? Or are there other ways that best practice A.I. generally works.

2) What is the primary reason for going with an abstraction, instead of considering utility of all possible moves? i.e. computational load, easier to program, tradition etc.

3) How would one go about deciding whether to build a chess style A.I. or a Starcraft style A.I. for a particular purpose? What sort of considerations come to mind?


问:
Is "convention over configuration" not violating basic programming principles?
I was looking at the WPF MVVM framework Caliburn.Micro and read that a lot of standard things are based on naming conventions.

For example, automatic binding of properties in the View to properties in the ViewModel. Although this seems to be convenient (removes some boilerplate code), my first instinct reaction is that it isn't completely obvious to a new programmer that will read this code. In other words, the functionality of the application is not completely explained by its own code, but also by the documentation of the framework.

EDIT:

So this approach is called convention over configuration. Since I could not find any questions concerning this, I altered my question:

My question is:

Is convention over configuration a correct way of simplifying things, or is it violating some programming principles (and if so, which ones)?

答: It might be violating few principles, but at the same time it obeys one of the most fundamental design principles, SRP (Single Responsibility Principle).</p>


答:
It depends on your tooling, but you probably can't (and shouldn't)

Some Unit-testing frameworks (take PHPUnit for example) allow you to 'chain' tests so that a failing test on one level does not execute other tests. However, I doubt that this will fix your problem for this situation.

Not allowing guaranteed test order execution forces tests to be isolated from each other and is generally considered a good thing. Imagine what would happen if tests would not only run themselves but also provide data for other tests to work on...

You can put these utility-methods in a separate solution or test-category. Make sure they visually 'stand out' in your test runner, or that this category runs first and does not run any other tests if the tests in this category fails*. When one of these tests fail the failure will probably cascade across all the tests and you should help make sure that whoever runs the tests knows to start by fixing these failing tests first of all. The same goes for Unit Tests and Integration Tests. If a Unittest fails, it will cascade and cause all sorts of mayhem in the Integration tests. Everybody knows that when Unit AND Integration tests fail, you start by checking out the Unittests...

*With an automated build or test script you could run this category first, check the result and only run the other tests if this first batch of tests pass.

Title: How to make one test depend on the results of another test?

Body:
Let's say there is a utility class that provides some common static methods used everywhere in your code by many other classes.

How would you design your unit tests for the consumers of the utility so that their tests fail if any one of the utility tests do not pass? Can you do it or do you have to check it yourself whether the utility class tests are all green?

For example I have a message-splitter utility that is used (or rather its output) by a message-parser. I'd like to be sure that the message-splitter works correctly before the message-parser gets tested.

I have written tests for both of them but is there a way to link them and make one test depend on the result of some other test?

I couldn't find a suitable tag for this but I'm using Visual Studio's unit test engine.


答:
Your problem is that TextBlocks shouldn't know how to draw themselves in the first place. This is a Single Responsibility Principle violation; now your classes will have to change any time the Graphics interface changes or any time you want to change how they get drawn to the screen, even though their primary concern should be representing parts of pages.

Instead, make Graphics be the one to draw pages and text blocks. This puts all the graphics logic in one place, lets you change it without affecting the rest of your code, and you don't have to pass around stub Graphics objects when you unit test.


问:
Should I backup gradle dependencies to git?
I always like to backup project dependencies myself in case they can't be resolved due to a down website or because certain versions aren't available for download any more.

Should I trust the maven central repository to be up and running when I try to build my project in 2020? Or should I backup dependencies manual?

If I should backup manual, then where does gradle store the downloaded dependencies? Or does gradle come with an build in solution for this?

答:
First, you are not alone with this questions and in our company I tried to answer this questions a dozen times. Here are my answers:

Should I backup gradle dependencies to git?

No, not in the git repository. In my opinion a source repository should be as small as possible, because I don't like to checkout a repository for hours.

Though it might be good to backup anyhow, but how?

I solved this by simply creating a zip of a working sandbox and the downloaded dependencies:

```<code>./gradlew -g ./backuped_USER_HOME build
cd ..
<zip Project>
</code>```

If you want to build your project simply unzip it and use the backuped USER_HOME directory by

```<code>./gradlew -g ./backuped_USER_HOME --offline build
</code>```

where --offline might be superfluous.

CAUTION: If you have any custom targets you should also run this directly or implicitly since otherwise gradle would not download the dependencies it needs for the custom tasks.

Body:
First, you are not alone with this questions and in our company I tried to answer this questions a dozen times. Here are my answers:

Should I backup gradle dependencies to git?

No, not in the git repository. In my opinion a source repository should be as small as possible, because I don't like to checkout a repository for hours.

Though it might be good to backup anyhow, but how?

I solved this by simply creating a zip of a working sandbox and the downloaded dependencies:

./gradlew -g ./backuped_USER_HOME build
cd ..
<zip Project>

If you want to build your project simply unzip it and use the backuped USER_HOME directory by

./gradlew -g ./backuped_USER_HOME --offline build

where --offline might be superfluous.

CAUTION: If you have any custom targets you should also run this directly or implicitly since otherwise gradle would not download the dependencies it needs for the custom tasks.


问:
Algorithm or domain for finding cheapest subgraphs that connect vertex pairs
I am currently working on a project inspired by the Ticket to Ride board game.  This board game is played on an undirected graph where each vertex represents a city and each edge represents a claimable train line connecting two cities.  Players get points by claiming an edge for themselves, scoring points based upon how many cars the route requires to claim.  There are also tickets that give bonus points if the player is able to claim a path that connects the two cities.  Each player has only 45 cars, so this is a resource allocation problem.

I am trying to write a program that helps agents (humans or AIs) plan which routes to take based upon which tickets that agent needs to complete, which routes the agent has already claimed, and which routes are unavailable due to other players having claimed them.  I need an algorithm that finds a set of subgraph(s) such that each ticket has its city in the same subgraph while trying to optimize some criteria (minimum car usage, maximum points per car, etc.).  I do not care whether the algorithm gets all the cities in one subgraph, or whether it strings them all out in a line without branching (which would help toward getting the Longest Route bonus); I want something that enables the agent to complete the tickets quickly so he can start working on new ones.

The problem is that I do not have enough familiarity with graph theory to know the name for this type of problem.  I have tried searches with text that describes what I am trying to do with no luck.  I have also looked in my old textbooks (Introduction to Algorithms and Algorithms in C: Part 5 - Graph Algorithms) to try to find a graph problem domain that seems to relate to my issue; the closest seems to be network flow, but that does not seem to be close enough.

I have tried solving this problem on my own.  I wrote an A* that scored each set of subgraphs based upon the estimated minimum distance to a node, but it did not work (as I would have discovered if I had read the Wikipedia article on A* first).  I wrote an NSGA-II implementation to try to solve the problem stochastically, but it oddly seems to do worse the closer the initial set of owned edges is to connecting the tickets.  In fact, the NSGA-II implementation "freaks out" and finds very strange routes to connect subgraphs when only one route that earlier calls to the algorithm recommended.

Could someone either tell me the name of this domain so I can start doing research, point me to an algorithm, or propose an algorithm that I could try?

答:
I want to thank those who have posted answers regarding combinatorial optimization.  I am going to start studying the field this weekend after I move.  In the meantime, I wanted to present my current best effort in case someone else might find it useful.

I have developed a heuristically-driven algorithm that seems to find at least decent results in what may be an acceptable amount of time once I throw part of the processing into an algorithm.  I estimate the complexity of the algorithm at O(T! M^T V^2 E^2), where T is the number of pairs to solve (the number of tickets to complete), M is the maximum number of paths of equal length found to connect two vertices using a modified Bellman-Ford, V is the number of vertices in the graph (36 for my map), and E is the number of edges in the graph (78 for my map).  For my purposes, M appears to be quite low (probably capped at 6, and frequently lower than that), and I do not expect T to be more than 5 (though 3 is a much more likely ceiling).

The basic assumption behind this algorithm is that the best route will optimally connect one of the pairs of vertices, and the others are more likely to save costs by connecting into this path than to connect directly using their locally optimal paths.  The trick is to find the correct order for connecting the pairs that best reduces the cost.  The following recursive approach is the backbone for the algorithm:

```<code>def planWorker(graph, pairs, ownedEdges, blockedEdges):
    if there are no pairs:
        return 0, empty set
    bestScore, added <- null, empty set
    build a Bellman-Ford table for every vertex in the graph
    // each ownedEdge costs 0
    // each blockedEdge effectively no longer exists in the graph
    for each pair:
        base <- distance to complete pair
        options <- all shortest paths connecting the pair
        // options is a set of sets of edges
        if this is the last ticket:
            bestScore <- base
            for each option:
                path <- option - owned
                added.add(path)
        else:
            for each option:
                subscore, subpaths <- planWorker(graph, pairs - pair, owned + option, blocked)
                total <- base + subscore
                if bestScore == null or total <= bestScore:
                    if bestScore == null or total < bestScore:
                        bestScore <- total
                        added <- empty set
                    for each subpath:
                        added.add(option + subpath)
    return bestScore, added
</code>```

This algorithm's complexity is O(T! M^T |V|^2 |E|).  Called on its own, it finds at least a good threshold against which to compare other paths.  I have not yet found an example where it does not find at least a subset of the optimal paths, but I am not assuming that it does find optimal paths because I do not know that my assumption about optimal path structure is correct.

I have found that this algorithm does not find all paths of the same length for a set of pairs.  However, by adding an additional search testing untried edges, the algorithm does seem to try them all:

```<code>def plan(graph, pairs, owned, blocked):
    bestScore, added <- planWorker(graph, pairs, owned, blocked)
    candidates <- graph.edges - owned - blocked - flatten(added) // the "untried" edges
    for each candidate:
        base = candidate's weight
        score, alternatives <- planWorker(graph, pairs, owned + candidate, blocked)
        total <- base + score
        if total > bestScore:
            continue
        if total < bestScore:
            bestScore = total
            added <- empty set
        for each path in alternatives:
            added <- added + (path + candidate)
    return bestScore, added
</code>```

The loop multiplies the computational complexity by E, giving the final computational complexity of O(T! M^T V^2 E^2).  There's probably additional terms that I am not accounting for that come from the set operations, but my guess is that the sets I am using do not really need more than an additional log E multiple for that.

I have hacked this approach (probably very inefficiently) in Java 8.  Running this implementation for four tickets on the Ticket to Ride map with no routes initially owned or blocked takes less than twelve minutes on my unplugged laptop with an Intel Core i7-4710HQ clocked at 2.5 GHz.  I can likely speed it up by cutting down on dynamic memory allocation and by threading the candidate checks instead of looping over them synchronously.  This algorithm solves the tickets (Los Angeles, Miami), (Los Angeles, New York), (Montreal, Vancouver), and (New York, Seattle) with a cost of 39 cars.  The six routes with that length it finds are shown below.  The initial planWorker() call finds the green route, and the candidate search finds the other five.

Body:
I want to thank those who have posted answers regarding combinatorial optimization.  I am going to start studying the field this weekend after I move.  In the meantime, I wanted to present my current best effort in case someone else might find it useful.

I have developed a heuristically-driven algorithm that seems to find at least decent results in what may be an acceptable amount of time once I throw part of the processing into an algorithm.  I estimate the complexity of the algorithm at O(T! M^T V^2 E^2), where T is the number of pairs to solve (the number of tickets to complete), M is the maximum number of paths of equal length found to connect two vertices using a modified Bellman-Ford, V is the number of vertices in the graph (36 for my map), and E is the number of edges in the graph (78 for my map).  For my purposes, M appears to be quite low (probably capped at 6, and frequently lower than that), and I do not expect T to be more than 5 (though 3 is a much more likely ceiling).

The basic assumption behind this algorithm is that the best route will optimally connect one of the pairs of vertices, and the others are more likely to save costs by connecting into this path than to connect directly using their locally optimal paths.  The trick is to find the correct order for connecting the pairs that best reduces the cost.  The following recursive approach is the backbone for the algorithm:

def planWorker(graph, pairs, ownedEdges, blockedEdges):
    if there are no pairs:
        return 0, empty set
    bestScore, added <- null, empty set
    build a Bellman-Ford table for every vertex in the graph
    // each ownedEdge costs 0
    // each blockedEdge effectively no longer exists in the graph
    for each pair:
        base <- distance to complete pair
        options <- all shortest paths connecting the pair
        // options is a set of sets of edges
        if this is the last ticket:
            bestScore <- base
            for each option:
                path <- option - owned
                added.add(path)
        else:
            for each option:
                subscore, subpaths <- planWorker(graph, pairs - pair, owned + option, blocked)
                total <- base + subscore
                if bestScore == null or total <= bestScore:
                    if bestScore == null or total < bestScore:
                        bestScore <- total
                        added <- empty set
                    for each subpath:
                        added.add(option + subpath)
    return bestScore, added

This algorithm's complexity is O(T! M^T |V|^2 |E|).  Called on its own, it finds at least a good threshold against which to compare other paths.  I have not yet found an example where it does not find at least a subset of the optimal paths, but I am not assuming that it does find optimal paths because I do not know that my assumption about optimal path structure is correct.

I have found that this algorithm does not find all paths of the same length for a set of pairs.  However, by adding an additional search testing untried edges, the algorithm does seem to try them all:

def plan(graph, pairs, owned, blocked):
    bestScore, added <- planWorker(graph, pairs, owned, blocked)
    candidates <- graph.edges - owned - blocked - flatten(added) // the "untried" edges
    for each candidate:
        base = candidate's weight
        score, alternatives <- planWorker(graph, pairs, owned + candidate, blocked)
        total <- base + score
        if total > bestScore:
            continue
        if total < bestScore:
            bestScore = total
            added <- empty set
        for each path in alternatives:
            added <- added + (path + candidate)
    return bestScore, added

The loop multiplies the computational complexity by E, giving the final computational complexity of O(T! M^T V^2 E^2).  There's probably additional terms that I am not accounting for that come from the set operations, but my guess is that the sets I am using do not really need more than an additional log E multiple for that.

I have hacked this approach (probably very inefficiently) in Java 8.  Running this implementation for four tickets on the Ticket to Ride map with no routes initially owned or blocked takes less than twelve minutes on my unplugged laptop with an Intel Core i7-4710HQ clocked at 2.5 GHz.  I can likely speed it up by cutting down on dynamic memory allocation and by threading the candidate checks instead of looping over them synchronously.  This algorithm solves the tickets (Los Angeles, Miami), (Los Angeles, New York), (Montreal, Vancouver), and (New York, Seattle) with a cost of 39 cars.  The six routes with that length it finds are shown below.  The initial planWorker() call finds the green route, and the candidate search finds the other five.


问:
Should I focus on being deep or broad
I have been a professional developer for just over half a year and have been amazed at how big the world really is out of college. I have continued to learn in my free time but I am wondering where should I focus?

FOCUS 1) The development stack used by my company. Quickest payoff in my day to day development. #Deepest

FOCUS 2) A different language with the same paradigm. See if I can generalize my knowledge and way of thinking.

FOCUS 3) Different language, different paradigm. Expand my borders and learn new ways to do things. #Broadest

If anyone has a different focus feel free to put that out there.

答:
Both options have their place. Focusing on the development stack used by your company will help you in your job, but learning about other technologies will help you in your career.

In the late 1990s, COBOL skills were in high demand by companies needing to prepare their software for the year 2000. But anyone who still knows only COBOL today will have a much harder time finding work.

In the same way, today's technology will be obsolete long before most of us are ready to retire, so learning new skills and technologies is essential.

Title: Should I focus on being deep or broad


问:
Domain analysis - why OFF points are inside of the domain when the border is open
I have asked on a few other sites, no response but it must be something silly as many authors mention in their books.

Here is the best text I found:

My ultimate question is:
Why the OFF point lies INSIDE the domain when the border is open. If it is about being off the border, why cant it be outside too?

EDIT: THank you for your answers. I found another contradicting article, what do you think?

According to the description, the INCLUDE gravity is when t>=1. However, for the other open domain, OFF point is OUTSIDE the domain, contradicting what you all and the other articles I quoted mentioned

答:
For closed domain, both OFF and ON points are outside domain, while for open domain, the OFF point is in inside the domain. I just do not get why is that.

This is incorrect. For both open and closed domain, one point is inside and one point is outside the domain. The difference is which point is inside (and which outside).

To test a domain boundary, you need one point on the inside, as close to the boundary as feasible, and one point on the outside, also as close the the boundary as feasible.

The point ON the boundary is by definition the closest you can get. For a closed domain, this point is defined to be the last point inside the domain and for an open domain this point is defined to be the first point that lies outside the domain.

Testing with two points ON the domain boundary does not provide you any additional information, so the second point must lie OFF the boundary.

If you combine the fact that you need both a point inside and a point outside the domain with where the point ON the boundary is considered to be (inside or outside), it follows logically where the point OFF the boundary should be located.

As for why you need points on the two sides of the boundary, If you have two tests telling you that the values 10 and 11 are both outside the domain, that doesn't tell you if the domain is (correctly implemented as) "values less than 10" or perhaps "values less than 9".


答:
For my important projects I try to make sure I have a backup of the following:

Dependencies for all releases.

Installation packages and instructions for all important tooling, such as IDE and compilers (used to build the application).

Saving them in your version control system is not the right thing to, as it is not created to store large blobs. Instead I use backuped project drive.

Automated solution with Nexus

For maven central (and comparable) dependencies you also have another option. I have done this in the past with Maven, but it can also be done with Gradle. The solution is to run Nexus as a cache. Instead of directly downloading your dependencies from Maven Central, you tell Gradle to download from Nexus, which in turn can be set up to download dependencies from a central repository, caching the artifacts in the process.

As noted by Sleske in the comments: Make sure that the cache is not automatically cleaned by Nexus. Also the following will have the added benefit that other local users will be able to download dependencies locally (so possibly quicker).

Title: Should I backup gradle dependencies to git?

Body:
I always like to backup project dependencies myself in case they can't be resolved due to a down website or because certain versions aren't available for download any more.

Should I trust the maven central repository to be up and running when I try to build my project in 2020? Or should I backup dependencies manual?

If I should backup manual, then where does gradle store the downloaded dependencies? Or does gradle come with an build in solution for this?


问:
How to organize predefined queries with Entity Framework?
I have some queries that I use all the time (like get rows only of some specific type, or count something etc.). I'd like to organize them somehow (better then I currently do).

Currently I have them all in a static class called Queries which I don't really like because it's like a I-don't-know-how-to-name-this-class.

Is there a preferred way for organizing predefined queries in Entity Framework by extending some types etc.?

As requested here is an example showing how I use it:

All of my queries:

```<code>public static class Queries
{
    public static IEnumerable<Light> GetEnabledLights()
    {
        using(var context = new MyEntities())
        {
             return context.Lights.Where(l => l.Enabled);
        }
    }
}
</code>```

Code using some query:

```<code>public static class LightsLoader
{
    public static void LoadLights()
    {
        var enabledLights = Queries.GetEnabledLights().ToList();
        if (enabledLights.Count == 0)
        {
            throw new InvalidOperationException("There are no enabled lights.");
        }
        // ... more code
    }
}
</code>```

Faking the query and testing the business logic:

```<code>[TestClass]
public class LightsLoaderTests
{
    [TestMethod]
    [ExpectedException(typeof(InvalidOperationException))]
    public void TestNoEnableLights()
    {
        using(ShimContext.Create())
        {
            ShimQueries.GetEnabledLights = () => Enumerable.Empty<Light>();
            LightsLoader.LoadLights();
        }
    }
}
</code>```

But back to the question:  I just thought Entity Framework might offer a better way for organizing queries then putting them all in a God-Class ;-)

答: Sounds like you are organizing your code by what the code is and not the domain it applies to. As a developer working with the entity framework, I would expect you to have a derived DataContext class with all your general CRUD operations. Since this DataContext is your gateway to the database, it would make sense to store the queries and methods that use them in your derived class. I suggest not exposing the literal query strings publicly, keep them private and create public methods that use them internally.


问:
Design, how to utilize The Hardware (multiple threads and/or GPU) while indexing (via a database) a very large set of binary files
Problem

How can design my file parser to maximize the hardware when processing (creating meta data for) a large file

(i.e. how to avoid being blocked by IO and running out of memory)

preferably I would like to give the user a "high priority" (locks the system apart from some progress UI) and a "run in background" option (Allows the user to start using data that has already been indexed/loaded)

Assumptions

Presumably I will have no problems having multiple threads reading the same set of files?

The way I see it the biggest bottleneck / will be writing to the database. Presumably I will have to lock/unlock that and have each thread queue up data to write in batches?

As each thread will need its own data queues I am unsure how to make sure the machine does not run out of memory

When processing the data blocks I basically want to get stuff like averages, minimums and maximums, I have assumed I can't use the GPU to process the data blocks like this? it feels like there is too much shared data to utilize the GPU here.

Detail:

I am working with very large data sets, split across multiple files (each "full" data file is 1.5gb and there are often several of these files (I am looking at one now that has 10)

The data effectively contains a series of buffers that I want to access 1 or more at a time.

|headerInfo-datablock|HeaderInfo-datablock|HeaderInfo-datablock| (thousands)

I want to go through the data file, filling a database with index information (so i can access specific blocks quickly based of either information in the header or the datablock itself). If I can I would also want to blit information to a graph image as I do it.

Hardware

The machine it will be ran on is a proper workstation PC so there is plenty of ram and processing power to utilize :)

On the top spec machine there is 64GB of ram and a i7 that is 12 cores (hyperthreaded) so in theory i could get away with loading the whole file into memory and then processing. But some of the lower spec machines have a lot less ram and the files that people are producing are getting bigger every day, so Its not very forward thinking to rely on that plan.

Technology

I am using C# so any tips on the best ways to judge the hardware capabilities in C# (at run time) and maximize them when accessing a set of large files, would be a great bonus

答:
Your main bottle neck will always be IO unless you are doing some seriously intensive computations. Your best bet for squeezing the most performance out of your target machine to read all files serially  (one at a time) and process each file concurrently (multiple calculation pipelines). Since you are using C#, I would suggest you look into using the Task Parallel Library for your calculation pipeline. The task scheduler is pretty darn smart about CPU utilization. You can provide it hints by specifying that particular tasks are going to be long running, thus requiring their own thread.

Design your processing pipeline such that it "pulls" data through and you'll never have more that one file in memory at a time. This means that every function which moves the pipeline forward must have some mechanism for bringing data in from the previous stage. The most common example of this type of mechanism in C# is the IEnumerable<T> and IEnumerator<T> interface pair and how they work with LINQ. You can think of LINQ statements as a series of pipeline operations that do no actual work until it is requested by some greedy function like ToArray().


问:
Best Data structure for implementation of dependent drop-downs
I want to implement dependent drop-down feature on a web page in my website containing the following drop-downs:

User's group name

Group events (dependent drop-down)

Locations (dependent drop-down)

Now, what I want is according to the selected option in the first drop-down that is group name (the other two will be disabled until it is selected), the list of events is displayed; only those values relevant to the selected group name should occur. Similarly, the values of locations should be in relevance to the group name and the event selected. Not only this, but I also want the design to be irrelevant of the level of dependencies or the current order (group name->events->locations). Even if I wish to add timings as another level of dependency, the design should incorporate it.

Now, in all the related questions to this problem tables are used to store data in databases like:

Best Data structure for dependent dropdown implementation

Two dependent drop-down lists with the values in two different
tables

Saving data of dependent drop-down - Yii

However, I wish to consider the following alternatives:

Trie: Since the order in which the attributes are selected is
defined, we could use a trie to store all possible combinations of
the list of values in each drop-down dependent on each other. Using
prefix search, we could retrieve the values of the next drop-down,
according to value selected in the previous one.

Table: similar to one used in above, we can store it in database but
then the number of levels of dependencies are not really fixed and
can increase in future. How do I handle that? (Assuming I don't want
to modify the schema every time this happens)

Graph: We could also store the possible combinations in a directed
graph and based on the values selected we can display all the next
adjacent nodes int he next dependent drop-down.

Which of these is a best approach, keeping in mind future extensibility or changes? Or any other suggestions for data structures are also welcomed. Please explain with proper design in detail considering complexity in mind.

答:
You're almost certainly overthinking this.  Your quest for an ideal data structure is a solution in search of a problem.

Look carefully at the example you gave.  All three of those dropdowns have a different data source, and they imply a relational structure.  Just by looking at the names of your dropdowns, I know that you have three tables: Groups, Events and Locations, each having primary keys and foreign keys that associate the tables with each other.

Three tables in a relational database is the ideal data structure for your scenario.

If you need a data representation that can be used in a web page, create a ViewModel object, but in non-trivial applications, it's often necessary to AJAX in the list for a particular dropdown, based on the selection provided by the user in the previous dropdown.  The lists can be too large to embed in the actual web page.


问:
Manage content for multiple websites and mobile apps
I need to manage content (pages, key/value list, assets and more) in one webbased system for multiple websites and mobile apps.

My idea is to create a web api, secured with tokens for apps and sites and some kind of OAuth authentication, also with JSON web tokens. I want to create it with ASP.net Web Api, Entity Framework and Identify.

My idea is to split up the cms into a single page application, probably in AngularJS, and the Web API. So first create the domain model, how do we need to structure all the content/data and store this. After that create the api. And when that is finished, I need to create a SPA-cms webapplication for the end users.

Every website or app can use the api to read and write data over https and with a secret token, and every other party is free to choose whatever technique or programming language they want to use.

What do you all think about this idea? Can it be a architechture/technique to use for a long time? And do you think this architecture can be used for high traffic websites?

Thanks!

Edit: I just want to talk about ideas... if this is the best for this time, to use an API, or just create a MVC-CRUD application with forms and stuff

答:
For the edit/admin interface, a SPA is fine.

For viewing the content, though I wouldn't recommend a SPA. Generally, you want to generate static pages from the content a user enters. This is faster/cheaper at runtime (serving static HTML is far easier than reading content from a DB and then rendering a page), and better for SEO. It's the approach used by most CMSs.


问:
Difference between DevOps and Software Configuration Management
What is the difference between Development Operations and Software Configuration Management?

For me it seems to be the same as long as both DevOps and Software Configuration Management are focused on:

Establishing development infrastructure - being in charge of version control, build management, deployment management, dependencies management, continuous integration and delivery, etc.

Using best practices for organizing developers environment.

Quality Assurance of development processes - gathering metrics of development effectiveness, working on eliminating bottlenecks of development process (running unit-tests, evaluating unit-tests coverage, running inspections, etc)

Infrastructure management - target platforms and its specifics.

Release management - making sure release has been delivered to customer/client in time.

Maybe I'm missing something? This link shows that usage of term 'Software Configuration Management' prevails. But still, what word combination would you rather use to describe listed range of activities: Development Operations or Software Configuration Management?

答:
Personally being a Sr. Software Configuration Manager for many years (10+) I hear the terms mismatched in a variety of real life situations.  It is not uncommon for non technical personnel due to the relative nature of the positions.  They both have specific roles, needs and requirements that are similar but yet can be clearly divided in my opinion.

I believe the best way to describe the division of these roles is to focus on their relativity to interaction.  Meaning this, Software Configuration Management focuses on the internal systems and environments, along with integration, deployment, release and management of source code.  Where as Developer Operations (DevOps) focuses more on the operational aspect of externally faced application architecture, while maintaining a clear understanding of the code as it was intended for use and the practice of its environment.  If the performance of a machine is showing signs of degradation, communication between multiple applications is faulty, business to business (BtB) communication and/or architecture limitations in relation to a production environment, then you would look to the Developer Operations for their diagnosis and solution.

Typically, in my experience, the Software Configuration Manager can do these things as well, but this takes away from their core focus of tracking, managing, and deployment of environment configurations and software revisions.  Managing the software that allows the separation of duties, bug and defect tracking, project tracking, and the software development lifecycle and worflow.  These tasks are not the core focus of Developer Operations and therefore less imperative, but still can be done.

I have seen many instances of the confusion of each, and in each there is some limited crossover.  However, it is most important to think of the differences between the responsibilities of each of the independent positions in relation to their primary focus.  Primarily when dealing with internally utilized systems and hardware to manage the configuration of environments and release of product, you would seek out a Software Configuration Manager. On the other hand, when dealing with system performance, monitoring, research and diagnosis of systems used by your customers, you should look to the Developer Operations or DevOps.

Now, this is not a meant as a rant, nor as a definitive answer, but rather a personal identification of the differences of each of the positions.  I would like to know if I am well off base, or if things are made clearer by this answer.


答:
They are giving rules about how to chose test points.

you have to have in test points and out one (or you'll have tested only one side of it).

you have to have on test points (to be sure to test the limit) and off one.

For closed borders, the on test points are in, thus there must be an off one which is out.

For open borders, the on test points are out, thus there must be an off one which is in.

Title: Domain analysis - why OFF points are inside of the domain when the border is open

Body:
I have asked on a few other sites, no response but it must be something silly as many authors mention in their books.

Here is the best text I found:

My ultimate question is:
Why the OFF point lies INSIDE the domain when the border is open. If it is about being off the border, why cant it be outside too?

EDIT: THank you for your answers. I found another contradicting article, what do you think?

According to the description, the INCLUDE gravity is when t>=1. However, for the other open domain, OFF point is OUTSIDE the domain, contradicting what you all and the other articles I quoted mentioned


答:
From the definition, "off points" can be inside or outside the domain, both cases match that definition.

But the text says "how should you choose test points" (which means - to get a good test coverage with as few cases as possible). So when you have chosen an "on point" which is inside the domain in case of a closed boundary, it makes just more sense to choose an off point outside the domain, and vice versa.

To your edit: in the "Ignore Gravity" domain, the point 1000ms is on the boundary, and it is already outside the domain. So it makes more sense to choose an "off" point inside the domain, which means at the "Ignore Gravity" side, so 999ms would be a better choice than 1001ms (note that both values are off points for both domains). Note that when looking at the "Include Gravity" domain 1000ms is inside, and 999ms is outside, so from that point of view it makes also sense to prefer 999ms.


问:
Laravel - BLOB File Management System - Possible obstacles?
I'm working on this weird project where I need to upload huge files (500mb+) and store them in a postgresql table as a blob.

Before you start telling me that storing files in the database is bad and that I should use the filesystem instead, hear (read) my reasons:

The access to the files must be authorized through the app, where individual permissions to them are applied.

I will need to keep an history (versioning) of each file, giving access to previous modifications.

I can't afford the risk of losing consistency between the relations and the files/versions over the course of the years.

Now, on to the questions:

Do I risk getting timeouts during upload/download or the download process counts as a 'keep-alive'?

Are the files completely loaded into memory for each user or are they buffered (streamed) to the user? I need to allow some thousands of users to download big files at the same time.

Are there any packages that can help me with this?

答:
This sounds like a very tough nut to crack, I'm not even sure it can be cracked at all.

The database is going to become enormous and hence slow in a short period of time, caching is not going to happen on any appreciable level.

Keeping multiple copies of such big files for versioning is going to require an inordinate amount of disk space (which is cheap, granted, but you are talking about years worth of big files).

Are you sure you have such requirements? The way it's been envisioned, this project is going to require huge hardware resources (not to mention bandwidth, both incoming and outgoing).

If your customer/boss has a budget to boot then it's cool, but I just wanted to point this out. This is a tough challenge from an engineering standpoint, the kind of challenge that you want to avoid if at all possible.

The only thing I can think of in order to save some space on disk is storing the first version of a file and then calculating and storing binary deltas against it.

Not knowing the nature of the binary files you're dealing with, I can only suggest that you look into bsdiff or even Google's Courgette (which is what they use to push Chrome updates out). They have the added benefit of compressing in addition to generating a binary delta. You're going to have to drop to either C or C++ for that subsystem, though, because I'm not really sure PHP would cut it.

Both bsdiff and Courgette are geared towards executables, which can change wildly even for small source code modification, so they could work even better for files that don't change that much from one version to the next.

And this is about all I can suggest.


问:
Injectable, Poppable Stack

Background

A project involves converting a relational expression map (rxm) to an XML/SQL statement. The map resembles:

```<code>root               > people,            # "root" keyword starts the document
person             > person,            # maps table context to a node
.first_name        > first,             # maps a column to a node
.last_name         > name/last,         # maps a column to an ancestor node
.age               > @age,              # @ maps a column to an attribute node
account.person_id +> person.person_id,  # +> performs an INNER JOIN
account            > account,           # context is now "account" node
.id                > @id,               # account id attribute
^,                                      # pop stack to previous context
address            > address,           # switch context to "address" node
.*,                                     # .* globs all columns
account.person_id -> company.person_id, # -> performs an OUTER JOIN
;                                       # Starts the optional WHERE clause
</code>```

The rxm is converted into Java classes using ANTLR.

Walking through the AST uses a Visitor pattern that calls methods for entering and exiting various parts of the tree. For example:

```<code>  @Override
  public void enterRoot( QueryParser.RootContext context ) {
    System.out.println( "Root: " + context.getChild(2).getText() );
  }

  @Override
  public void exitRoot( QueryParser.RootContext context ) {
    System.out.println( "<< root" );
  }
</code>```

Problem

The code needs to generate an XML/SQL statement along the lines of:

```<code>XMLROOT (
  XMLELEMENT (
    NAME people,
    XMLELEMENT (
      NAME person,
      XMLATTRIBUTE( ... )
    )
  ),
  VERSION ’1.0’,
  STANDALONE YES
)
</code>```

At the time that either enterRoot or exitRoot are called, it is not known whether there will be another line mapped using rxm. Ideally, I'd like to write:

```<code>  @Override
  public void enterRoot( QueryParser.RootContext context ) {
    String root = context.getChild(2).getText();
    getStack().push( "SELECT XMLROOT( XMLELEMENT( NAME " + root );
    getStack().push( "VERSION '1.0', STANDALONE YES )" );
  }
</code>```

Question

Using a stack seems to be a good way to generate the query based on the visitor pattern.

What data structure would you use to convert a linear map into a hierarchical query?

Would it be feasible, for example, to just pop the last element from the stack (i.e., the line containing the closing parenthesis), store it locally, then push it back on afterwards?

答:
Use a Tree data structure then convert it to a string using recursive polymorphic toString methods.

Let me reiterate your question in my own words to make sure I understand you correctly:

It appears that you are writing a Domain Specific Language (DSL) that you wish to convert directly your desired output via string manipulation without any intermediate representation. Your question is about your current solution and your choice of data structure required for building of the final string.

If your recursion calls get too deep, you can build a set of classes to walk the tree and build up the string as they visit each node using a depth first search. All this is assuming you have no circular references in your tree.

After re-reading the question, I think I have a better understanding of what you have implemented and what tools you are using. I had assumed you were skipping the whole process of AST generation because I missed that on my first few reads. Can you control how the visitors walk the tree? If start building your string with the deepest child and before you start walking back up the tree, you should just always be wrapping the previous string with opening and closing tags of the current node. Then there is no need to track whether or not you have to insert a closing tag or not, you just always do.

Title: Injectable, Poppable Stack


问:
Styleguide when coding in a static language
I am currently a junior engineer and keen on learning best practices and expanding my experience. My question concerns any static programming language such as Java, C#, C++ etc.

When I am writing code, I like making it easy to read. In my opinion, reading code should be like reading a book. It should be fluent and elegant. Then, even if I do not need to use them, I like prepending this, super–base keywords whenever I can. Ditto for current class name when I want to use constants or static variables/methods.

Consequently, another developer can quickly have a long shot. He knows this method or var is in the current class or in mother class without needed to move to declaration. You may say to me it is really easy to do that with recent IDE. However, I know a bunch of guys who are still working with Vim, Emacs or other editors without these fancy features.

When explaining it, I like comparing my practices to a drama book. We have all read at least one of them, such as Macbeth from Shakespeare. Who has never felt frustrated to go back at the beginning of the book to know who is that character and what part he has in the plot? You did that so many times, right?

My question can be associated to literate programming practices. However, I assumed Donald Knuth's recommandations are more about commenting and adding macros to your code.

So I would like to know your opinions and feedbacks about these practices. Am I doing too much? Should I keep it simpler? Am I breaking OOP rules?

Here is a code sample:

```<code>class Bar {
    protected int _motherVar;

    public aBarMethod() { }
}

class Foo extends Bar {
    private static List<String> _strings;

    private int _myPrivateVar;

    public void aMethod() {
        super.aBarMethod();

        this._myPrivateVar++;
        super._motherVar -= 2;
    }

    public static String anotherMethod() {
        String outcome = "";

        for (String s : Foo._strings) {
            outcome += s;
        }

        return outcome;
    }
}
</code>```

答: I am not sure about Java, but C# has a whole set of framework design guidelines, that includes naming conventions for public and protected members. Protected fields are not recommended. Use protected properties instead.</p>


问:
Design of actions handlers requiring some order
I have a REST application where 'actions' can be executed to perform anything in the system. For example: user.save, user.get, etc...

I also have pre and post execution 'handlers'.  For example a post execution handler is used to add tags to the users; it's an AddOn module that handles the tags of the users (and other entities). I also have another module (called Rules) that can, for example, validate the user information and do something based on that (eg, send an email).

The problem I'm facing now is that in general the execution order of those modules is not important, but sometimes it is. Take the following cases:

Example 1:

Action: Save user

Handler: Tag the user as "VIP"

Handler: Send an email if user is tagged as "VIP"

=> The email gets send.

Example 2:

Action: Save user

Handler: Send an email if user is tagged as "VIP"

Handler: Tag the user as "VIP"

=> The email won't be send.

All the operations (action and handlers) are executed inside a single transaction.

What would be a good solution to make sure the "Send email" handler is executed after the "Tag user" one?

Some ideas:
 - Have post-action handlers and post-(post-action) handlers. But how many post-post-post would I end up adding?
 - Add a weight or priority index to each handler. But when you end up having several handlers, the priorities tend to be confusing as each module doesn't know about the other modules and handlers.

What would you recommend? Thanks.

In case anyone finds it important: it's C# 4.5, ASP.NET, IIS.

答: I would consolidate the actions and handlers into higher level abstractions that operate using a fixed order of operations. The priority-based solution will not scale.</p>

OwnerDisplayName: Diego Jancic


问:
What algorithm can I use to find the biggest subarray within a 2d array with only n different numbers?
Let's say I have a 2d array 100x100 in size, each cell in that array has a number from 1 to 50 randomly.

How do I find the biggest subarray in a rectangle size in that array that has only n different numbers?

Small example:

```<code>array: 1 2 3 3 3 2 2
       7 4 3 3 4 9 8
       1 2 3 3 3 4 2
       7 6 1 9 9 4 2
In this case the biggest sub rectangle with only 1 number allowed would be
       3 3
       3 3
With 2 numbers allowed it would be
       3 3 3
       3 3 4
       3 3 3
</code>```

Does something for this exist?

答:
You could try something like:

Grab the whole 2d array

Remove first column / first row / last column / last row

Stack each of the four resulting subarrays.

Store the biggest one that meets the condition, if it's bigger than
the biggest one that currently does (if any).

Repeat procedure for each subarray in the stack

By doing this you would have checked every possible subarray you can take form the starting array, and made sure you got the biggest possible. If you want it a bit faster you can return early when no more arrays bigger than the current biggest one are left


答:
Extending the ORM Context is a good approach, but in a system with lots of predefined queries, I use to take another approach, using Extensions methods in order to group the related queries. Let me give an example:

The usage is kept simple like this:

```<code>var data = Context.Financial() // This returns a FinancialContextExtensions instance with all Financial grouped queries
                  .GetComplexReportData() // This returns the actual result for your query
                  .ToArray();
</code>```

I create a file FinancialContextExtensions:

```<code>public static partial class ContextQueryExtensions
{
    public static FinancialContextExtensions Financial(this DataContext context)
    {
        return new FinancialContextExtensions(context);
    }
}

public class FinancialContextExtensions : ContextExtensions
{
    protected readonly DataContext Context;

    public FinancialContextExtensions(DataContext context)
    {
        this.Context = context;
    }

    public IEnumerable<FinancialReportInfo> GetComplexReportData(DateTime dateBeing, DateTime dateEnd)
    {
        return from a in Context.AAA
               join b in Context.BBB on ...
               where ...
               group ...
               select new FinancialReportInfo { ... };
    }
}
</code>```

PS: I don't know if this pattern has a name, but a I remember reading it on a site, don't know what site though...

Title: How to organize predefined queries with Entity Framework?

Body:
I have some queries that I use all the time (like get rows only of some specific type, or count something etc.). I'd like to organize them somehow (better then I currently do).

Currently I have them all in a static class called Queries which I don't really like because it's like a I-don't-know-how-to-name-this-class.

Is there a preferred way for organizing predefined queries in Entity Framework by extending some types etc.?

As requested here is an example showing how I use it:

All of my queries:

```<code>public static class Queries
{
    public static IEnumerable<Light> GetEnabledLights()
    {
        using(var context = new MyEntities())
        {
             return context.Lights.Where(l => l.Enabled);
        }
    }
}
</code>```

Code using some query:

```<code>public static class LightsLoader
{
    public static void LoadLights()
    {
        var enabledLights = Queries.GetEnabledLights().ToList();
        if (enabledLights.Count == 0)
        {
            throw new InvalidOperationException("There are no enabled lights.");
        }
        // ... more code
    }
}
</code>```

Faking the query and testing the business logic:

```<code>[TestClass]
public class LightsLoaderTests
{
    [TestMethod]
    [ExpectedException(typeof(InvalidOperationException))]
    public void TestNoEnableLights()
    {
        using(ShimContext.Create())
        {
            ShimQueries.GetEnabledLights = () => Enumerable.Empty<Light>();
            LightsLoader.LoadLights();
        }
    }
}
</code>```

But back to the question:  I just thought Entity Framework might offer a better way for organizing queries then putting them all in a God-Class ;-)

Body:
Extending the ORM Context is a good approach, but in a system with lots of predefined queries, I use to take another approach, using Extensions methods in order to group the related queries. Let me give an example:

The usage is kept simple like this:

var data = Context.Financial() // This returns a FinancialContextExtensions instance with all Financial grouped queries
                  .GetComplexReportData() // This returns the actual result for your query
                  .ToArray();

I create a file FinancialContextExtensions:

public static partial class ContextQueryExtensions
{
    public static FinancialContextExtensions Financial(this DataContext context)
    {
        return new FinancialContextExtensions(context);
    }
}

public class FinancialContextExtensions : ContextExtensions
{
    protected readonly DataContext Context;

    public FinancialContextExtensions(DataContext context)
    {
        this.Context = context;
    }

    public IEnumerable<FinancialReportInfo> GetComplexReportData(DateTime dateBeing, DateTime dateEnd)
    {
        return from a in Context.AAA
               join b in Context.BBB on ...
               where ...
               group ...
               select new FinancialReportInfo { ... };
    }
}

PS: I don't know if this pattern has a name, but a I remember reading it on a site, don't know what site though...


问:
Github convention for putting projects on hold
I have a few github projects on the go at the same time.

I am only actively working on one at any one time which can take months. My other projects remain in a semi-completed state. Is there a developer convention to indicate a project as being on hold? I.e. no active development?

答:
You could always update the Readme (since I'm assuming most people will see that on the main Github page for your project).

I would say just continue on doing what you are doing. Work on another project and come back to this one when you're ready. Maybe someone will fork and contribute in your absence. Who knows, that is the beauty of open source. Your timestamp for checking in revisions should indicate to everyone who doesn't check your Readme that you are busy elsewhere.


答:
If the project is not usable in its current form, say something to that extent near the beginning of the README. It doesn't have to be a bold big all-caps "Do not use", but it should be noticeable to an idiot in a hurry to save everyone's time.

If the project is usable but in a dire state, you should probably say in rather clear terms that you are not maintaining the project and (if you want to be nice) suggest alternatives for people who are using the project or would want to use the project. If the project is registered on package manager repositories like NPM, RubyGems, PyPI, etc, it's probably also good form to publish "one last update" to update the description -- but don't have your package emit additional console output unless the user can disable it.

If the project is usable but you need to take a hiatus, make this clear in any open issues. It's good to know that a project isn't actively maintained at the moment but not dead, because otherwise you may not think to have another look when the maintainer resumes their work (or a new maintainer has taken over). Also do this if you are actually looking for maintainers: if someone went through the trouble of creating a PR or raising an issue, they may be interested in contributing further or at least tell others.

Additionally, if you have a lot of active and a lot of inactive repos cluttering up your account and you find the inactive ones too distracting, you could create a GitHub organization and move the unfinished/exploratory projects there. It won't be an obvious indicator to others, but you may find it soothing. I may have gone overboard with this (I also moved all my one-off forks into a separate org), but I think it's more humane than just deleting abandoned projects.

Title: Github convention for putting projects on hold

Body:
I have a few github projects on the go at the same time.

I am only actively working on one at any one time which can take months. My other projects remain in a semi-completed state. Is there a developer convention to indicate a project as being on hold? I.e. no active development?


问:
Is a 'least significant bit' used anywhere practically today?
I'm working on a library that supports file reading, and right now I've always assumed that all the bytes are written in most significant bit first format. Is the least significant bit first format ever practically used anywhere today on any platform? The library I'm writing isn't targeted at older operating systems (ideally anything onwards from the year 2000).

I'm curious if writing such a feature in might be a waste of time that could be spent on other things.

答:
Given that things such as characters / letters, numbers, and raw in essentially every format and programming language use the most significant bit first format, you can apply the ostrich solution to this problem. Your time is better spent working on the actual library itself instead of a feature that will likely never be needed.

Also, as some people have mentioned, a decent amount of integers that use the least-significant-* format use the most-significant-byte format which is a different thing.


答:
If you are looking for a very precise answer, you will need to define very precisely what "least significant bit format" means. As evident in the comments, there can be a lot of interpretations of what that means, and a lot of details can be glossed over by a not very careful reader.

Example #1 - BMP image format, for black-white (1bpp)

For one example of "least significant bit first format", consider the BMP image format, 1bpp.

A black and white (bitonal, or 1-bit-per-pixel) image stored as BMP will have its row-zero, column-zero pixel stored at the bit 7 of the byte 0 of the pixel data area.

As a matter of arithmetic, the term "bit 7" always unambiguously refer to the bit mask 0x80, because it is the "7th digit of its binary representation". (the 0th digit is the bit mask 0x01.)

Example #2 - TIFF Fax

http://www.awaresystems.be/imaging/tiff/tifftags/fillorder.html

The original TIFF Fax specification was designed with hardware (electronic) implementations in mind, and therefore has to deal with electrical serialization and deserialization. With it comes the choice of which bit to send down the wire first. Thus, the specification allows for both, and therefore every TIFF image reader has to support reading both kinds of files and to perform the necessary conversion before decoding the bit stream.

Title: Is a 'least significant bit' used anywhere practically today?

Body:
I'm working on a library that supports file reading, and right now I've always assumed that all the bytes are written in most significant bit first format. Is the least significant bit first format ever practically used anywhere today on any platform? The library I'm writing isn't targeted at older operating systems (ideally anything onwards from the year 2000).

I'm curious if writing such a feature in might be a waste of time that could be spent on other things.