Category Archives: tips

MS Wheel Mouse Optical Redux (August 2018)

Back on the WMO train again. I was using Sweetlow’s signed driver, but it stopped working again, probably due to Windows updates. You can find the old guide here.

I’m on Windows 10 Home 64-bit, version 1803. Here’s how to get it working at the time of writing.

The main google result is not the actual official Sweetlow post. It links to a thread on the overclock.net forums that was not made by Sweetlow. Instead, follow the instructions on Sweetlow’s official (and up to date!) post.

Unfortunately, the ‘vanilla’ signed driver no longer works for me, but I would recommend trying the main instructions first.

I had to use a workaround that is covered in his post. Specifically, the part where he says:
2. If you have EHCI (USB2.0) Controller only on version x64 1703+ or any controller on version 1803+ use these drivers and (Test Mode or atsiv method with non Test Mode)

I haven’t had any luck with the atsiv method, but the test mode suggestion worked (after a bit of fumbling around).

Here are explicit steps on how to do this workaround. As ever, I will caveat this by saying it may not work for you.

Backup your files

  • Backup the following files:
    • %systemroot%\system32\drivers\usbport.sys
    • %systemroot%\system32\drivers\usbxhci.sys

Enable test mode to allow unsigned drivers

  • Open a cmd prompt with admin privileges and type the following commands
    • bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
    • bcdedit -set TESTSIGNING ON
    • Reboot

Finally, install the driver

