Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Color Brewer – colour schemes for data visualisations December 1, 2009

Filed under: Uncategorized — Rupert Bates @ 9:44 pm

Found this nice online tool to generate colour schemes for data visualisations

http://colorbrewer2.org/

 

Euclidean Distance and Similarity in C# October 22, 2009

Filed under: Uncategorized — Rupert Bates @ 4:46 pm

Here are a couple of functions to calculate Euclidean distance between 2 points and similarity based on that distance. These are useful in the sort of algorithms described in the excellent book Programming Collective Intelligence

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Algorithms
{
 public class Distance
 {
 /// <summary>
 /// Return the distance between 2 points
 /// </summary>
 public static double Euclidean(Point p1, Point p2)
 {
 return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
 }

 /// <summary>
 /// Calculates the similarity between 2 points using Euclidean distance.
 /// Returns a value between 0 and 1 where 1 means they are identical
 /// </summary>
 public static double EuclideanSimilarity(Point p1, Point p2)
 {
 return 1/(1 + Euclidean(p1, p2));
 }
 }
}

And some tests:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Algorithms.Test
{
 [TestClass]
 public class TestDistance
 {
 [TestMethod]
 public void Test_Euclidean()
 {
 var p1 = new Point(5, 4);
 var p2 = new Point(4, 1);

 Assert.AreEqual(3.1622776601683795, Distance.Euclidean(p1, p2));

 }
 [TestMethod]
 public void Test_EuclideanSimilarity()
 {
 var p1 = new Point(5, 4);
 var p2 = new Point(4, 1);

 Assert.AreEqual(0.2402530733520421, Distance.EuclideanSimilarity(p1, p2));

 }
 }
}
 

Open your hosts file in notepad from Powershell September 29, 2009

Filed under: Uncategorized — Rupert Bates @ 12:36 pm
Tags:

notepad (gci -Include hosts -Path c:\windows\system32 -Recurse)

 

When two problems appear at the same time no matter how seemingly unrelated, they probably are September 18, 2009

Filed under: Uncategorized — Rupert Bates @ 10:02 am

I’ve seen two examples of this in the last few days.

Firstly we have an Asp.Net website which has recently moved to a new datacentre and seemed to be working well, but then the other day it fell over big time and the event log started filling up with errors about deadlocks in the aspnet_isapi.dll and faults in the W3SVC service. We googled away and just came up with some thing about thread contention and upping the maxWorkerThreads parameter in the machine.config which I didn’t want to do without understanding why this had suddenly become and issue.

At the same time somebody noticed that printing no longer worked in non Internet Explorer browsers, but we ignored that to focus on the more serious stability issue. It was only when I gave up on the first error and looked into the printing bug that I worked out what was going on. The printing page for Non IE browsers tried to make an http request to another page on the site to load the image it was trying to print. Stricter firewall rules in our new datacentre meant that this http request was being blocked meaning that the thread that was trying to make this request was also blocked until the request timed out, and this was what caused both the printing problem and the threading deadlock.

The second example of this maxim is a bit less high tech; my washing machine started leaking water through the door and we noticed the seal was a bit torn. At the same time it kept stopping with an error message (yup, even washing machines have them now) about the filter being blocked (which it wasn’t). It turns out that the loss of pressure from the leaking water affected its ability to pump out water, so it thought that the filter was blocked (that may not be 100% accurate, but when it comes to washing machines I’m not technical).

 

Display C# code in a WordPress Blog September 16, 2009

Filed under: Uncategorized — Rupert Bates @ 4:24 pm

A cool way to get WordPress to format and sytax highlight your C# code:

[sourcecode language=’csharp’]
string MyCode = “My Code”;
[/sourcecode]

Which appears in the post as:

string MyCode = "My Code";
 

Auto Initialize a Dictionary in C# September 16, 2009

Filed under: Uncategorized — Rupert Bates @ 4:05 pm

I couldn’t find an example of using the new auto initialization syntax in C# 3.0 with a Dictionary so here is one:

var dict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } };
 

An Implementation of Fold for C# August 20, 2009

Filed under: C#, Coding, Functional programming, Uncategorized — Rupert Bates @ 9:22 am

I expect there are a number of implementations of this around, but I couldn’t find one so I wrote this. It is an extension method which implements Fold on IEnumerable


public static class Extensions
{
  public delegate TDestination FoldOperation<TSource, TDestination>(TSource item, TDestination acc);
  public static TDestination Fold<TSource, TDestination>(this IEnumerable<TSource> list, FoldOperation<TSource, TDestination> foldOperation, TDestination acc)
  {
     foreach(TSource item in list)
     {
       acc = foldOperation(item, acc);
     }
     return acc;
  }
 }

I can then use this Fold function for something like this which takes an object with a number of properties and creates a querystring with the name/value pairs of all of those properties which are non-null:

public class UrlConstructor
{
  //Takes a RequestParameter object with a number of properties which
  //if their value is set should be translated into querystring parameters
  public static string ConstructUrl(RequestParameters rp)
  {
    //Get all the properties where the value is not null
    var values = typeof(RequestParameters).GetProperties().Where(p => (p.GetValue(rp, null) != null));

    //Fold these values up into a string
    var querystring = values.Fold(((p, acc) => acc + p.Name + "=" + p.GetValue(rp, null) + "&"), "").TrimEnd('&');

    return "http://mybaseurl.com/default.aspx?" + querystring;
  }
}
 

Find and run aspnet_regsql.exe with powershell August 18, 2009

Filed under: Uncategorized — Rupert Bates @ 4:47 pm

gci -Recurse -Path c:\windows\ -Include aspnet_regsql.exe | Invoke-Item

 

Enumeration model binder for asp.net mvc August 8, 2009

Filed under: C#, MVC, Uncategorized — Rupert Bates @ 9:06 pm

We were recently working on an asp.net MVC app and I noticed that in a lot of places actions were taking strings as parameters and then converting them to enum values with the action. The reason for doing this rather than just typing the parameter as the enum type was because they were optional and so when the value didn’t exist an error was thrown:

screenshot of error page

screenshot of error page

Because enums are not nullable types they can’t be used as optional parameters.

What was needed then was a way to provide a default parameter for when the parameter didn’t exist in the url. To do this I wrote a custom model binder and it solved the problem pretty well.

Here is the code for the binder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EnumTest.Helpers
{
public class EnumBinder<T> : IModelBinder
{
private T DefaultValue { get; set; }
public EnumBinder(T defaultValue)
{
DefaultValue = defaultValue;
}

#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return bindingContext.ValueProvider[bindingContext.ModelName] == null
? DefaultValue
: GetEnumValue(DefaultValue, bindingContext.ValueProvider[bindingContext.ModelName].AttemptedValue);
}

#endregion

public static T GetEnumValue<T>(T defaultValue, string value)
{
T enumType = defaultValue;

if ((!String.IsNullOrEmpty(value)) && (Contains(typeof(T), value)))
enumType = (T)Enum.Parse(typeof(T), value, true);

return enumType;
}
public static bool Contains(Type enumType, string value)
{
return Enum.GetNames(enumType).Contains(value, StringComparer.OrdinalIgnoreCase);
}
}
}

And to use it in your project you just register it in your Global.asax, specifying the type of your enum and the default value you want when there is no value available in the input.

protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.Add(typeof(TestEnum), new EnumBinder<TestEnum>(TestEnum.rupert));
        }
 

Albums everyone should hear before they die July 18, 2009

Filed under: Uncategorized — Rupert Bates @ 7:46 am

‘In the aeroplane over the sea’ by Neutral Milk Hotel