Posted in Uncategorized | Leave a comment

“Until” extension method for integers in C#

I wrote this simple snippet today, and thought I’d share:

public static IEnumerable<int> Until(this int from, int to)
    for (int i = from; i <= to; i++)
        yield return i;

Its purpose is to return number ranges:

IEnumerable<int> firstTen = 1.Until(10);
foreach (int i in firstTen)
    Console.Write(i + " ");

Which outputs the following:

1 2 3 4 5 6 7 8 9 10
Posted in C# | Tagged , | Leave a comment

Haversine Distance Formula

I’m working on an analysis tool for GPS data in C# which needs to calculate the distance between two geographic coordinates, and I chose the Haversine formula (explanation).  So I figured I’d share my implementation:

        public class Point
            public double Latitude { get; private set; }
            public double Longitude{ get; private set; }

            public Point(double latitude, double longitude)
                Latitude = latitude;
                Longitude = longitude;

        public static double ToRadian(double angle)
            return Math.PI * angle / 180.0;

        public static double HaversineDistance(Point a, Point b)
            const double radius = 3956.6 * 5280; // in feet
            double latitude = ToRadian(b.Latitude - a.Latitude) / 2;
            double longitude = ToRadian(b.Longitude - a.Longitude) / 2;

            double x = Math.Sin(latitude) * Math.Sin(latitude) + Math.Sin(longitude) * Math.Sin(longitude) *
                                                                 Math.Cos(ToRadian(a.Latitude)) * Math.Cos(ToRadian(b.Latitude));
            double y = 2 * Math.Atan2(Math.Sqrt(x), Math.Sqrt(1 - x));

            return radius * y;

To change the units (these are in feet), change the radius (source: Wolfram Alpha).

Posted in C#, Math | Tagged , | Leave a comment

Modifying the Protocol Buffers compiler to support ScalaDoc

I’ve been building a server for a chess game in Scala, and chose protobuf as the serialization format.  When I hooked up ScalaDoc, I hit all sorts of errors, such as:

Contracts.java:2125: error: not found: type BuilderParent
      private Builder(BuilderParent parent) {

The limitation is in resolving class references.  While this is most likely a problem with ScalaDoc, it was easier to fix in the protobuf compiler.  My solution was to simply supply the fully qualified name for classes like BuilderParent in the Java portion of protoc. I’ve created a patch to protoc (based on 2.4.1) that represents these changes:


I’ll also supply the protoc Windows binary:


Using this to generate Java protobuf code will allow you to create ScalaDocs off of Scala code that consumes your contracts.

Posted in Java, Protocol Buffers, Scala | Leave a comment

Jack-o’-Lantern & Arduino

After a few glasses of wine, we decided to do some pumpkin carving:

I chose a cat; she chose the ghost:

and the finished product:

Then I had the bright idea to put some LEDs into it. Add a little creativity, and the dust that’s been collecting on my Arduino was dusted off.

Here’s the complete set of LEDs and their corresponding wires. We made 4 red and 4 yellow (two per pumpkin):

…then we wired up the pumpkins, labeled the colors and the ground/hot:

Thanks to my old iPhone charger (RIP Steve Jobs), we got power over USB from my living room extension cord:

…and they turned out beautiful:

Here’s a video (please excuse the sound):

Quote of the night: “I should have known pumpkin carving with you would have ended up like this.”

More videos to come!

Posted in Arduino | Leave a comment

Determine which process is locking the clipboard

I was having a peculiar error where some process occasionally appeared to be using the clipboard when my application went to handle copy & paste operations. There are some retry work arounds, and I had an acceptable solution in place, but I wanted to locate which process it was if the error keeps occurring.

After some research and a little coding, I’ve wrapped my solution into an easy-to-use method (plus some declarations):

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetOpenClipboardWindow();

[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

private static Process GetProcessLockingClipboard()
    int processId;
    GetWindowThreadProcessId(GetOpenClipboardWindow(), out processId);

    return Process.GetProcessById(processId);


Posted in C# | Tagged | Leave a comment

WordPress: Diagnosing “Error establishing a database connection”

I recently experienced the ever-so-helpful “Error establishing a database connection” message from my WordPress installation.  After about 30 minutes looking through Google results and watching some terribly useless YouTube videos, the best explanation I found was: there must be a problem with your wp-config.php file. I knew I hadn’t changed it, and none of the software was new, so I was the 1% case where that didn’t apply. So I thought, man, I know the LAMP stack pretty well, there’s no reason I can’t just cut through this and find the real error. I did, and so I’m going to share my method.

Turns out there are three places in the code that produce an “Error establishing database connection” message.  If you’re receiving only that text, then we don’t care about two of them.  The remaining place that generates this error is in the dead_db() function in /wp-includes/functions.php.  You’ll notice the following code:

// If installing or in the admin, provide the verbose message.
if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )


For security reasons, the actual MySQL error will only be displayed if you’re either (1) currently installing, or (2) an admin. If you aren’t logged in (like I wasn’t), then you definitely won’t see it. All I did was comment out the if-statement, and poof, the error was displayed, so I saw something along these lines:

One or more database tables are unavailable. The database may need to be repaired.

Easy enough. So I went into phpMyAdmin, repaired my options table, and my blog was back online. Hope that’s more helpful than the rest of the discussions on the web about this error.

Posted in PHP, SQL, WordPress | Leave a comment

SQL query to find duplicate rows, in any table

I recently needed a SQL query that could find duplicate rows in any table, without specifying each column.  With some help from Tom H., I have a solution.  And with some modifications, a foray into dynamic SQL and a stored procedure, I now use this little beauty:

	@TableName NVARCHAR(64)

	SET @Query = '

			CHECKSUM(*) AS chksum,
			' + @TableName + '
		CTE T1, CTE T2
		T2.chksum = T1.chksum AND
		T2.rownum <> T1.rownum'

	EXEC sp_executesql @Query

So this is doing a few things.  At the highest level, it’s a stored procedure, which we could execute like this:

EXEC [dbo].[GetDuplicates] @TableName = N'Users'

This is passing Users as the name of the table in which we wish to find duplicates.  The actual stored procedure uses a very simple example of dynamic SQL (for more information on the pros and cons of dynamic SQL, read this).  By writing the actual query we want to use in an NVARCHAR variable, it becomes possible to replace the table in the FROM clause to the value passed into the stored procedure. We then pass the variable containing the query to the sp_executesql system stored procedure, which is kind of like eval() in PHP.

Now, on to what the query is actually supposed to do.  A common table expression is a named result set whose lifetime exists for the duration of a single subsequent SELECT, INSERT, UPDATE or DELETE statement.  The query that populates this result set (named CTE) is

	CHECKSUM(*) AS chksum,

The CHECKSUM function is a hash function that takes columns as arguments, which is used to uniquely identify the values of all the fields in a row; this includes derived columns.  The call to ROW_NUMBER() is used to uniquely identify each row, despite the values in its fields. The point being, if two rows have the same checksum value, but (obviously) different row numbers, then they are duplicates. So with that in mind, we do an implicit inner left join:

	T2.chksum = T1.chksum AND
	T2.rownum <> T1.rownum

Remember, we wanted the same checksum, but different row numbers. T1 and T2 are aliases for the same temporary result set we populated earlier, and the DISTINCT T1.* eliminates extra columns and rows. The final result will each duplicate row. It might look something like this:

Username Password Birthday chksum rownum
foo bar 1999-12-31 00:00:00.000 -1327027712 1
foo bar 1999-12-31 00:00:00.000 -1327027712 7
foo bar 1999-12-31 00:00:00.000 -1327027712 8
foo bar 1999-12-31 00:00:00.000 -1327027712 9
foo bar 1999-12-31 00:00:00.000 -1327027712 10
hillary ilikepie 1999-12-31 00:00:00.000 956702162 4
hillary ilikepie 1999-12-31 00:00:00.000 956702162 5
hillary ilikepie 1999-12-31 00:00:00.000 956702162 6
jim pass1 1999-12-31 00:00:00.000 2026298685 2
jim pass1 1999-12-31 00:00:00.000 2026298685 3

So if you want to know how many duplicate rows there are, there’s one row in the result for each. Sorry, I got lazy and everybody in this example is eleven years old.

Posted in SQL | Tagged , , , | Leave a comment

Karl Sims: Evolving 3D Body Morphology

One of my favorite research topics is artificial life.  Although this paper is not recent, Karl Sims published Evolving virtual creatures at SIGGRAPH ’94 and I still enjoy watching the video of these body shapes:

I don’t think it’s technically legal for me to post parts of the paper here without permission, so I hope you have a subscription to ACM. Anyways, he uses some relatively basic directed graphs to model the creature’s body. Each node is represented by a rectangular prism, and edges are the physical connections between them. The mutations can occur by altering the internal properties of a node, adding/removing a node in the graph, altering the properties of connections between nodes and adding/removing connections between nodes. The vestigial components–unconnected nodes–are discarded.  The resulting graph is the creature’s genotype.

Mating also occurs between the creatures, where the graphs are combined by simulating the biological concepts of crossover and grafting.  When represented in a virtual environment, the graphs become “physical” creatures, the body phenotype.  Further, the control of these mechanics are determined by artificial neural networks, also fueled by the evolutionary process, the brain phenotypes. Sims uses basic fitness functions to choose for species that can swim quickly or grab an object.  The result, though over sixteen years old, is a very cool adaptive process to both “aquatic” and “terrestrial” environments.

Posted in Artificial Intelligence, Evolutionary Computation | Tagged , , , , , | Leave a comment

Multi-Dimensional Analog Literals

I have a weakness for programming tomfoolery.  Something I just came across made me smile, so I thought I’d share it.  They’re called multi-dimensional analog literals, and they’re the work of some clever C++ templates.  Basically, it allows you to “draw” shapes in text, in C++, and have it compute length, area and volume.  Check this out:

// Note: The following is all standard-conforming C++, this is not a hypothetical language extension.

#include "analogliterals.hpp"
#include <cassert>

int main ()
  using namespace analog_literals::symbols;
// Consider:

  unsigned int a = 4;
// Have you ever felt that integer literals like "4" don't convey the true size of the value they denote? If so, use an analog integer literal instead:

  unsigned int b = I---------I;

  assert( a == b );
// Due to the way C++ operators work, we must use N*2+1 dashes between the I's to get a value of N:

  assert( I-I == 0 );
  assert( I---I == 1 );
  assert( I-----I == 2 );
  assert( I-------I == 3 );
// These one-dimensional analog literals are of type analog_literals::line<N>, which is convertible to unsigned int.

// In some cases, two-dimensional analog literals are appropriate:

  unsigned int c = ( o-----o
                     |     !
                     !     !
                     !     !
                     o-----o ).area;

  assert( c == (I-----I) * (I-------I) );

  assert( ( o-----o
            |     !
            !     !
            !     !
            !     !
            o-----o ).area == ( o---------o
                                |         !
                                !         !
                                o---------o ).area );
// Two-dimensional analog literals are of type analog_literals::rectangle<X, Y> which exposes static member constants width, height, and area.

/* As an example use-case, imagine specifying window dimensions in a GUI toolkit API using:

   window.dimensions = o-----------o
                       |           !
                       !           !
                       !           !
                       !           !
                       o-----------o ;
Who said C++ was unintuitive!? */

// But wait, there's more. We can use three-dimensional analog literals, too:

  assert( ( o-------------o
            |L             \
            | L             \
            |  L             \
            |   o-------------o
            |   !             !
            !   !             !
            o   |             !
             L  |             !
              L |             !
               L|             !
                o-------------o ).volume == ( o-------------o
                                              |             !
                                              !             !
                                              !             !
                                              o-------------o ).area * int(I-------------I) );
// Three-dimensional analog literals are of type analog_literals::cuboid<X, Y, Z> which exposes static member constants width, height, depth, and volume. In addition, three free-standing functions top, side, and front are provided which yield rectangles:

  assert( top( o-------o
               |L       \
               | L       \
               |  o-------o
               |  !       !
               !  !       !
               o  |       !
                L |       !
                 L|       !
                  o-------o ) == ( o-------o
                                   |       !
                                   !       !
                                   o-------o ) );
// The current implementation has one restriction on cuboid dimensions: the height of a cuboid literal must be at least its depth + 2.

// Note that storing these literals directly in a variable requires you to specify the dimension sizes:

  analog_literals::rectangle<4, 2> r = o---------o
                                       |         !
                                       !         !
// This of course defeats the purpose of using the analog literal. C++0x's proposed `auto' feature would come in quite handy here. We can actually fix this problem partially (using the stack-ref-to-temporary's-base trick used by Alexandrescu's ScopeGuard), but we would no longer be able to use the values in ICE's, and frankly I think this madness has gone far enough already.


You can find the rest of the code on the page I linked above.

Update: There’s now a Scala version of this that can be found here.

Posted in C++ | Leave a comment