Convert an Integer to a Binary Representation

Here is a quick way to convert any integer n into a string that represents the n integer in binary notation:

def dec_to_bin(n, bits=32):
    return ''.join([str((n >> y) & 1) for y in range(bits - 1, -1, -1)])

What's going on in the above code? This can be better explained if we read the return line in the dec_to_bin function backwards. First we create a list of integers from 31 to 0 in order to iterate through it. This list is created with the built-in range function and it uses the number of bits that we passed into the function, with a default being 32. Next, we iterate through the list with each number being represented by y. Then we take the number parameter n, which is the number we want to transform to binary, and we shift its bits to the right by y places. Then we apply a bitwise and operation on the result of that right shift and the literal value of 1. This and operation tells us if the bit at location y is turned on or off. We then make a string out of the value and append it to the string that we are building to return to the user. This is a perfect example of Python's conciseness and the power of list comprehensions.

You can use the code above like so:

>>> print dec_to_bin(255)
00000000000000000000000011111111

Enjoy!

Practical Keyboard Macros in Emacs

If you spent any time in Emacs you will sooner or later run into keyboard macros. In this article I will cover the basics of keyboard macros by going through a few practical, real-world examples. If you are new to Emacs or don't know about keyboard macros, then this is a great place to start.

In my work I am querying databases and writing reports for people on a daily basis. I like to use Emacs SQL mode as my front end for connecting to a Microsoft SQL Server backend because it allows me to write queries and manipulate the results in very powerful ways.

A scenario where I use keyboard macros goes something like this: A business user gives me a list of invoices and she needs to check if they where processed in our invoicing application. She would send the list in email or IM and it looks like this:

001000403456
001000404567
001000405678
001000405679
001000405680
001000406789
001000406790
001000407890
001000407891
001000407892

In the database we have a table called InvoiceHeader where we keep the invoice data. The InvoiceNumber column is of a nvarchar(30) type. This means that if I want to use the list of invoices above in a IN clause of a transact SQL query, I need to wrap each item with single quotes and delimit then with a comma. That's not too much work if this is a one-off and your list has only 10 items like the list above. But what if the list has 100 or 1000 items and you were doing these types of queries several times per week? Well, this is where keyboard macros come to the rescue.

Suppose that your SQL code looks like this:

SELECT h.InvoiceNumber
     , h.CustomerName
     , h.DueDate
     , h.Status
     , SUM(d.Cost)
FROM InvoiceHeader h (NOLOCK)
JOIN InvoiceDetail d (NOLOCK) ON h.RowID = d.InvoiceID
WHERE h.InvoiceNumber IN (
  -- PASTE INVOICE NUMBER LIST HERE
) GROUP BY h.InvoiceNumber, h.CustomerName, h.DueDate, h.Status

I paste the list of invoice numbers from the email to where I indicated in the comment in the query above. The invoice numbers are structured one per line and each looking like this 001000407892 but I need them to look like this '001000407892',. To achieve that using Emacs keyboard macros, place the point on the line with the first invoice number and follow these keystrokes:

C-x (
Start macro recording
C-a
Anchor the point at the beggining of line
'
Insert a single quote
C-e
Anchor the point at end of line
' ,
Insert a single quote and a comma
C-n
Move the point to the next line
C-x )
Stop the macro recording

Go ahead and try it now. Once completed, the key sequences above allowed you to record the macro, and now you will want to apply the macro to all the lines in the rest of list of invoices. You do that by keying in the following chord: C-x e. This key sequence invokes the Emacs command kmacro-end-and-call-macro which calls the last defined keyboard macro.

This is certainly a lot more efficient than applying the single quotes and commas to each line manually. And this is just one way to make macros work for you. As you probably already know, there is more than one way to skin a cat in Emacs. Lets see how we can make our macro example even more efficient for our SQL coding situation.

Macros Reloaded

What I really want to do in the situation above is to yank my list of invoice numbers into the WHERE clause of the query and then mark the region. Once I have the region marked, I want to apply the macro to the whole region in one key chord. Starting with the following SQL code:

SELECT h.InvoiceNumber
     , h.CustomerName
     , h.DueDate
     , h.Status
     , SUM(d.Cost)
FROM InvoiceHeader h (NOLOCK)
JOIN InvoiceDetail d (NOLOCK) ON h.RowID = d.InvoiceID
WHERE h.InvoiceNumber IN (
    001000403456
    001000404567
    001000405678
    001000405679
    001000405680
    001000406789
    001000406790
    001000407890
    001000407891
    001000407892
) GROUP BY h.InvoiceNumber, h.CustomerName, h.DueDate, h.Status

