Nerd wannabe

lazy weblog

Archive for the ‘trivia’ Category

C++ and C++ TR1 (Technical Report 1)

with 5 comments

In this post I will assume you’re familiar with other languages like Java and C#, which are OO languages, and you start to learn the ‘multi-paradigm’ C++. Yeah, you couldn’t be that guy, could you.

So you already know the syntax.. so quick, let’s write classes!

We’ll start with a ‘bitmap’ that supposedly encapsulates a bitmap image, allocating memory at construction and freeing it at destruction:

/* bitmap.h */
#include <string>
class bitmap
    unsigned char *data;
    bitmap(std::string path);
/* bitmap.cpp */
#include "bitmap.h"
bitmap::bitmap(std::string path)
    //allocate memory
    data = new unsigned char [1024];
    //read data from path
    //parse it as an image
    //free the memory
    delete [] data;

Now that’s pretty simple and obvious, given that details about reading/parsing the bitmap are left out.Let’s see how we can use this class; we can allocate a bitmap object on heap like this:

/* main.cpp */
#include "bitmap.h"
int main (int argc, char * argv[])
    bitmap *icon = new bitmap ("./icon");

Oops.. not good, our destructor doesn’t get called. We have to manualy call delete icon so that it calls its delete [] data.

Hmm.. ugly.

But we do know that desctructors are automatically called when an auto variable gets out of scope and so we do this:

 bitmap icon = bitmap ("./icon");

