Clare’s Birthday Dinner

Clare’s birthday meal at Red Chilli went very well. We had ten people, and that meant that we could share. Tried a bunch of different things, had good conversation, then everyone came back to our place and we had cake and wine. Thanks to everyone who attended; it was a great night out.

The Game Crafter

An interesting site for all my gamer mates; [The Game Crafter](http://www.thegamecrafter.com/home) is a site which lets you design your own card and board games, and package them up for purchase. [Hacker News](http://news.ycombinator.com/) had it linked as ‘CafePress for boardgames.’

Anyway, the barrier to entry has dropped significantly for producing home-baked games.

Fitness, Fatness; what matters for diseases like heart disease?

I’ve been reading the rather excellent [junk food science](http://junkfoodscience.blogspot.com/) blog recently, and I’ve found it really interesting. The author shares some of the big research into obesity and nutrition. What’s really interesting is that many of the guidelines we hear on a regular basis seem to have no scientific credibility. And I don’t mean things that sound outlandish, like diets composed entirely of cranberries and algae smoothies, but really straightforward, everyone-believes this stuff. Things like;

– being overweight causes heart disease.
– eating fruits and vegetables is good for you.
– reducing your fat intake is healthy.

What’s interesting is how little is shown to be true by actual respectable science. In [this article](http://junkfoodscience.blogspot.com/2007/10/junkfood-science-exclusive-big-one.html), the author considers the results of the Women’s Health Initiative (WHI) Dietary Modification Trial. This trial was a study of nearly 50,000 postmenopausal women; some ate a ‘healthy diet’ high in fruit, vegetables, fibre, and whole grains, and low in fat. The control group ate whatever they felt like. The women were on the study for eight years, and at the end they were tested for heart disease, weight, cancers, etc. Here’s what the study found;

Cardiovascular disease:

> “a dietary intervention that reduced total fat intake and increased intakes of vegetables, fruits, and grains did not significantly reduce the risk of CHD, stroke, or CVD in postmenopausal women.”

Breast cancer:

> “We found no evidence that lower intake of total fat or specific major types of fat was associated with a decreased risk of breast cancer.”

Colon and rectal cancer:

> “a low-fat dietary pattern intervention did not reduce the risk of colorectal cancer in postmenopausal women during 8.1 years of follow-up.”

Body Weight:

> The women following a “healthy” diet for eight years didn’t end up thinner. They lost a bit at the beginning, but had regained it back years before the end of the trial, despite continued restrained eating and eating fewer calories (361 kcal/day less than they had been at the start of the study). During the last years of the trial and at the end, the researchers found an insignificant difference in weight changes between the intervention and control group of a mere 0.7 kg. They concluded:

>> “A low-fat eating pattern does not result in weight gain in postmenopausal women.”

Which is pretty amazing. Women on eight years of a recommended healthy diet were just as likely to get heart disease, clogged arteries, strokes, or three kinds of cancer, and were no thinner than the women who ate whatever they fancied.

A similar [study of male veterans](http://junkfoodscience.blogspot.com/2009/06/paradoxes-compel-us-to-think.html) found similar things. They followed about 1,000 men who were healthy in 1987, and followed up in 2004. By then, 208 had died. The overweight men in the study had a 34% better survivability than normal [BMI](http://en.wikipedia.org/wiki/Body_mass_index), whereas obese men had a 44% better chance of being alive.

That’s a fairly hefty foundation stone in a lot of the advice we see on how to live healthily. That being overweight leads to all manner of diseases and problems is heard so often that it’s incredible that it isn’t really backed up by the literature. And if that isn’t credible, then all the smaller studies and claims, about foods being either Good or Bad (chocolate, red wine, antioxidants, dihydrogen monoxide, polyungiptomobes) are probably equally suspect.

It’s got me intrigued. Over the next little while, I’m going to try to find the real papers, the real studies, that have managed to show what really does, and does not, have a benefit.

So my first aim will be to find out what effect cardiovascular fitness has on heart disease. Does getting fit help you avoid heart disease?

Athlete’s Foot: the Vibram Fivefingers

As a kid, I always enjoyed going barefoot. I used to spend summer holidays walking around without shoes, and my feet used to toughen up over those six week breaks. But then when I went back to school and got back into smart shoes, my soles would soften up again and my barefoot pleasure was curtailed.

So when, on occasion, I’ve daydreamed about the perfect shoe, it hasn’t been about the latest Jimmy Choos, but something more like the Vibram Five Fingers, a shoe I’ve discovered on the web. What I’ve always wanted, but never seen before, is as minimal a pair of shoes as possible; something that’ll stop my feet being cut to ribbons, but let me feel like I’m not really wearing shoes.

So here’s the Five Fingers;

![Vibram Five Fingers](http://www.vibramfivefingers.com/products/images/products/116C//large.jpg)

What we’re looking at is a shoe which is basically enough tough rubber to save your feet from dogshit and broken glass on the streets, with just enough structure to strap it onto your feet.

So they’ve got a couple of interesting points; some in terms of health and fitness, and some social.

Healthwise, there’s evidence that training shoes might be pretty bad for your feet, and the fivefingers gets you back to something close to nature. There’s some folks who believe that [Homo Sapiens evolved to be joggers](http://www.fas.harvard.edu/~skeleton/pdfs/2004e.pdf); (Harvard Uni, pdf)

> However, although humans are comparatively poor sprinters,
they also engage in a different type of running, endurance running
(ER), defined as running many kilometres over extended time
periods using aerobic metabolism. Although not extensively studied
in non-humans, ER is unique to humans among primates, and
uncommon among quadrupedal mammals other than social carnivores
(such as dogs and hyenas) and migratory ungulates (such as
wildebeest and horses.

What’s interesting, from a health and fitness point of view, is that if humans are designed to jog, then the feet should be a bloody well-adapted instrument, and shoes might just be screwing with their optimal comfort. And in fact, a lot of joggers suffer foot and leg injuries. Some of that probably comes from hard asphalt, and some comes from poor footware.

From a social point of view, I have a restrained optimism. There are social situations that call for shoes; in fact, it’s pretty much unheard of to go without shoes. So in situations which require shoes, these may well serve well enough to get by; I’m wondering if I can away with them in the office.

Somewhere in between health and social norms is gym etiquette. My gym, at least, doesn’t allow people to wander around barefoot. So these might serve people who want to run barefoot on the treatmill or do kicking martial arts training on the heavy bag.

Now, [Wired](http://www.wired.com) described them as [“Ugly as a bucket of vomit”](http://www.wired.com/reviews/product/pr_vibram_fivefingers_kso) but they, like me, were intrigued and gave it a decent review. Personally, I really like the look.

I think I’m going to put this on my shopping list as my next toy.

Immutable objects in C#

Immutability is one of those programming subjects we hear about fairly regularly at the moment. It’s supposed to be one of those principles which make parallel programming easier, and since we’re currently in the world of 4-core machines, parallel is big right now.

Unfortunately it’s really hard in C# to create immutable objects. Or at least, C# isn’t really designed for it, so if you try to write an app using immutable data structures, you may find yourself writing a lot of boilerplate just to adhere to this particular paradigm. Which means at some point you’ll stop bothering, because it’s just too much work.

So, in the interests of reinventing the wheel, I’ve written a small code generator which creates immutable structs, which have ‘mutator’ functions. Mutators are methods which return whole new objects with just one property changed. For instance, if you have an immutable rectangle defined like this;

var firstRect = new Salamander.Models.Rectangle(100, 100, 100, 100);

then you can create a new object will all the same properties except one like this;

var secondRect = firstRect.WithTop(50);

Anyway, the system consists of two files; the generator itself [(Immutable.ttinc)](https://stevecooper.org/documents/Immutable.ttinc) and a file which defines the immutable types to create [(myImmutableTypes.tt)](https://stevecooper.org/documents/myImmutableTypes.tt). You’ll need to include them both in your c# project, then right-click the `.tt` file and choose ‘Run Custom Tool’

## To define your own custom types

You’ll need to look inside the `.tt` file and write a line which describes the type you’d like to create — basically just a namespace-qualified type name, and a list of fields;

GenerateImmutable(“Db.Person: string FirstName; string SecondName”, “A Person”);

The second parameter is a class-level xml comment

## Immutable.ttinc

<#+

private class Member
{
public string Type;
public string Name;
}

void GenerateImmutable(string definition)
{
GenerateImmutable(definition, string.Empty);
}

void GenerateImmutable(string definition, string comment)
{
var typeBuilder = new System.Text.StringBuilder();

int indexOfColon = definition.IndexOf(':');
if (indexOfColon == -1)
{
Error("No colon; expected, eg 'Rectangle: ‘”);
}

string ns = “”;
string typeName = definition.Split(‘:’)[0];
string members = definition.Split(‘:’)[1];

//
// NAMESPACE
//
int lastNsDot = typeName.LastIndexOf(“.”);
if (lastNsDot != -1)
{
ns = typeName.Substring(0, lastNsDot);
typeName = typeName.Substring(lastNsDot+1);
}

if (String.IsNullOrEmpty(ns) == false)
{
typeBuilder.Append(“namespace “).AppendLine(ns).AppendLine(“{“);
}

//
// TYPE DEFINITION
//
typeBuilder.Append(” ///

“).Append(comment).AppendLine(“

“);
typeBuilder.Append(” public partial struct “).AppendLine(typeName).AppendLine(” {“);
var memberList = members
.Split(‘;’)
.Select(x => x.Trim())
.Where(x => x.Length > 0)
.Select(x => x.Split(‘ ‘))
.Select(arr => new Member { Type = arr[0], Name=arr[1] })
;

//
// CONSTRUCTOR
//
typeBuilder.Append(” ///

Create a new “).Append(typeName).Append(“

“).AppendLine();
typeBuilder.Append(” public “).Append(typeName).Append(“(“);
foreach(var memberItem in memberList)
{
typeBuilder.Append(memberItem.Type).Append(” “).Append(memberItem.Name).Append(“,”);
}
typeBuilder.Length = typeBuilder.Length-1; // remove trailing comma
typeBuilder.AppendLine(“)”);
typeBuilder.AppendLine(” {“);
foreach(var memberItem in memberList)
{
typeBuilder
.Append(” this.”)
.Append(memberItem.Name)
.Append(” = “)
.Append(memberItem.Name)
.Append(“;”)
.AppendLine();
}

typeBuilder.AppendLine(” }”);

//
// fields
//
typeBuilder.AppendLine(” // fields”);
foreach(var memberItem in memberList)
{
typeBuilder
.AppendFormat(” public readonly {0} {1};”, memberItem.Type, memberItem.Name)
.AppendLine();
}
typeBuilder.AppendLine();

foreach(var memberItem in memberList)
{
typeBuilder
.AppendLine(” ///

mutator for ” + memberItem.Name + ” property

“)
.AppendFormat(” public {0} With{1}({2} new{1})”, typeName, memberItem.Name, memberItem.Type)
.AppendLine(” {“)
.AppendFormat(” var newItem = new {0}(“, typeName)
;

foreach(var memberItemParam in memberList)
{
if (memberItem.Name == memberItemParam.Name)
{
typeBuilder.Append(“new”).Append(memberItem.Name).Append(“,”);
}
else
{
typeBuilder.Append(“this.”).Append(memberItemParam.Name).Append(“,”);
}
}
typeBuilder.Length = typeBuilder.Length-1; // remove trailing comma
typeBuilder.AppendLine(“);”);
typeBuilder.AppendLine(” return newItem;”);
typeBuilder.AppendLine(” }”);
typeBuilder.AppendLine();
}

typeBuilder.AppendLine(” }”);

if (String.IsNullOrEmpty(ns) == false)
{
typeBuilder.AppendLine(“}”);
}

Write(typeBuilder.ToString());

}

#>

## myImmutableTypes.tt

Make a cafe au lait in the office

I’ve just gone to the nearby coffee bar for a lunchtime latte, and I was bitterly disappointed. Filth! So I won’t be buying latte there any more.

Instead, I’ll be making cafe au lait in the office. Cafe au lait isn’t just white coffee; it’s a 50-50 mix of hot milk and double-strength coffee, and bears a remarkable resemblance to a caffe latte, just without the foam cap. It’s much richer and more luxurious than a white coffee.

If if you have fresh coffee and fresh milk, you can make a very passable cafe au lait in minutes. Here’s the skinny.

##Equipment:

– a cafetiere.
– a microwave.
– a large mug or microwave-safe jug, to heat the milk.
– a smaller mug, to serve.

##Ingredients:

– milk.
– coffee ground for cafetiere.

##Method:

The steps are; start the coffee brewing, heat the milk, plunge the coffee, then mix.

_Start the coffee brewing:_ To make the coffee, boil a kettle of water and either let it cool for a minute, or put some cold water. Boiling water can scald the coffee. I know this sounds precious, but it makes a difference; you won’t taste as much bitterness in the coffee, and you should notice more of the flavours.

Now you’re going to make double-strength coffee. I use two heaped desert spoons in a cafetiere that will make three cups (two mugs) of coffee, but then I half-fill the cafetiere. Give it about three minutes to brew. During those three minutes, we’ll heat the milk.

_Heat the milk:_ Take your large mug and half-fill it with milk. Nuke it for about a minute and a half.

_Plunge and mix:_ When that’s done, your coffee should be about ready. Plunge the cafetiere, then mix the milk and coffee about 50-50. You will end up with something that looks like white coffee, with some wisps of white almost-foam floating on the surface. You’re done!

Drink in small amounts; it’s a rich drink and you don’t need huge quantities. Save yourself from bad industrial estate caffe latte!

Python-style string formatting for C#

[Jon Skeet][skeet] recently asked in one of [his posts][op]:

> it would be really nice to be able to write:
>
> `throw new IOException(“Expected to read {0} bytes but only {1} were available”, requiredSize, bytesRead);`

Which would do the same as

throw new IOException(String.Format(
“Expected to read {0} bytes but only {1} were available”,
requiredSize, bytesRead));

And it got me wondering about the String.Format method, and how much uglier it makes C# code to read than, say, the equivalent python code. Alongside each other;

// C#
string message = String.Format(
“Expected to read {0} bytes but only {1} were available”,
requiredSize, bytesRead);

// python
message = “Expected to read %s bytes but only %s were available” % (requiredSize, bytesRead)

I think I’d solve the problem, not by creating a new constructor for `IOException`, but by making String.Format part of the C# syntax. It works very nicely for python, and it’s such a common thing to do that I tink it would warrant a change to the language. Given how cumbersome String.Format is, it’s often shorter and clearer to use simple string concatenation. This makes things rather inconsistent.

Here’s what I came up with. It’s a ‘first draft’, and more for interest’s sake than as something I’d put into production.

Instead of passing an object array in as the values, I’m reading from the properties of an object. So you can do it with objects or tuples;

var person = new Person()
{
firstname=”Steve”,
secondname=”Cooper”
};

Then you can inject the tuple into a format string like this;

string message = “{firstname} {surname} says injecting properties is fun!”.ㄍ(person)
// message == “Steve Cooper says injecting properties is fun!”

So you’ll see this weird thing on the end of the format string that looks like a double-chevron. This is supposed to look like a double arrow, pushing values into the format string. In fact, it’s the [Bopomopho letter ‘G’][g] and therefore a perfectly normal C# method name.

Here’s the code for the double-chevron method. I say again, this is _just a proof of concept_, not production code. Use at your own peril. (In fact, don’t use. Write your own. It’ll be more solid.)

public static class StringFormatting
{
public static string ㄍ(this string format, object o)
{
var rx = new System.Text.RegularExpressions.Regex(@”{(?w+)}”);
var match = rx.Match(format);
while (match.Success)
{
string name = match.Groups[“name”].Value;
format = format
.Replace(“{“, “{{“)
.Replace(“}”, “}}”)
;
format = format.Replace(“{{” + name + “}}”, “{0}”);

object prop = o.GetType().GetProperty(name).GetValue(o, null);
format = string.Format(format, prop);
match = rx.Match(format);

}
return format;
}
}

[skeet]: http://msmvps.com/blogs/jon_skeet/default.aspx
[op]: http://msmvps.com/blogs/jon_skeet/archive/2009/01/23/quick-rant-why-isn-t-there-an-exception-string-params-object-constructor.aspx
[g]: http://www.alanwood.net/unicode/bopomofo.html

SonicFileFinder for Visual Studio

For those of you who use Visual Studio all day, can I suggest that you install [SonicFileFinder][sff]?

[sff]: http://jens-schaller.de/blog/2008/12/15/295.htm

This lovely little addin by Jens Schaller gives you a way to find files in your current solution with a few keypresses. Invoke it, and you see a dialogue like this;

Sonic File Finder

Type in a fragment of a filename, and you’ll get a filtered list of files matching that fragment. Choose a file, hit ‘return’, and the file opens in the code editor.

Basically, if you know the name of your file, you no longer need to use the Solution Explorer. As codebases get bigger and bigger, this addin gets more valuable as the Solution Explorer gets worse.

Highly recommended, plus it now works with F#, C#, and VB.NET projects.