What's Boost?

With so many languages, libraries, tools, frameworks, and Internet fads to keep up with, sometimes you let a few slip through the cracks.  This post is intended as an ultra quick primer (one of many) for anyone who let the Boost C++ libraries slip through the cracks.  If you have used Boost before, this post is not for you.

 

Below is an edited version of an email conversation that I just had with one of my coworkers:

 

Me:

From the Wikipedia article:

 

The Boost C++ Libraries are a collection of peer-reviewed, open source libraries that extend the functionality of C++. Most of the libraries are licensed under the Boost Software License, designed to allow Boost to be used with both open and closed source projects. Many of Boost's founders are on the C++ standard committee and several Boost libraries have been accepted for incorporation into the Technical Report 1 of C++0x.[1]

The libraries are aimed at a wide range of C++ users and application domains. They range from general-purpose libraries like the smart_ptr library, to OS abstractions like FileSystem, to libraries primarily aimed at other library developers and advanced C++ users, like the MPL.

In order to ensure efficiency and flexibility, Boost makes extensive use of templates. Boost has been a source of extensive work and research into generic programming and metaprogramming in C++.

 

The Wikipedia article does a pretty good job of explaining what boost is, but here's a little more information.  In non technical terms, Boost "contains a bunch of sneaky cool libraries that let you do some pretty sweet things in C++".  The libraries can be a little daunting to look at when you first start, but those that I've messed with are pretty useful (and really cool under the hood).  For those that have not messed around with boost but despise C++, part of the reason that I like C++ so much is because ideas and tools from boost as well as those found in the depths of the STL/TR1 (as well as other best practices) have made the language a lot easier and safer to use while also enabling you to do some really powerful things with the language.

 

Coworker:

Okay, so what's the difference was between Boost and other Open Source Projects like Apache, which also has a lot of nice C++ libraries and has a license that allows you to both use the code in open and closed source projects?


Is there a different Metaphor here than simply:  "It's an open source foundation for C++"?

 

Me:

That's essentially the metaphor, but I would change it to read:

"It's THE open source foundation for C++"


Boost has implemented a lot of libraries that have gotten rolled back into the STL, so in a lot of ways, it's like getting a new version of the C++ STL before it gets released except that you actually get a lot more libraries than will ever make it into the real STL.  You also get a lot of things that really should have been in the STL, but were omitted for one reason or another (hash tables, for example).  With the benefit of getting things that don't have to go through all the red tape of the standards committee, you also have the downside of having libraries that are not universally a part of a standard C++ implementation of the STL which may or may not be a concern for you depending on your project's requirements.


Anyway, boost is awesome if you're a C++ dev (and you should already know about it if you are one).  My only gripe has been that I have found their documentation to be a bit painful at times which can be a hassle since their libraries can be tricky to use the first time unless you have some good example code.

Posted by cmarinos | with no comments

Vacation Fun: Deciding on a Media Center Solution (part 1)

For a year or so now, I have been thinking about setting up some sort of media center for my home theater.  After looking at a few different options, I decided to try setting up my Xbox 360 as my media center hub while I was on vacation the past few days.  Read on to see how everything worked out.

 

Goals

My ideal solution to my media center "problem" had to solve these problems:


1) Ripping of all of my DVDs to my desktop PC (without compression).

2) Streaming of these ripped DVDs as well as my music from my desktop for playback on my home theater.

3) Playback of all media quickly and without a drop in quality (5.1 sound for audio, no quality loss from compression for video, etc.)

4) Cost effectiveness (read: free)

5) Not interfering with my day to day computer usage.  I run Ubuntu Linux as my primary OS at home, so any programs for my PC would have to run in Linux.

6) Playback of High Definition content. (optional)

 

Step 1 - DVD Ripping

I played around with a few different methods of DVD ripping before finally settling on DVD Shrink.  My goal was to be able to rip DVDs from my Linux desktop, but I ran into a few problems, so I gave up and took the easy way out.  Unfortunately, the "easy way out" was to install a virtual machine running Vista, install DVD Shrink, rip the DVD and send it back to a shared drive on my host machine (this process was a blog post in itself).

I set everything up so that the result was a single .vob file for each item on the DVD (eg. main movie, special features).  So far so good.  High quality DVD rips- check.

 

Step 2 - Setup the Media Server

Once I got a movie stored on my server machine, it was time to setup a server to enable streaming to my 360.  There were a few Windows-based ways to do this (it looks like Tversity was the favorite), but I definitely wanted to do this in Linux since running a windows VM all the time is too resource intensive.  I tried out a couple programs to do this.  First up was uShare.

