Archive for January, 2009

C++ Exception Safety Guarantee

Wednesday, January 14th, 2009

After stumbling on this one in a recent telephone interview, I thought I’d refresh my memory.

The following from Anthony Williams’s ACCU Overload Journal article last August provides a succinct summary of the topic.

The Abrahams Exception Safety Guarantee

These guarantees were first documented by Dave Abrahams when the C++ Standards committee were working on the 1998 C++ Standard. The idea is that code should provide one of the three guarantees – if it doesn’t, then an exception occuring in your code will result in leaked resources or corrupt data structures or both. The guarantees are:

The no-fail (or no-throw) guarantee

This is the strongest of all guarantees. A function that provides this guarantee will not throw any exceptions, and will not fail. All destructors should provide this guarantee, as should important operations like swap which provide the building blocks for the code that uses them to provide suitable exception safety guarantees.

The strong guarantee

A function that provides this guarantee is all or nothing: if it fails, then any effects are rolled back so the state of the data structure is the same as it was on entry. This requires that the function doesn’t do anything irreversible (like perform I/O), and that there are suitable operations that provide the no-fail guarantee which can be used to commit or roll back the changes.

The basic guarantee

This is the basic level you should strive for in all code: if a function fails, then it must leave the data structures in a valid state, even if that state differs from the original. For example, failure to insert a new item into a container must leave the container in a valid state, even if all the existing items have been deleted.

Any code that doesn’t provide even the basic guarantee is not exception safe.

Exceptions Make for Elegant Code, ACCU Overload Journal #86, August 2008

Writing exception safe code is hard. If you have any doubts about that statement consider the following challenge from Herb Sutter: Guru of the Week 8. In Exceptional C++, Sutter expands on his earlier post and provides the following guidelines –

Observe the canonical exception-safety rules: (1) Never allow an exception to escape from a destructor or from an overloaded operator delete() or operator delete[](); write every destructor and deallocation function as though it had an exception specification of “throw()“. (2) Always use the “resource acquisition is initialization” idiom to isolate resource ownership and management. (3) In each function, take all the code that might emit an exception and do all that work safely off to the side. Only then, when you know that the real work has succeeded, should you modify the program state (and clean up) using only nonthrowing operations.

The standard for the C++ Standard Library contains the guarantee that no destructor operation defined in the library itself will throw an exception. The C++ Standard, however, does not enforce this requirement for all C++ code so your compiler will not prevent you from creating a class that breaks the golden rule: never throw exceptions from a destructor.

Anyone looking for more information should consult the links above and also look at Abrahams’s essay: Exception-Safety in Generic Components: Lessons Learned from Specifying Exception-Safety for the C++ Standard Library.

Editing and Removing Pages from PDF Documents

Sunday, January 11th, 2009

I’ve been using Google Docs to store and edit my CV, however I’ve recently run into a number of problems when exporting the file.

Word documents are invariably mangled. This is a common problem because Word format is a de facto standard by virtue of the number of companies using Microsoft Word but formatting varies from version to version, platform to platform so it’s not really a standard at all. It’s more frustrating than web development at times. You spend hours laying out your CV on a Mac only to find that it looks like hell when opened and printed on a PC.

Recruiters and employers that use text-processing algorithms to assess candidates for positions hate PDF documents but for anyone who cares about presentation and wants to guarantee that their potential employers see their CV exactly as they intended, there is no other choice.

Unfortunately, Google Docs insists on adding a line feed to the last line of every document and when you export the file as a PDF this can result in a blank page being appended to the end.

Fortunately you can edit PDFs on linux using pdftk.

For example, to create a new two page PDF from the first two pages of an original try:

pdftk originalCV.pdf cat 1-2 output editedCV.pdf

The application enables many more useful ways to manipulate PDF documents. Read the man pages for further details.

Connecting to Ubuntu from iBook G4 Using NxMachine

Saturday, January 3rd, 2009

I’ve been using my girlfriend’s iBook recently and am very impressed by it.

The Good
Things I love include the fact that it feels like unix, the build quality of the hardware itself and the failsafe reliability of its sleep/resume.

(I’ve long forgotten the number of hours I spent a couple of years back disassembling then recompiling the buggy DSDT on my old IBM Thinkpad T20 to fix all the warnings and errors before linking it against a patched kernel in order to get ACPI working. Sure it gave me a taste of the days “when men were men and wrote their own device drivers” but sometimes it’s nice when things Just Work.)

The Bad
Things that niggle include the lack of right-mouse button, the unfamiliar keyboard layout and the absence anywhere on the keyboard of a hash/pound key which makes writing bash scripts a little tricky (it’s ALT+3 but for some reason this isn’t printed on the key itself).

The Ugly
Things that seriously annoy include the monolithic, closed nature of the operating system that requires you to upgrade the whole damn thing in order to use a more recent version of Java.

Early observations aside, connecting to my Ubuntu box using NxMachine was pretty straightforward.

The mac client is straightforward to download and install. Apt-get makes setting up the server on the linux box utterly painless. The instructions on the site are more than sufficient for getting the connection up and running.

Getting the key mapping right takes a little longer – out of the box several keys did not behave as expected.

Anyone looking to save a little time is welcome to use my keyboard settings. To apply them use xmodmap:


xmodmap keyboardsettings

Retrieving Rapidshare Files with Python

Friday, January 2nd, 2009

A cursory google search will reveal several scripts for retrieving rapidshare files using python, but each one I’ve seen delegates the actual retrieval to wget.

This is not necessary.

Rapidshare uses basic authentication to identify logged in members and urllib2 can handle this easily.

The following method would do the trick without the need to call external executables:

def rapidget(url. login, password):
    "Retrieve files from rapidshare using only python"
    request = urllib2.Request(url)
    base64string = base64.encodestring('%s:%s' % (login, password))[:-1]
    request.add_header("Authorization", "Basic %s" % base64string)
    i = url.rfind('/')
    filename = url[i+1:]
    print url, "->", filename
    file = open(filename, 'wb')
    handle = urllib2.urlopen(request)
    buffer = ''
    buffersize = 1024*1024
    while True:
        buffer = handle.read(buffersize)
        if not buffer:
            handle.close()
            file.close()
            break
        file.write(buffer)
        buffer = ''
        print '.',

This assumes, of course, that you have an account at rapidshare.