Bummer! this time the destructor is called twice! Obviously, it fails the second time:(

The reason is that we weren’t aware that the default assignment operator is called in what we thought was an initializer (that ‘=’ that stands between the object and the constructor call).

This is actually one of the reasons most C++ code reads like:

bitmap icon("./icon");

The other is performance.
(yeah, event a simple int f = 0; gets obfuscated to int f(0); which looks like a goddamn function call)

Introducing auto_ptr<T>

We can further get rid of: the stars ‘*’ and the destructor by declaring the data to be an auto_ptr:

#include <string>
#include <memory>
using namespace std;
class bitmap
    auto_ptr<unsigned char> data;
    bitmap(string path);
#include "bitmap.h"
bitmap::bitmap(string path)
    data = auto_ptr<unsigned char> (new unsigned char [1024]);

auto_ptr is a class that wraps a pointer. Its instance being used without dynamic allocation, the instances are freed (after being destructed) when they are out of scope.

This simply allows the ~auto_ptr () destructor to call ‘delete’ on the wrapped heap object just like with an auto object: when it gets out of scope.

It allows us to write code like this – once again:

 bitmap icon = bitmap ("./icon");

and like this:

 data = auto_ptr<unsigned char> (new unsigned char [1024]);

That is because the assignment operator of the auto_ptr transfers ownership of the wrapped object, NULL-ing the old reference, and because the right-hand expressions in the above two examples are not used further in the code.

You’re still fucked up if you write:

bitmap largeicon = icon;

since the right-hand object is left with a NULL reference!

Introducing shared_ptr<T>

shared_ptr is a class that boost provided long time ago, and now will be part of the upcoming C++ standard (C++09 probably, but currently named C++0x).

This is, one way or another, already supported in the upcoming Visual C++ 9 SP1 (today as a beta feature pack) and also in GNU g++ 4.x

The simple fact that this feature, now in the standard, can be provided by a library tells something about the power of C++. Unfortunately, the fact that the boost implementation is unreadable tells another thing – about C++ compilers. (to think about it, what other languages have as many compilers – and compilers’ problems – as C and C++?)

Basically, shared_ptr is counting the references to a pointer, and, when copied, increments the references, and when destructed, decrements their number. Finally, when no more references exists, it calls ‘delete’.

So our pointer-free source (sic!) becomes:

#include <string>
#include <memory>
using namespace std;
using namespace tr1;
class bitmap
    shared_ptr<unsigned char> data;
    bitmap(string path);
#include "bitmap.h"
bitmap::bitmap(string path)
    data = shared_ptr<unsigned char> (new unsigned char [1024]);
#include "bitmap.h"
int main (int argc, char * argv[])
    bitmap icon = bitmap ("./icon");
    bitmap largeicon = icon;

If read up until here, you have just seen the way to aquire the memory resource on instantiation, so that you don’t need to manage it’s release.

TR1 has other new things too.. next time we’ll check on the <functional> classes function, bind and result_of.

(to compile the above in g++ 4.x, use #include <tr1/memory> and using namespace std::tr1;).


Written by vlad

March 12, 2008 at 3:32 pm

Posted in trivia

how gtkaml works

with 5 comments

If you are writing something based on GTK+ / GObject then you should be interested by this:

  • Vala is a very productivity-boosting language based on GObject OOP-ness, which translates to C and therefore can export GObject classes and interfaces from shared libraries.
  • gtkaml is a thin SAX Parser on top of Vala that allows you to write XML user interface descriptions

This is how a minimal Vala class described with gtkaml looks like:

<VBox class:name="MyVBox"
      xmlns="Gtk" xmlns:class="">
        <Label label="Hi_story"
               expand="false" fill="false" padding="0" />

This code creates a class named MyVBox that extends VBox and contains a Label. The label has the value “History”, it does not expand or fill its box and is not padded.Easy, no?

But GtkLabel doesn’t have expand, fill, or padding properties! I hear you say. Yes, but the pack_start () method has them as parameters.

Which leads us to the first subject:

Container Add Methods

gtkaml uses a file named implicits.ini to determine which containers have which add methods. This is for “implicit” decisions it makes based on your UI layout.

For the example above, it simply finds this:

adds = pack_start;pack_end;pack_start_defaults;pack_end_defaults

This simply lists all the functions that one can use to add widgets to a Box and to a Container. Since VBox is a Box and Box is a Container, gtkaml finds these two entries ‘significant’ and merges them in this order (most specialized first):


Then it loops over these methods – in this order – finds the first matching one and ‘picks’ the parameters from the child widget tag: that is, it removes “expand”, “fill” and “padding” from the Label and makes a note to use their value when adding the label in the VBox.

What if I want to use another add method?

Well, in that case simply specify the method’s name as an attribute of the child tag, with the value “true”:

<Label pack_end="true" label="Hi_story"
               expand="false" fill="false" padding="0" />

Creation methods

In this same example we notice that the label contains an underscore: this is intended to show up as a “mnemonic” (an keyboard shortcut) or simply as “History”.

Looking again at the GtkLabel documentation we notice that the only ways to get a mnemonic is to use either gtk_label_set_text_with_mnemonic () or gtk_label_new_with_mnemonic (). But since gtkaml can only help you with public fields, properties and signals, and not with function calls, how does one specify a mnemonic?

The answer is that you can select a “creation method”, and gtk_label_new_with_mnemonic () is not an ordinary function but a creation method. That is, a method that does not require the object as the first parameter but returns a new object.

So simply specify the creation method name as an attribute with a value of “true”: with_mnemonic=”true”.

Wait, but how about the creation method’s parameters? with_mnemonic has one parameter named str..

Well, usually Gtk widgets’ creation methods have their parameters named after the field/property they are initializing. gtkaml recognizes them from the specified attributes.

In this case, though, str is not a field or parameter of GtkLabel. But we know that it actually refers to the label property.

So what gtkaml does is to specify, again, in implicits.ini, the attributes that will go as parameters to the creation method:

new = label
new.with_mnemonic = label

So the code becomes:

<Label pack_end="true" with_mnemonic="true" label="Hi_story"
               expand="false" fill="false" padding="0" />

That’s it! – more on what gtkaml 0.2 will do for you in a future article.

p.s. as I am writing this, gtkaml was accepted on! yay!

Written by vlad

February 7, 2008 at 3:06 pm

Posted in gtkaml, trivia

(basic) functional programming in C++

leave a comment »

(update: simplified expression)

So I’m (re) learning C++. And would like to point out some functional language features found “out of the box” – although using boost::lambda or boost::bind you could get nicer ones, or waiting for C++0x would be another option…

This came to me while reading the wikipedia article on functional programming , which basically gives this example (in python I think):

# functional style
# FP-oriented languages often have standard compose()
compose2 = lambda F, G: lambda x: F(G(x))
target = map(compose2(F,G), source_list)

And the tag-line:

In contrast to the imperative style that describes the steps involved in building target, the functional style describes the mathematical relationship between source_list and target.

To begin, let’s have a look at an imperative version that I coded in C++:

vector<string>& imperative_version (vector<string>& source_list)
    vector<string> *target = new vector<string> ();
    string trans1, trans2;

    for (vector<string>::iterator item = source_list.begin ();
        item != source_list.end (); item++) {
            trans1 = G (*item);
            trans2 = F (trans1);
            target->push_back (trans2);

    return *target;

Pretty long, isn’t it? Besides defining type for the elements of the ‘list’ (I used a vector), and allocating memory, you can see the ugliness of the iterator type and.. well.. the imperative for loop with calls to the F and G functions.What I did was that I shortened everything down to:

vector<string> target = map<string>(source_list, compose (F, G));

What this code does is to call a function named map() that receives a vector and a function, calls the function on each element of the vector and returns a new vector with the results.Exactly like in the functional programming example, the functions F and G are composed so that the actual transformation is target[i] = F(G(source[i])).Let’s look at another example:

vector<int>target_int = map<int>(source_list, compose (len, F));

So, how is this implemented? compose2 is a functor: it is actually an object that has the () operator overloaded. And here’s the class definition for it:

template <typename input_type, typename intermediate_type, typename return_type>
class compose2 {
    return_type (*f)(intermediate_type);
    intermediate_type (*g) (input_type);
    compose2( return_type (*F)(intermediate_type), intermediate_type (*G) (input_type))    :f(F), g(G) {}
    return_type operator() (input_type input)
        return (f(g(input)));

What it does is that it requires two functions when the constructor is called and, upon calling the () operator, evaluates them.We cannot use compose2 directly without specifying the input type for the G function, the input type of the F function and last, the return type of the F(G()) function.

But we can make the compile infer them by wrapping everything in a function template, that has the ability to better deduce the type arguments:

template <typename input_type, typename intermediate_type, typename return_type>
compose2<input_type,intermediate_type,return_type> compose (return_type (*F)(intermediate_type), intermediate_type (*G) (input_type))
    return compose2<input_type,intermediate_type,return_type> (F, G);

The compose2<>() statement is a call to the compose2’s constructor. It returns a compose2 instance ready to replace a function.

Then there’s the map() function that applies a function to a vector, using the transform() algorithm:

template <typename out_type, typename in_type, typename functype>
vector<out_type>& map (vector<in_type>& in, functype f)
        vector<out_type> *target = new vector<out_type> (in.size ());
        transform (in.begin (), in.end (), target->begin (), f);
        return *target;

The out_type has to be specified because it cannot be inferred.(tested with MSVC 2005 and g++ 3.4.5 (mingw) and g++ 4.1.5)

Next time, an example with Boost or with TR1;)

Written by vlad

January 31, 2008 at 4:07 pm

Posted in trivia

what happend to overwrite mode?

leave a comment »

Two kinds of cursor image were used in the beginning of terminals:

Some may think that this is quite the opposite, since the command prompt from today’s and yesterday’s Windows is the other way around:

this is the insert mode And this is the replace mode: commandcomreplace.png

You can switch to the old-fashion prompt, in Windows 2000/XP by setting cursor size to Large in the window’s properties.

this is the insert mode And this is the replace mode:
insert-mode-2.png overwrite-mode-2.png

Although rarely used, this “overwrite” mode is very useful sometimes. This is why windowed application continued to provide it, signaled through a little status bar “led” like this one:


To activate “OVR” just press the Insert key..

Now for the question: what happend to overwrite mode in Word 2007?

First, it isn’t there: you type Ins and nothing happens. Nor does something else happen (Insert isn’t bound to another action).

Second, you can turn it on in only a 3 steps, but I’d recommend ticking “Use the Insert key to control overtype mode”

Third, if you want the “led” you have to right-click on the status bar and tick “Overtype”:


This is awkward: it’s like, what will be disabled next? the Del key? or the Tab one?

Written by vlad

December 17, 2007 at 10:46 am

Posted in morons, trivia

Simple UI enhancement

leave a comment »

Good software has keyboard shortcuts. This way, if you use it often, you can become more productive (by not leaving the keyboard to reach for the mouse).

This is one of the reasons I love Total Commander and I hate windows explorer: the first has shortcuts for 99% of the things you can do, the latter has only some shortcuts, and it incredibly slow at processing them.

Another thing I love about commander clones is that I don’t have to learn too many new keyboard shortcuts (e.g. F6 was Ren/Move in NC ten years ago, shift-F6 is the new shortcut for in-place renaming in TC).

But no matter how many shortcuts you learn, you will still meet a software that needs you to redefine keys.

Redefine Keys

This option was necessary in 5-keys-arcade-games as is still necessary in 200-shortcuts word processors.

And it has progressed until Office and it’s “Customize Keyboard” dialog:

Customize Keyboard

But Office is a software that everybody (I think) has used some time or another, and most of us know it’s keyboard shortcuts already. But as a programmer I also used Visual Studio – before.

And today I am using Anjuta, a GTK programming environment, and I have the Auto Complete keyboard shortcut redefined from Ctrl-Enter to Ctrl-Space. How did I did that?

Simply opened Edit and selecting AutoComplete… and press Ctrl-Space. That’s it!
initial-autocomplete-setting.png redefine-keyboard.png

Ta-da..! The unassigned shortcut key is assigned directly to the selected option for you;)

(there’s another catch, though: careful what you type when you open a menu… :-D noticed the shortcut I accidentally set for Undo?)

Written by vlad

December 12, 2007 at 9:11 pm

Posted in trivia

slackpkg vs. swaret vs. slapt-get

leave a comment »

Long time ago I remember myself searching which one of these is best as a remote-mirror-package manager for Slackware.
There are three flavours, excluding the provided pkgtools :
1. slackpkg
Provides the exact features of installpkg/removepkg/upgradepkg but you can use a ftp/http/etc mirror. No dependencies et Co.

2. swaret
Has the same commands as slackpkg (update brings the file list up-to-date, then upgrade, install or remove, after a search)
The difference is that, after installing the files, it runs ldd against each binary (executable or library) and if it catches some missing libraries, searches through the file list of the mirror again and offers itself to install those packages too.

3. slapt-get
The same as slackpkg, but, against Slack’s phylosophy, uses a dependency list as a metadata for the .tgz itself. You can see here what I’m talking about.

My advice: swaret, because it installs from network, just as slackpkg, and resolves missing libraries. Not dependencies written by some fool human..

Also, do not install programs from sources just like that. Download checkinstall, and instead of making
sudo make install

do a
./configure --prefix=/usr
sudo checkinstall

after you set PAK_DIR="/builds" in your etc/checkinstall/checkinstallrc file (and of course, after creating that directory).

That way you will have .tgz’s ready for redistribution or uninstall;)

Written by vlad

November 5, 2006 at 1:03 pm

Posted in trivia

fuser on win32

leave a comment »

In case you were wondering if there’s a fuser.exe utility (just like I did today), for native windows programs (not the cygwin-only port), has the answer, of course: handle.exe, which manages to do exactly what fuser does.

Good luck with “safely removing” your hardware, now!


C:\\>handle -u c:\\WINDOWS\\system32\\config\\SAM
Handle v3.11
Copyright (C) 1997-2005 Mark Russinovich

Sysinternals -
System pid: 4 NT AUTHORITY\\SYSTEM 164: C:\\WINDOWS\\system32\\config\\SAM
System pid: 4 NT AUTHORITY\\SYSTEM 48C: C:\\WINDOWS\\system32\\config\\SAM.LOG

(P.S. Contratulations for the guys at SysInternals for “Process Explorer” and “Handle”, too bad they haven’t named it “fuser.exe” to show up in a common search…)

Written by vlad

May 11, 2006 at 10:03 pm

Posted in trivia