uShare is a UPnP server that is light on features, but light on setup.  It was fairly painless to setup (it installs right from the Ubuntu repositories), but I immediately ran into some problems.  First, the 360 does not support a lot of video formats, and somewhat surprisingly, .vob files with  MPEG-2 were not supported.  Furthermore, uShare did not read the tags for audio files or specify the type of any file, so my media was a MESS when viewed from my 360.  My images would show up under both the "video" and "music" sections, and some movies would only show up under "music".  Lastly, since my .vob files were not playable by the 360, I needed something that could transcode them as they were streaming (I don't want to have to transcode every single DVD that I rip).  Clearly uShare was not the right choice.

 

Step 2.1 - Setup the Media Server with Transcoding on the Fly and Improved Categorizing Features

There were a few Linux compatible UPnP server programs that I researched to accomplish this.

First up was MediaTomb.  Although it did not support the 360 due to the 360's funky Windows Media Center-crippled UPnP support, it was a breeze to setup.  Although the UI was pretty clunky it seemed like a decent program for anyone with a compatible UPnP player (like a PS3).

Next was TwonkyMedia.  I didn't evaluate this program because it costs money to use beyond a 30 day trial, and the trial wouldn't install properly on my machine.  This is too bad, since I did read good things about it.

 

Finally I decided to try Fuppes.  Although, I had to compile it from source, Fuppes had the honor of being one of the very few open source projects that actually built and installed without any errors or hiccups whatsoever.  Very big kudos, and a nice way to start off.  Configuration for Fuppes was straightforward (I followed this guide) except for one minor problem.  It turns out that you really do have to specify the port number and network interface in the "network" section of the config file or the 360 won't find your Fuppes server.  Aside from that, things worked pretty well once I got everything configured.  Music was sorted by artist and album (once I built with taglib installed), and everything seemed to be organized much better.  I could stream my .mp3s without a hitch, and my xvid encoded .avi files played great as well.  Unfortunately, I still had some tinkering to do with my mpeg-2 encoded .vob files...

I tried out a few different codecs for transcoding my .vob files on the fly, but I was consistently rewarded with "unsupported format" errors from my 360.  Finally, I realized that my 360 would ONLY play xvid encoded .avis with a mime type of video/x-ms-wmv.  Fun.  Unfortunately, Fuppes only supported on the fly transcoding using ffmpeg which did not seem to support encoding to xvid.  Crap.  Scratch one night of tinkering until dawn.

As a last ditch effort, I tried hacking on the Fuppes source to get it to use mencoder to do the transcoding to xvid instead of ffmpeg.  Surprisingly, my hack actually worked on the first second compile.  What didn't work was the 360 playing the file as it was transcoding.  As soon as I stopped mencoder from transcoding the file, it would play the partially converted file, but it simply refused to play the thing when mencoder was still working it's magic.  Scratch one weekend of tinkering.

 

Conclusion - Temporary Defeat

Although I learned way more than I though I would need to about video encoding, and the 360's UPnP support, I did not accomplish my goal.  I could just transcode my MPEG-2 ripped .vob files into xvid .avi files, but the encoding process is time intensive, and the 360s interface and UPnP support leave something to be desired for a media center.  The 360 just does not seem like a great solution for my media center needs at this time.  Next up, it looks like I will probably be taking a look at installing XBMC on an original Xbox.  We'll see how that goes soon!

Posted by cmarinos | with no comments
Filed under: ,

Spice Up Your C# Code With Currying

Just because C# doesn't have language support for currying, doesn't mean you can't spice up your code by implementing currying methods yourself.  Even better news is that, it's very easy to do.  Let's look at the following code, to see how it's done:

public static Func<T2, TR> Bind1<T1, T2, TR>(Func<T1, T2, TR> function, T1 param1)
{
   return delegate(T2 param2) { return function(param1, param2); };
} 

As you can see, this simple method returns a delegate accepting one parameter corresponding to the second argument of the input function.  This means that the returned delegate acts the same way as the input function, except that the first argument is now bound to the input parameter.  We've just curried the method.

 

Let's see an example of how this might be useful:

private static string CreateMessage(string a, string b)
{
   return string.Format("Let's write a message.... {0} + {1}", a, b);
} 
static void Main(string[] args)
{
   Func<string, string, string> tmp = CreateMessage;
   var CurriedCreate = Bind1(tmp, "Some crazy string value");

   Console.WriteLine(CurriedCreate("Another insane string!"));
   Console.WriteLine(CurriedCreate("and another"));
   Console.WriteLine(CurriedCreate("yet another"));
} 

The output:

Let's write a message.... Some crazy string value + Another insane string!

Let's write a message.... Some crazy string value + and another

Let's write a message.... Some crazy string value + yet another

Pretty cool.  Now, there is a little bit of work to do because you have to write a new bind function for each number of arguments that you want to support.  I supported up to 4 arguments, since that meshes with the definition of Func.  You also will probably want to write out Bind1, Bind2, Bind3, and Bind4 methods, so that you aren't limited to always binding to the first argument.  That's a lot of "duplicated" code for the definitions, but C# doesn't have a way to specify variable-arity (think params[]) for generic parameters, so you're stuck writing everything out.

 

Another interesting thing to note is that you have to explicitly cast your method as a Func for this to work, or you'll get a "type arguments cannot be inferred from usage" compile error.  It would be nice to be able to just write:

var CurriedCreate = Bind1(CreateMessage); 

cbut, alas, C#'s type inference doesn't let you do this.  Implementing Bind1 as an extension method, is one option to clean up the syntax, though:

 

public static Func<T2, TR> Bind1<T1, T2, TR>(this Func<T1, T2, TR> function, T1 param1)
{
   return delegate(T2 param2) { return function(param1, param2); };
} 

private static string CreateMessage(string a, string b)
{
   return string.Format("Let's write a message.... {0} + {1}", a, b);
} 

static void Main(string[] args)
{
   Func<string, string, string> tmp = CreateMessage;
   var CurriedCreate = tmp.Bind1("Some crazy string value"); 

   Console.WriteLine(CurriedCreate("Another insane string!"));
   Console.WriteLine(CurriedCreate("and another"));
   Console.WriteLine(CurriedCreate("yet another"));
}

 

Note that there is a lot more to say on this subject, but that will have to wait for another post.

Posted by cmarinos | with no comments
Filed under: , ,

Testing for Exceptions in Unit Test Frameworks

In MSTest and nUnit, the typical way to test for exceptions is by using the [ExpectedException] attribute on a test method.  I've always found this to be a little annoying, but it was just recently that I decided to do something better.  Unsurprisingly, I'm not the first one to have this thought; xUnit uses this method of exception testing by default and a Google search revealed that a few others had posted about this as well.  It still makes for a decent blog post, though, so I figured that I would toss this up for everyone to check out.

The problem

Pure unit test philosophy says that each test method should test one and only one condition.  I tend to agree with this, but sometimes, it can be a bit cumbersome.  For example.  Let's say we're testing the indexer on a 2D array.  An obvious test would be to make sure that an IndexOutOfRangeException is thrown when a user tries to use an out of range index.  For a 2D array, though, there are quite a few ways for this to happen.  Let's take the lower boundaries to start:

[TestMethod]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void TestIndexerWithExpectedException()
{
    var obj = new int[5, 5];
    var tmp = obj[-1, -1];
}

[TestMethod]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void TestIndexerWithExpectedException1()
{
    var obj = new int[5, 5];
    var tmp = obj[0, -1];
}

[TestMethod]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void TestIndexerWithExpectedException2()
{
    var obj = new int[5, 5];
    var tmp = obj[-1, 0];
}

As you can see, this is actually quite a bit of code to test something that should be pretty simple.  We just wanted to test to make sure that the indexer throws an exception if you go off the low end, but we had to write 3 functions to do this, all with a lot of repeated code (even if we extracted the construction of obj out of each method).  Now think about what happens when we try to test all of the boundaries of the array to make sure that they throw exceptions.  If you think of the array as a square grid, each corner has 3 different ways to go off the edge and cause an IndexOutOfRangeException.  That means that we have 12 different ways to cause an error, so at the very least, we have 12 different test methods.  Yuck.


The ExpectedException approach also has another obvious problem:

[TestMethod]
[ExpectedException(typeof(IndexOutOfRangeException))]
public void UnfortunateResultFromUsingUnexpectedException()
{
    var obj = new int[5,5];

    //initialize array...
    obj[5, 5] = -1;//random mistake while initializing the array
    //more initialization code would go here...

    var tmp = obj[-1, -1]; // this code was the real test, but it doesn't get executed...           
}

Though the above code is a small example, it illustrates the danger of using the ExpectedException approach.  ExpectedException says that somewhere in your test method, the test will throw an exception, but it doesn't specify where that will happen.  That's not fine grained enough for a good unit test.  As you can see above, fairly innocent initialization code can cause your well intentioned test to pass or fail for the wrong reasons.

A Better Approach?

One approach to remedy this problem is to use try/catch blocks with some sort of "exception thrown" flag:

[TestMethod]
public void TestIndexerWithTryCatch()
{
    var obj = new int[5,5];

    //lots of ugly try/catches... not very nice to look at, but provides more fine grain control within a test.
    bool exceptionThrown = false;
    try
    {
        var tmp = obj[-1, -1];
    }
    catch (IndexOutOfRangeException)
    {
        exceptionThrown = true;
    }
    Assert.IsTrue(exceptionThrown);

    exceptionThrown = false;
    try
    {
        var tmp = obj[-1, 0];
    }
    catch (IndexOutOfRangeException)
    {
        exceptionThrown = true;
    }
    Assert.IsTrue(exceptionThrown);

    exceptionThrown = false;
    try
    {
        var tmp = obj[0, -1];
    }
    catch (IndexOutOfRangeException)
    {
        exceptionThrown = true;
    }
    Assert.IsTrue(exceptionThrown);
}

This approach gives you the benefit of allowing you to control where you are testing for the exception to occur.  You get the fine grained control you want in a unit test, but unfortunately, this makes your code ugly and bloated.  It's not a bad compromise, but we can definitely do better.

A Better Approach 2.0

While it was nice to have fine grained control, it was a pain to write.  What would really be nice is if our unit test library provided something like this:

        [TestMethod]
        public void TestIndexerUsingExceptionAssert()
        {
            var obj = new int[5, 5];

            //assertion version of the try/catch syntax... much less repeated code, no need for individual functions.
            MyAssert.ThrowsException<IndexOutOfRangeException>(() => { var tmp = obj[-1, -1]; });
            MyAssert.ThrowsException<IndexOutOfRangeException>(() => { var tmp = obj[0, -1]; });
            MyAssert.ThrowsException<IndexOutOfRangeException>(() => { var tmp = obj[0,0]; });
        }

Now we have what we really want.  We have the fine grained control that the "try/catch with a flag" approach gave us, but it's much easier to read/write, and we don't have to repeat so much code.  xUnit supports this style of exception testing by default (see Assert.Throws), but if you don't want to switch to xUnit, it's very easy to implement yourself:

    /// <summary>
    /// Contains assertion types that are not provided with the standard MSTest assertions.
    /// </summary>
    public static class MyAssert
    {
        /// <summary>
        /// Checks to make sure that the input delegate throws a exception of type exceptionType.
        /// </summary>
        /// <typeparam name="exceptionType">The type of exception expected.</typeparam>
        /// <param name="blockToExecute">The block of code to execute to generate the exception.</param>
        public static void ThrowsException<exceptionType>(Action blockToExecute) where exceptionType : System.Exception
        {
            try
            {
                blockToExecute();
            }
            catch (exceptionType)
            {
                return;
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected exception of type " + typeof(exceptionType) + " but type of " + ex.GetType() + " was thrown instead.");
            }

            Assert.Fail("Expected exception of type " + typeof(exceptionType) + " but no exception was thrown.");
        }
    }

And there you have it- a better way to test for exceptions.  Nothing revolutionary, I know, but it never hurts to have more example code for folks to look over.

Posted by cmarinos | 7 comment(s)
Filed under: ,

*Nixing Your Windows Workstation - Part 1

At home, I run Ubuntu Linux as my primary OS since I'm a sucker for eye candy (Compiz FTW) and I'm a nerd.  At work, most of my development needs to be done in Windows, and until recently, I found myself missing some of the features that I use at home.  Fortunately, I was able to find some nifty programs that help me put a *nix spin on windows.  Here's part one of my windows customization fun:

 

Restore Virtual Desktop Functionality With VirtuaWin

Plain and simple, VirtuaWin is the Windows application that I have been trying to find for many years.  Ever since I got used to virtual desktops when I first tried Linux a few years back, I desperately missed them every time I had to use a Windows machine.  I tried several other programs to provide this functionality, but they never stayed on my machine more than a few minutes.  Some were too slow, some were too bulky, and some just didn't have the features I was looking for.  VirtuaWin is open source, quick, and easy to use.  Just install, configure your shortcuts to your liking (Ctrl+Alt+left, Ctrl+Alt+right, Ctrl+Alt+H, Ctrl+Alt+L for me), and you're ready to go.  You can hold down shift (or another custom key) to drag windows with you when you switch desktops, set windows to be sticky across all desktops, change the number of virtual desktops used, and quite a bit more.  It even supports mouse switching, but I don't find myself using this feature too much at work.  Highly recommended- even for those who aren't (yet) fans of virtual desktops.

 

Move Windows Around With Alt+Click Using WinMover

This is a pretty simple one.  In some Linux environments, you can press the Alt key, then click and drag anywhere on the window to move it around.  I use this feature all the time under Linux because it's easier than hunting for the titlebar when my hand is on the mouse.  Admittedly, this has only limited use, but I missed this feature in Windows nonetheless.  With Compiz's wobbly windows enabled under Linux, I also find it fun to move windows around this way because it feels more like you're throwing or dragging them around (what can I say, I'm easily amused).  This behavior can also be nice for laptops where it can be a pain to pinpoint small titlebars with a touchpad.

 

