Archive for the ‘Cookbook’ Category

Boost DateTime, Locales and Facets

Saturday, 17 October 2009

Boost DateTime extends the standard library facets for formatting dates and times according to locale.

I have had some trouble with these libraries. It seems that there is something of a flaw in the design of the standard library locales. Following are some functions that look like they work but don’t, and one that work, but looks like it shouldn’t.



Boost: converting xtime to posix_time

Saturday, 17 October 2009

Here is some Boost code to convert (approximately) from an xtime to a posix_time. (The function forgets the nanoseconds.)

#include <boost/thread/xtime.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
  convert_to_posix_time (const ::boost::xtime & xt) // from_xtime
  // this conversion is valid until
  // about the year 2038 = 1970 + 2^31 seconds
  // after which long(xt.sec) will wrap
  ::boost::posix_time::ptime pt (
      ::boost::gregorian::date (1970, boost::gregorian::Jan, 1),
      ::boost::posix_time::seconds (long (xt.sec)) );
  return pt;

Date Regex; Leap Years

Friday, 16 October 2009

It’s suprising what can be expressed using regular expressions. I tend to think of these at syntactic, but sometimes they can seem almost semantic.

Take dates, for instance, in the format “DD/MM/YYYY”

The months have varying numbers of days. In the Gregorian calendar, a year is a leap year if it is divisible by 4, unless it’s divisible by 100, unless it’s divisible by 400. So, for example, the years 2008 and 2012 are leap years, but the year 2100 is not, but the year 2000 is. This can all be expressed in a regex.


Fast Bit Reversal

Thursday, 15 October 2009

The naïve method of reversing the bits in a number copies the bits one-by-one in a loop, or alternatively, swaps them two-by-two. This algorithms is O(n) where n is the number of bits.

However, there is an O(log n) method (when n is a power of 2); rather than taking n or n/2 steps, it takes log2(n) steps.


Bugzilla Links

Wednesday, 8 April 2009

When you type a comment or a description (which is “comment 0”) for a bug in Bugzilla, certain phrases are treated as special.

For example, the word “bug” followed by a space and then a decimal number is converted into a link to another bug. Therefore, rather than saying

See also bugs 1234 and 2345.

you could instead say

See also bug 1234 and bug 2345.

and the links will be formed by “autolinkification”—you will only see the links after you click the [commit] button.

For more information, see the Bugzilla help topic.

HCF without Division

Wednesday, 8 April 2009

The previous blog entry reminded me of this…


XML Skeletons

Tuesday, 7 April 2009

I often need to write an XML file and can never quite remember the exact syntax. So here, as much for my own record as anything else, are some skeletons.