This is what I do:

  1. Place the point a the start of the line of the first invoice number
  2. Record the macro by follonwing the key chords in the table above (if you haven't already done so)
  3. Undo the editing you done by recording the macro
  4. Mark the region encompassing all the invoice numbers
  5. Use the key chord C-x C-k r to apply the macro to each line in the region
  6. Delete that last comma behind the last invoice number so you won't get a syntax error in you SQL code

This is the result of performing the steps above:

SELECT h.InvoiceNumber
     , h.CustomerName
     , h.DueDate
     , h.Status
     , SUM(d.Cost)
FROM InvoiceHeader h (NOLOCK)
JOIN InvoiceDetail d (NOLOCK) ON h.RowID = d.InvoiceID
WHERE h.InvoiceNumber IN (
    '001000403456',
    '001000404567',
    '001000405678',
    '001000405679',
    '001000405680',
    '001000406789',
    '001000406790',
    '001000407890',
    '001000407891',
    '001000407892'
) GROUP BY h.InvoiceNumber, h.CustomerName, h.DueDate, h.Status

This is a simple example of the power of keyboard macros in Emacs. There are many other more complex tasks you can accomplish using keyboard macros that I have not covered here. Things such as parsing log files and outputing lines based on a regular expression or doing string substitution on a buffer while asking the user for the input to replace the tokens with.

Things to Remember

In order to write effective and flexible macros that work everywhere always remember to use your anchor key chords. These key chords allow you to place the point in the buffer with a great degree of flexibility. To name a few, they are: C-a, C-e, C-n, C-p, etc.

If you will perform the task you captured in the macro on a regular basis, then you will want to save it to your .emacs file and maybe even bind it to a key chord of your choosing. First, key in the chord C-x C-k n and give your keyboard macro a unique name. Open up your .emacs file and place the point in the buffer where you can yank some content. Use the elisp function to yank the macro definition from the macro ring to the point location by typing M-x insert-kbd-macro and then providing the name you just created. If you are saving the macro definition we have been working on in the article, then you should see code similar to this:

(fset 'prep-list-items-for-sql
   (lambda (&optional arg) "Keyboard macro."
     (interactive "p")
     (kmacro-exec-ring-item
      (quote ("^A'^E',^N" 0 "%d")) arg)))

Finally, you can bind your macro to a key chord to make it easily accessible in any situation. I have the following code in my .emacs file to bind Shift plus the F10 key to the macro:

(global-set-key [S-f10] 'prep-list-items-for-sql)

Until next time and happy emacs hacking!

Bill Murray to win an Oscar

This is off-topic for this venue and the fact that I decided to include it says a lot about how strongly I feel: I just watched the trailer for the upcoming movie Hyde Park on Hudson, starring Bill Murray as F.D.R., and based on that alone, I am hereby predicting that Mr. Murray will win an Academy Award for the performance.

Update 2014-11-29 13:58:35

This movie didn't win the heart of critics and took a lot of dramatic liberties around historical facts.

Heard on Twitter...

If you aren't willing to learn, No one can help you. If you are determined to learn, No one can stop you.

Ted Neward (@tedneward), [+] Wed 22 Aug 2012 14:52

List your Current Emacs Key Bindings

A lot of people who use Emacs bind different keys to functions and other things. From time to time I tend to forget what I bound a key to, so perhaps I am getting old. There is, however, a quick way to list out all the bindings currently available to the session of Emacs you are using.

To view a list of bindings, use the following incantation:

M-x describe-bindings

Alternatively, you can use the following command:

M-x describe-key

With describe-bindings we can see a list of all defined keys and their binding definitions. The describe-key function will display the documentation of the binding invoked by the key you are interested in.

How to use Emacs key bindings in Visual Studio 2010

Visual Studio 2008 used to have a Emacs key mapping scheme that you could pick from the Options dialog under the Keyboard options. Visual Studio 2010 did away with that key mapping scheme.

VS2010 Keyboard Mapping Schemes

But those emacs enthusiasts among us who use Visual Studio should not fear... There is now an Emacs Emulation extension available for VS2010 that you can install via the Extensions Manager under the Tools menu.

Installation

To install the Emacs Emulation extension, follow these steps:

VS2010 Extensions Manager

  1. Open Visual Studio 2010
  2. Go to the Tools menu
  3. Select the Extension Manager
  4. On the Extension Manager dialog, select Online Gallery
  5. Search the Online Gallery for Emacs (top right)
  6. Select and install the Emacs Emulation package
  7. Restart Visual Studio 2010
  8. From the Options dialog, the Emacs key mapping scheme is now available

VS2010 Emacs Keyboard Mapping Scheme

Beyond the default Emacs key bindings, the ones that I find most useful are the following:

Edit.EmacsExtendedCommand
ALT + X - Places the cursor in the Find/Command box on the Standard toolbar.
Edit.EmacsFindReplace
SHIFT + ALT + 5 - Displays the replace options in the Quick tab of the Find and Replace dialog box.
Edit.EmacsSwapPointAndMark
CTRL + X, CTRL + X - Moves the cursor to the current mark in the location stack and moves the current mark to the location where the cursor mark was when the command was invoked.
Edit.EmacsCloseOtherWindow
CTRL + X, 1 - When a window is split, this shortcut closes the pane that does not have focus.
Edit.EmacsSplitVertical
CTRL + X, 2 - Splits the current document in half vertically. The current line of code is centered in each window.

... and that's all, folks!

An Emacs Birthday Present

There is a little known amusement in Emacs that you can use on your loved ones:

  1. For maximum effect, ensure the loved one is looking over your shoulder.
  2. Open emacs
  3. Enter the command: M-x animate-birthday-present
  4. Provide your loved one's name and ...
  5. Voila! Watch the magic happen...

To find out more about it, describe the function (C-h v animate-birthday-present) or look in animate.el. Have lots of fun...

Swap CTRL with CAPS LOCK in Xubuntu 11.10

I wrote previously about swapping CapsLock and Ctrl in an older version of Ubuntu, but recently I have been using Xubuntu because I don't like the user interface changes in the newer versions of standard Ubuntu desktop. Well, it turns out that the old technique for swapping the keys doesn't work on Xubuntu. But there is an alternate method:

  1. Open the Applications Menu on the top left side of the screen and click Settings.
  2. Click on the Settings Manager option and then click on Session and Startup.

    Xfce Settings Manager

  3. Click the Add button and enter Swap CapsLock & Ctrl for the name.

    Xfce Session Startup

  4. Next enter /usr/bin/setxkbmap -option "ctrl:swapcaps" for the command.

    Xfce Add Application

  5. Click the OK button and then click the Close button.

  6. Restart the computer.

That is it... Super easy!

Heard on Twitter...

Shipping a version 1 that does one thing well is the only way to not ship crap AND not waste time on something nobody wants.

apike, (RT by avibryant), [+] Tue 17 Jan 17:49