Bind Caps Lock to Ctrl to Up Your Hacker Street Cred

Okay, so I didn't actually decide to do this tweak because I missed it from Linux.  It turns out that I just got carried away with all of the tweaks that I had been doing and decided to keep going.  I was a bit skeptical at first, but now I love having my caps lock as another Ctrl key.  It's much easier to reach the caps lock key vs. the left or right Ctrl, but more importantly, it makes it easier for me to do Ctrl+number to switch tabs in Firefox.  Under Linux, Firefox uses Alt+number to switch directly to a tab which I find to be much easier to type than the Windows default of Ctrl+number.  Unfortunately, I was not able to find a good workaround for rebinding this key in Firefox (and I looked pretty hard), but having Ctrl bound to Caps Lock makes it a lot more comfortable to type.

 

This little registry tweak below will do the rebinding for you, just copy and paste the text into a .reg file, and import it with regedit.  There's several resources online to explain exactly what it's doing if you want to go into more depth.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,1d,00,3a,00,00,00,00,00

Posted by cmarinos | with no comments

Hello World!

Well it finally happened.  First it was a subtle hint, “we’re giving you all blogs in case you ever want to start blogging!” Next came the slightly less subtle hints, “Hey! That would make a good blog post!” And finally, I was just plain called out by my boss, “Now if we can just get Chris, Nate and Alex blogging.” To paraphrase Wyatt Earp, they called down the thunder, and now they’ve got it- my first foray into the blogosphere.

