Great vim quick reference card

There are some Vim commands or keystrokes which I don’t use often and also some useful ones which I tend to ignore or forget.

For example I never do movements with combinations of (), [] and {}, even if some of them would allow me to move through source code in a real hurry!

I have my own text file with some “must-remember” commands, mostly related to my own bindings and plugins, but I just found an impressively complete Vim reference card, which is going to be stuck up over my desk at the office.

The card has been made by Laurent Grégoire, with some community contributions and can be found on Laurent website here: http://tnerual.eriogerg.free.fr/vim.html.

This is the direct link for the English PDF.

Other formats and languages are available on the website.

C++ Simulator for the Monthy Hall Game

Suppose you’re on a game show, and you’re given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1 [but the door is not opened], and the host, who knows what’s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to switch your choice?

[From Wikipedia]

Introduction

The game is simple: first the player chooses a door, than the host opens one of the remaining doors which has a goat behind it, then the player is offered the chance to change door. At the end, the last door the player chose is opened and the hidden object is the player’s prize. The player’s objective is to open the door that hides the car.

To understand the gist of the game, whether it should be better to change the door or to keep the previously selected one, consider this simple explanation.

If you want to change door, then you will win if your first choice was a goat-door.
If you don’t want to change door, then you will win if your first choice was the car-door.

At the beginning, you can pick a goat-door with a probability of 2/3 (66%).
At the beginning, you can pick a car-door with a probability of 1/3 (33%).

If you decide to change door, you will win with a probability of 2/3.
If you decide not to change door, you will win with a probability of 1/3.

Well, this is the game, then it comes the simulator.

The Simulator

Code here: https://github.com/vincepii/MontyHallSimulator

I was watching the football match between Portugal and Czech Republic and getting bored.
My brother proposed me to implement a model to simulate the Monty Hall problem, and that was a great idea.

While I was at coding, I decided that it was more interesting to develop a full emulator of the game, rather than a tiny mathematical simulation model, and this is what I did. Nevertheless, the emulator performs well also for simulations (10,000,000 runs of the game in less than 7 seconds on my notebook).

If you want to try it, or take a look at the code, you can find it on GitHub.

If you are only interested in some results, this is what happens when running 10,000,000 cycles:

vince@vince-VPCSB1C5E:~$ montyhallsimulator --cycles 10000000

Number of games (total): 10000000
Number of times the player changed doors: 5002849
Games result (WON/TOTAL): 5003182/10000000 (50.0318%)
Winning rate when changing door: 3336568/5002849 (66.6934%)
Winning rate when NOT changing door: 1666614/4997151 (33.3513%)

It is funnier to see what happens every game, using the verbose mode:

vince@vince-VPCSB1C5E:~$ montyhallsimulator --cycles 1 --verbose

The player Chose door number 2
The host Chose door number 1
The Player Changed its door and picked door number 0
The Player Won the game, car behind door number 0

The simulator also works with more than three doors, applying the same rules. This could be interesting for statistical analysis.

For the complete list of options, just type – -help:

vince@vince-VPCSB1C5E:~$ montyhallsimulator --help
Program options:
  --help                Help message
  --doors arg (=3)      Number of doors (default: 3)
  --cycles arg (=1)     Number of runs of the game (default: 1)
  --verbose             Verbose mode, prints player and host actions (default: 
                        false)

Technicalities

The Pseudo-Random-Number-Generator that the simulator uses is the boost::mt19937, initialized with a time-dependent seed.

In order to test different PRNGs easily, the generator has been encapsulated inside an Adapter class and instantiated with a Singleton to ensure that always the same generator with the same seed is used across a simulation.

I have used the boost::program_options library for options parsing. If downloading the run-time libraries (e.g.: libboost-program-options-dev package under Ubuntu) is a problem for you, the main.cpp file can be easily edited to manually assign values to the doors, cycles, and verbose variables. Then the code for options handling can be removed.

I’ve used the CMake build system to create Makefiles for the code. That’s another requirement.

Discovering SCons

I was looking for alternative – alternative to what? make, autotools, CMake – software building tools for C++ and I discovered an interesting project I didn’t know about: SCons.

Everybody knows about SCons.

SCons is a software construction tool that lets you write SConstruct files (the SCons makefile counterpart) in a very concise (with respect to classic Makefiles) and powerful way. But the greatest part of it is that you can write Python code inside your SConstruct files!

Imagine you could write a line like this inside your Makefile:

src_files = [src_dir + name for name in src_files]

I think this is enough to decide it could be worth trying it!

Following the SCons User Guide I managed to create a SConstruct file to replace my Makefile in a subdirectory of an existing project in a very short time. And it worked really well.

I had a bit of disappointment when I decided it was time to choose where to put object files, libraries and executables. This is how this must be done in SCons: Separating Source and Build Directories.

Initially I couldn’t believe it had to be so cumbersome, but I had some confirmations:

Anyway, the world is not a perfect place.

Nice to meet you, SCons.

Lens for Ubuntu Unity (12.04) to browse tasks on Remember The Milk

UPDATE: latest version

IMPORTANT NOTICE:

This product uses the Remember The Milk API but is not endorsed or
certified by Remember The Milk.

Ubuntu 12.04 is out, so I decided to update my lens for remember the milk to work in Unity 5.

Actually, the lens uses singlet, by Michael Hall (many thanks for your work), so the transition to Unity 5 has been flawless.

While I was there, I made some minor improvements (e.g. the due dates are now printed in a prettier format) and added a feature to sort tasks.

As usual, I screencasted the lens at work:

If you want to try it, you can get the source code here on gitHub.

I wrote two simple scripts to install and launch the lens. You can find instructions on the README file.

Don’t trust the temporaries (C++)!

Class X is defined as follows (C++):


class X {
    std::map<uint32_t, uint32_t> _map;
public:
    X() {
        for (uint32_t i = 0; i < 20; i++) {
            _map[i] = i + 10;
        }
    }

    std::map<uint32_t, uint32_t> getTheMap() const {
        return _map;
    }
};

The getTheMap method returns by value.

What is the output of this code?

X x;
std::map<uint32_t, uint32_t>::const_iterator it = x.getTheMap().begin();
std::map<uint32_t, uint32_t>::const_iterator et = x.getTheMap().end();

for (; it != et; it++) {
    std::cout << "[" << it->first << ";" << it->second << "]" << std::endl;
}

It’s undefined!

At lines 2 and 3, the map iterators are obtained on a temporary object which is destroyed just at the end of the statement. That’s because getTheMap() returns by value. Consequently, on the for loop at line 5, we are iterating over unallocated memory.

My main concern about class X code was to find a way to stop users using it the wrong way (such as in the above code sample). I was told on stackoverflow that in C++11 the STL itself should have a protection to make that code illegal.

Another interesting and very elegant solution is the use of a wrapper:

class X {
    std::map<uint32_t, uint32_t> _map;

    class InternalWrapper {
        const std::map<uint32_t, uint32_t>& _internalMap;

    public:
        InternalWrapper(const std::map<uint32_t, uint32_t>& map) :
            _internalMap(map)
        {}

        operator std::map<uint32_t, uint32_t>() const {
            return _internalMap;
        }

    };

public:
    X() {
        for (uint32_t i = 0; i < 20; i++) {
            _map[i] = i + 10;
        }
    }

    InternalWrapper getTheMap() const {
        return InternalWrapper(_map);
    }
};

The magic of this code is done by the automatic type conversion operator at line 12.

Now, the getTheMap() method returns an object of type InternalWrapper by value. This object can be implicitly converted to std::map<uint32_t, uint32_t> type, but it doesn’t have begin() and end() methods, so the following line of code is illegal:

std::map<uint32_t, uint32_t>::const_iterator it = x.getTheMap().begin();

The user is now prevented from using the interface incorrectly and the only way he can use it is the correct one, this one:

std::map<uint32_t, uint32_t> map = x.getTheMap();
std::map<uint32_t, uint32_t>::const_iterator it = map.begin();
std::map<uint32_t, uint32_t>::const_iterator et = map.end();

Wow!

Ubuntu 12.04 and Hybrid Graphics on Sony VAIO S

As an update to this post, I confirm that using vgaswitcheroo to shutdown the discrete AMD/ATI card on the new Sony Vaio S, works perfectly also in 12.04 (Precise Pangolin).

Quick reference:

  1. Edit the file /etc/modprobe.d/blacklist.conf (replace “gedit” with your favorite editor):
    sudo gedit /etc/modprobe.d/blacklist.conf
  2. Add the following lines at the end of the file:
    # radeon
    blacklist radeon
  3. Edit the file /etc/rc.local (replace “gedit” with your favorite editor):
    sudo gedit /etc/rc.local
  4. Add the following lines just before exit 0:
    modprobe radeon
    chown -R $USER:$USER /sys/kernel/debug
    echo OFF > /sys/kernel/debug/vgaswitcheroo/switch

After a restart, use this command to verify that the AMD/ATI discrete graphic card has been shutdown:

sudo less /sys/kernel/debug/vgaswitcheroo/switch

Your output should be similar to this:

0:IGD:+:Pwr:0000:00:02.0
1:DIS: :Off:0000:01:00.0

Where the + sign indicates that the Integrated card (Intel) is currently in use and the Off keyword in the 1:DIS: entry indicates that the discrete AMD/ATI card is powered off.

The benefits I’ve noticed when using this setup are:

  • The notebook is much less noisy
  • The battery lasts longer
  • The notebook is cooler

Tasks Lens for Ubuntu Unity (11.10) to browse tasks on Remember The Milk

UPDATE: latest version

IMPORTANT NOTICE: This product uses the Remember The Milk API but is not endorsed or certified by Remember The Milk.

This is my third update for this Lens.

Unfortunately, as some of you might have noticed, the previous two have disappeared.

Anyway, here’s the last version of the Lens in all her splendor :D:

And here you can find the source code with installation instructions:

SOURCE CODE on GITHUB

IMPORTANT NOTICE: This product uses the Remember The Milk API but is not endorsed or certified by Remember The Milk.

Creating screencasts with Ubuntu: a summary of available desktop recording applications

There are many available options to record your desktop on Ubuntu, but I’ve found only one of them to be properly working with my configuration.

My results could be hardware-dependent, so, this is my hardware:

  • Sony Vaio S-Series
  • i5-2520 @ 2.50 GHz processor
  • 4 GB RAM
  • Intel HD 3000 integrated graphic card (Hybrid Graphics with discrete ATI card is disabled)

RecordMyDesktop

recordmydesktop

Project Home Page: recordmydesktop

This seems to be the most popular option when talking about screencasting software for Ubuntu.

It can easily record video + audio from your microphone and it is very easy to use it.

My problem is that the recorded video will not be synchronized with my actions, resulting in glitches, delay and low frame rate.

This is exactly what I am talking about:

However, many people are happy with this software (I’ve seen many HD videos properly recorded with recordmydesktop on YouTube), further, it is one of the simplest solution to test, just type:

sudo apt-get install gtk-recordmydesktop

or use the software center.

If it works with your configuration, good for you.

XVidCap

XVidCap

Project Home Page: xvidcap

This application works really well for video recording, however I wasn’t able to record audio from the microphone. Anyway, I have to admit that didn’t spend much time trying to fix the audio configuration.

The settings dialog is rich of options and the application is highly customizable.

Like recordmydesktop, you can find it in the repositories, so you can install it with

sudo apt-get install xvidcap

or through the software center.

Tibesti

Tibesti

Project Home Page: tibesti

This application is not present by default in Ubuntu repositories, but you can find instructions on its home page on how to add the PPA to install it.

Alternatively you can download the last source archive, extract it and build the application with the setup.py script:

python setup.py build

The application is very simple to use but I had major issues when recording videos.

After a few seconds, the video stopped recording what was being displayed on the desktop and started collecting a big delay.

It must be remarked that recording audio from the microphone or from the system out is very easy, but the video problem prevented me from using this application.

FFMPEG

There are many tutorials on how to use ffmpeg for recording the desktop. It is also possible to easily record audio from the microphone.

One of the most useful resource I’ve come across is this page on Ubuntu Forums.

This is a very effective solution, but a GUI approach is preferred by most users for this kind of applications.

Kazam

Kazam

Project Home Page: kazam

This is the winner for tonight contest on desktop recording applications.

  • It records video flawlessly: no glitches, no frame losses, perfectly synchronized
  • When you stop the recording, your video is instantaneously available (with recordmydesktop you have to wait for a long encoding process)
  • It is very easy to record audio with video
  • The interface is modern and the look and feel is great, a special mention goes to the countdown window preceding the recording of a new screencast

Kazam is not present in Ubuntu repositories, but you can easily install it using the .deb archive that is provided on the launchpad page.

Conclusions

Kazam really had all the features of a modern desktop recording application for a modern OS. I was quite surprised for not having found it in the official repositories.

If I have omitted some other relevant desktop recording applications, just let me know about it.

Doing backups with Ubuntu: again with Back In Time

In the past, I’ve always used Back In Time to do my data backups, then I switched to DejaDup when it became the official Ubuntu backup tool in 10.10.

I’ve been quite happy with DejaDup: simple and neat interface (maybe even too simple), easy to use, solid.

The problems with DejaDup started when I wanted to search for a particular file across the backups. I was sure it was there, but I couldn’t remember in which backup (the date of the snapshot) I included it. DejaDup doesn’t provide a “snapshot browser” as Back In Time does and it is not possible to browse the data directly on the storage device as it is archived in tar format.  The only option is to recover a snapshot by its date.  In this situation, the lack of a more advanced set of functions made me fell helpless.

I don’t want to talk about the features of Back In Time here, as they are well documented on the web site along with some nice screenshots, but about why I preferred it over DejaDup. A single reason:

  • Backups are stored in plain format (files and folders) on your storage device, with the same directories structure of the source data

This implies a whole set of benefits:

  • Control: you can browse a snapshot with your favorite file browser or even with the very rational Back In Time interface. You have everything under your control (“Was that folder included in the backup?” Just go and check it!)
  • Portability: you can extract the data you need from the storage device even if the backup application is not installed. As long as the OS of the computer where you need to extract the data is able to read the file system of the backup driver, you can get every file you need

In conclusion, I installed Back In Time and re-started doing my incremental backups with this very nice tool.

If you want to give it a try (gnome and kde versions are available from Ubuntu repositories):

sudo apt-get install backintime-gnome

or

sudo apt-get install backintime-kde

Object-oriented blinking with Arduino

Yesterday I started programming again with Arduino.

First thing I setup the Eclipse environment and to test it I ran the very simple blink program.


void setup() {
 pinMode(13, OUTPUT);
 }

void loop() {
 digitalWrite(13, HIGH);
 delay(100);
 digitalWrite(13, LOW);
 delay(100);
 }

Then, I wanted to go OO, so I wrote a class to represent a blinking object!

Header:

class Blink {
 private:
 unsigned long _onInterval;
 unsigned long _offInterval;
 uint8_t _blinkingLedId;
 bool _ledActivity;

public:

Blink(unsigned long onInterval, unsigned long offInterval, uint8_t blinkingLedId);

void oneBlink();

void setLedActivity(bool ledActivity);
 };

Implementation:

Blink::Blink(unsigned long onInterval, unsigned long offInterval, uint8_t blinkingLedId) :
 _onInterval(onInterval), _offInterval(offInterval), _blinkingLedId(blinkingLedId)
 {
 _ledActivity = true;
 pinMode(_blinkingLedId, OUTPUT);
 }

void Blink::oneBlink()
 {
 // LED activity disabled?
 if (_ledActivity == false)
 return;

// ON
 digitalWrite(_blinkingLedId, HIGH);
 delay(_onInterval);

// OFF
 digitalWrite(_blinkingLedId, LOW);
 delay(_offInterval);
 }

void Blink::setLedActivity(bool ledActivity) {
 _ledActivity = ledActivity;
 }

Main:

Blink *b;

void setup() {
 b = new Blink(2000, 2000, 13);
 }

void loop() {
 b->oneBlink();
 }

Well, okay, OOP doesn’t add anything to the story here, but how about having a blinking object instead of a procedural set of blinking statements :D? Exciting!