We’re going to download the official Sweetlow package (which contains the installer and versions of the driver) and replace the official driver with a patched version. We will then use the official installer to install a patched driver.

  1. Download & unzip https://www.overclock.net/attachments/45829 (you need an overclock.net account to do this) to a directory called “official”
  2. Download & unzip https://github.com/LordOfMice/hidusbf/blob/master/hidusbfn.zip to a temp directory called “patch”
  3. Navigate to “patch”
  4. Copy the DRIVER\AMD64\1khz\hidusbf.sys file
  5. Navigate to “official”
  6. Replace its DRIVER\AMD64\hidusbf.sys + DRIVER\AMD64\1khz\hidusbf.sys with it (I suspect the installer uses the first of these, but I haven’t checked for sure, so replace both)
  7. Still in “official”, run setup.exe
  8. Check the “Filter On Device” box
  9. Change the rate to 1000hz
  10. Click the “Install Service” button
  11. Click the “Restart” button
  12. Close setup.exe
  13. Open mouserate.exe (or browse to https://zowie.benq.com/en-eu/support/mouse-rate-checker.html) and check your hz

If that didn’t work, reboot. If you mess it up and your mouse stops working, simply go to device manager, uninstall the WMO via remove device, then unplug it before plugging it back in. You’re then OK to try again.

Focused commits (also: git add -p)

Many people use version control as a bucket for their stuff. They commit and merge in some shape or form, and it gets shared with their colleagues. Everyone moves on with their lives. Fire & forget sucks when using distributed version control systems.

The trouble with this approach is that it gets complicated to track two simple things:

  1. When was a change introduced?
  2. What is the purpose of the change?

How do we use git in a way that makes it easy to track both when a change was introduced, and the intent of the change? Read more »

MS Wheel Mouse Optical Redux (WMO 1.1 & Windows 10 x64)

Back in 2011, I wrote a fairly gushing post about the Microsoft WMO 1.1/1.1a. It’s a great mouse. It really is.

The end of my WMO

Sadly, in late 2016, the venerable WMO gave up the ghost – its death certificate listed a faulty cable. Basically, I’d be playing Overwatch and it’d randomly disconnect, then reconnect. I’m not a technician, so I binned it.

I then bought a Steelseries Rival 100, as I needed a stopgap mouse. The Rival 100 is a decent mouse, but its shape doesn’t agree with me (it’s too narrow), and it’s a touch too heavy for my tastes.

Finding a replacement mouse model

I decided to try and track down a decent WMO replacement. After a bit of a hunt, I couldn’t find anything that’s 100% suitable; some people recommend Zowies like the EC2-A or FK1, and others like the Razer DeathAdder Chroma.

It’s tough to track down accurate information regarding the unpackaged weight of the mouse, too. The WMO weighed in at ~80g, and in my opinion is better for it.

Furthermore, I don’t want a mouse with stupid cloud software (S3 is down? Well, not sure how to load your mouse settings man!), and I’m not really a fan of spending £60 on a mouse in what is essentially a blind purchase. I might love it, but I might hate it.

Read more »

The fundamentals of unit testing : draw attention to ‘interesting’ values

3 is the magic number? No. No, it’s not. Magic numbers/strings/other values in all walks of programming are a readability and maintenance liability. It’s quite common to see all kinds of literals being littered through test code. It’s quite easy to simply switch off and treat test code as a second class citizen.

To illustrate this point, please tell me what this does

[Test]
public void TestInvalidFuelAmount()
{
    // Arrange
    var car = CreateLittleCar();

    // Act & Assert
    var exception = Assert.Throws<ArgumentException>(() =>  car.AddFuel(500));
}

It’s not exactly crystal clear, is it? Although the naming of this test can and should be improved, bear in mind that it’s an extremely simple case (one method call with one argument being passed). Despite this, the intent is still obscured because of a literal.

Replace literals with named consts

Let’s change 500 to a named constant. Let’s also change the test name while we’re at it.

[Test]
public void when_the_car_fuel_tank_capacity_is_too_low_and_fuel_is_added_an_exception_is_thrown()
{
    // Arrange
    var car = CreateLittleCar();
    const int LitresOfFuelThatIsTooLargeForTankCapacity = 500;

    // Act & Assert
    var exception = Assert.Throws<ArgumentException>(() => 
            car.AddFuel(LitresOfFuelThatIsTooMuchForTankCapacity));
}

Now that’s much clearer. We can see what the value represents, the units it’s measured in and its place in the test. Some people shit the bed when they see really long story-like variable names in tests, but they’re generally a help, not a hindrance.

While the previous example is simple, this tip makes much more of a difference in situations where a function/method/constructor has numerous parameters, but the test is largely focused on only one of them. How do you know which one to pay attention to?

[Test]
public void when_account_balance_is_low_money_transfers_fail_when_would_be_overdrawn()
{
    // Arrange
    var currentAccount = GetCurrentAccountWithBalanceInUSD(10);

    // Act    
    bool transferSucceeded = currentAccount.TryTransfer(1000, 42, 602402);

    // Assert
    Assert.That(transferSucceeded, Is.False);
}

Fine, this is a crufty-looking API, but in certain circumstances, it’s quite common to see functions/constructors that take multiple arguments of a similar type. At a glance, how can you tell which of the arguments is the one of interest to the test? Is it 1000, 42 or 602402? What is the significance of any of them? Which one is causing the transfer to fail?

Let’s use a named const to draw attention to the interesting argument.

[Test]
public void when_account_balance_is_low_money_transfers_fail_when_would_be_overdrawn()
{
    // Arrange
    var currentAccount = GetCurrentAccountWithBalanceInUSD(10);
    const int AmountInUSDThatWillForceAccountIntoOverdraft = 1000;    

    // Act    
    bool transferSucceeded = currentAccount.TryTransfer(AmountInUSDThatWillForceAccountIntoOverdraft , 42, 602402);

    // Assert
    Assert.That(transferSucceeded, Is.False);
}

Turns out the 42 is the number of cents in the transfer, and that 602402 is just a dummy customer number we’re passing through.

We can go further than this to clean things up still further by doing things such as:

  • Extract a wrapper test method that calls TryTransfer, but only has one parameter: the amount of USD to withdraw (the other parameters can be satisfied with constants). This draws attention to the important part of the test (varying the value of the USD transfer amount) and also helps insulate the tests from changes to the TryTransfer method.
  • In the production code, using types that are more appropriate to reduce ambiguity (e.g. in the case of a customer account number, an AccountCredentials class would be more suitable than an int!)
  • Finally, if lots of things are changed in the tests, but in slightly different ways each time, consider the use of a Test Data Builder. Test data builders are very useful, as the provided defaults are sensible for most cases. As a result, when arranging your test, the only things that are changed in the builder are the things that actually matter. Test data builders can also insulate the tests from breaking changes.

The fundamentals of unit testing : Arrange, Act, Assert

Arrange, Act, Assert” (aka “AAA”) is a very simple way to structure your tests – I thoroughly recommend it. It is especially helpful when learning the ropes.

For this post, I’ll use the following example test scenario: When a stack is empty, pushing an item increments the count to one (this example was previously discussed in Narrow & Focused, if you want more context)

[Test]
public void pushing_an_item_onto_an_empty_stack_increments_count()
{
    // Arrange
    var stack = new Stack<bool>();

    // Act
    stack.Push(false);

    // Assert
    Assert.That(stack.Count, Is.EqualTo(1));   
}

Each ‘phase’ of the test happens in order and occurs precisely once. Arrange precedes Act, Act precedes Assert. I’ll go into a little more detail later as to why this is a useful property.

A brief description of each “A” follows.

Read more »

Integer to binary string in c#

Python has the terribly useful functionality of bin() to do this, but what about C#?

On the rare occasion I have to monkey around with bitwise operators, I always keep this handy. It has the added bonus of printing the leading zeros – I find this very useful when writing/debugging bitwise code, as it makes it easy to line up bitmasks etc. in the immediate window / console.

public static class BinaryPrinter
{
    public static string ToBinaryString(long _long)
    {
        // have to do this or it won’t print the leading 0 values       
        return Convert.ToString(_long, 2).PadLeft(sizeof(long) * 8, ‘0’); 
    }
}

Similarly, you could write a few of these (for all of the various inbuilt types) and chuck them in extension methods.

Python data-driven testing, ddt and @unpack

Several eons ago, I wrote a blog post about using the python ddt package. My only criticism was that you had to manually pack/unpack the test case arguments.

Happily, the developers of ddt were nice enough to add an @unpack decorator! You can now provide lists/tuples/dictionaries and, via the magic of @unpack, the list will be split into method arguments.

Documentation is here: http://ddt.readthedocs.org/en/latest/example.html

Empathetic Code

I always liked the phrase, “if you’re incapable of empathy, then you shouldn’t be designing APIs”.

I’ve worked with some terrible libraries in the past and the worst ones all had a common design flaw: the author didn’t put themselves in the user’s place. Worse still, sometimes the author just didn’t give one. When someone using the code pointed out that something was hard to understand or didn’t make sense, they were met with a snarl and shouted down; “it makes sense; you’re just using it wrong”.

On the other hand, I’ve occasionally picked up libraries/frameworks that make an extra effort to guide you along the correct path. The author of the code understood where users were likely to stumble.

image

It doesn’t matter whether it’s a carefully designed API you’re crafting for external use or internal code that will only be viewed and modified by engineers inside the company, you can always do something extra, especially if it’s something that’s already tripped you up.

If you encounter a gotcha, why not write a bit of code to clearly document the case, particularly if it is time-consuming to debug in the first place?

Read more »

A R#/Visual Studio style keymap for PyCharm

PyCharm is a lovely little IDE for Python by the splendid JetBrains, but the built-in Visual Studio keymap is not much like the default VS/R# settings I’m accustomed to. I’ve rustled up a quick version that restores all of the easy to remember refactoring key combinations (Ctrl-Shift-R, Ctrl-R, Action Key etc.) along with some of the common navigation ones (Ctrl, comma for recent files and so forth).

There’s a few things missing and I’ve unbound some of the PyCharm functionality as it clashed with the R# style keymap, so your mileage may vary. Give it a try, though!

You can download it here: http://defragdev.com/files/RStyle.xml

The fundamentals of unit testing : Tests shouldn’t ape the production code

Aping the logic of the class under test is an bad idea when writing tests, but it’s an easy mistake to make.

Aping… Bueller?

"Aping" simply means imitating/repeating the logic used in the class under test. In its simplest form, the problem can be illustrated like so:

Production code:

public class Calculator
{
        public int Add(int a, int b)
        {
                return a + b; // actual logic of the class under test
        }
}

A test for the above class:

[Test]
public void adding_two_numbers_returns_the_sum()
{
        // Arrange
        var calculator = CreateCalculator();

        // Act
        int result = calculator.Add(1, 2);

        // Assert
        Assert.That(result, Is.EqualTo(1 + 2)); // ape alert, ooh ooh ooh! >:O
}

Although this doesn’t look like the end of the world, we can see that the test method line "Assert.That(result, Is.EqualTo(1 + 2))" is directly replicating the logic in the Add method.  This is “aping”.

Why is this a bad thing?

This is bad for a few reasons. Firstly, if the class under test is bugged and the test apes its logic to get an expected answer, we’ve just reproduced the bug in our test code and erroneously passed the test. So, instead of having working production code, we have two bits of bugged code and a false sense of security.

Secondly, when writing tests, if state can be tested, it should be done using as declarative a style as possible — we don’t want to say how we get to the answer, just what it should be.

I don’t want to see the test code literally add 1 and 2 to get 3. Instead, I want to see 3 in the test.  Here’s a fixed-up version of the test that does not ape the production code:

[Test]
public void adding_two_numbers_returns_the_sum()
{
        // Arrange
        var calculator = CreateCalculator();

        // Act
        int result = calculator.Add(1, 2);

        // Assert
        Assert.That(result, Is.EqualTo(3));   
}

You should always scan your test code looking for this anti-pattern.  The example I’ve cited is very simple, but I’ve seen a lot of real world code that has succumbed to aping the production code resulting in bugs going undiscovered.

Validating your answers

You may be thinking, “OK genius, so you skipped adding 1 and 2 in the test code, but you must’ve known to follow the addition algorithm in your head to be able to come up with the answer of 3.  How do you know your brain didn’t get it wrong and the test is bugged?” 

It’s a good question and the truth is, it’s often the case that it’s not clear-cut.  However, there are steps you can take to validate your answers (or at least be a little more sure of them).

  • Don’t just assume you’ve got it right first time.  Double check it for a few minutes more.
  • Write out some notes on paper (I sometimes do the testing version of truth tables).
  • Maybe you have a specification for this particular part.  Use it to check the answer  (stop laughing at the back, there! – it occasionally does happen; e.g. conventions for a maths library).
  • Use an alternative method to come up with the same answer (it’s often the case that the same value can be calculated via multiple algorithms / schemes).
  • Use an existing implementation to corroborate your findings.  E.g. if you’re writing a test to make sure that JSON is validated correctly, then check that JSONLint.com agrees with your test results.
  • If you’re not sure how to corroborate an exact answer, then check any invariants you’re aware of as a smoke test.  If any of the invariants don’t hold, your answer is probably wrong.