Unfortunately for me, an important step in creating a blog is writing a first post, and who really knows how to do that? Well, according to Google, and more specifically, this dude who blogged about how to write your first blog post, I’m supposed to start with who I am, why I’m blogging, what I’ll be blogging about, and something else that I can’t really remember. Oh, and I’m supposed to have pictures, too. Sounds good. Anyway, I’ll get to that stuff in a sentence or so, but since most of the content on here will be programming related, I wanted to first point out how nice it is to know that thanks to that guy, blogs are apparently self compiling now. Wonderful.

Okay, now that I have all of that out of the way, let’s start the show:

n2205745_33932969_5775

(Showing some school spirit. I'm the guy with the maize shirt and the open mouth...)

Who am I?

For this blog, the parts that might matter are that I’m a Software Consultant at SRT Solutions, a recent graduate of the University of Michigan (Go blue!), and that I’ve got a passion for software development. I’m a measly 21 years of age, and the bulk of my development right now is done in C#.  As far as languages go, I love C/C++ (much to the dismay of my coworkers), but I also like playing around with other languages (Python, Ruby, Java, Lisp, etc.) as well.  I'm very close with my family, I love video games (big surprise), and I'm a Detroit sports fan (especially the Wings).

randompic

(Serious pictures aren't really my forte.)

Why am I blogging?

Reason 1: Shameless Self Promotion (A.K.A. self branding/social media/marketing)

This one should be obvious; after all, you’re reading a blog. I’d wager that most blogs with any sort of readership have at least started out as some good old fashioned shameless self promotion- and for good reason, too. Blogging is a great, easy way to help strengthen your personal brand, and there’s nothing wrong with that. In my case, it also has the benefit of marketing for the company I work for, which makes my bosses happy, so it’s basically a win-win situation.

Reason 2: Peer Pressure (A.K.A. respect and commitment to my coworkers)

Hey, I’m man enough to admit that a good chunk of why I decided to start blogging now was because all but a few of my coworkers decided to do it. It also doesn't hurt that there really isn't any good reason NOT to join them. And yes, if everybody was jumping off a bridge, I WOULD follow them (assuming that it was a really, really short drop).

ProfilePic2

(Okay, one halfway serious one for the road.)

What am I blogging about?

Whatever the heck I want to blog about. That being said, most of the content is probably going to be focused on software development since, after all, this blog is hosted by SRT Solutions. Aside from software, we’ll see as time goes on. I’m probably twice as knowledgeable about video games as I am about software development, and there is a little bit of synergy between video games and software development, so I wouldn’t be surprised to see my vice manifest itself here from time to time. Other than that, who knows. Build it and they will come, I suppose.

So there you have it, my first blog entry. Let me know what you think about it!

Posted by cmarinos | 1 comment(s)
Filed under: