syntax highlight

Thursday, 19 May 2016

I can't believe this works!

Are you bored? Try pasting this, as is, in a cpp file:

// What is going on here??/
Is this even legal C++??/
Yes, it is!

NB: You may have to use -trigraphs to compile this. Try it out! You can use this command:

echo -e "// What is going on here??/Is this legal C++?" | g++ -E -c -trigraphs -

With some luck, this won't be legal C++ anymore after C++ 17 deprecates trigraphs.

Tuesday, 17 May 2016

Some sane advice from Firefox's console

Tinkering with Firefox' JS console I had to copypaste some stuff. I got a really nice surprise when it wouldn't let me:

Scam Warning: Take care when pasting things you don't understand. This could allow attackers to steal your identity or take control of your computer.


That's some really good advice coming from your browser's console.

Thursday, 12 May 2016

Quickly sharing files in Linux via HTTP

Isn't it awful when you have to share a file too big for email and don't know how? You'd think by 2016 we'd have that figured out. Actually we do, many times over. Just pick a standard that works for you!

If you don't want to read many pages on file transfer standards (Samba? What's that?) you can try this little snippet:

python -m SimpleHTTPServer $PORT

This will create an http server sharing the current directory. HTTP, luckily, is one of those things that tend to work everywhere, always.

Bonus: some other ways of doing the same thing at https://gist.github.com/willurd/5720255

Tuesday, 10 May 2016

Initialization oddities: Aggregate initialization

Do you know the quickest way to create a constructor that initializes the elements in this struct?

#include <string>
struct MyStruct {
    int x;
    std::string y;
    const char *z;
};

If you answered "by typing really fast", you may be interested in knowing that the fastest way to create this constructor is to not write it at all!

MyStruct a = {42, "Hello", "World"};

Yes, the line above works and it's perfectly legal C++. It's event C++ 98! This language feature is called aggregate initialization and it says the compiler should be smart enough to initialize MyStruct using each value successively. Of course C++11 has made this syntax somewhat simpler and a lot more uniform:

MyStruct a{42, "Hello", "World"};

There are some caveats when using this initialization, namely that the initialized type must be an aggregate. An aggregate, in standard lingo, is a type that has some restrictions. No virtuals, no privates, etc. You can say it's a POD and in most cases you'd be right.

Now, is this also legal?

MyStruct a = {42, "Hello"};

You'd be tempted to say that's a syntax error. It's not, now z will just be default-initialized. What about this, then?

MyStruct a = {42, "Hello", "World", "Extra!"};

According to the standard, that's an error. Or... is it? Let's try out this example:

struct A {
    int x;
};

struct B {
    A a;
    std::string y;
};

struct C {
    B b;
    const char *z;
};

C o = {42, "Hello", "World"};

Yes. Believe it or not, the object o will now contain three members: o.b.a.x, o.b.y and o.z. All three will be properly initialized with their respective value.

Aggregate initializations should, according to the standard, be smart enough to initialize aggregate objects and use any "spill over" to continue initializing other values/aggregate objects recursively.

Bonus I:

Aggregate initialization is also what makes this idiom valid:

char x[] = {1, 2, 3}

In this case, x will be of length 3 because that's the length of its aggregate initializer.

Bonus II:

I'm sure anyone trying to get up to date with C++11 will have played around with variadic templates. One of the first exercises I'd recommend for this would be a compile-time list of different types. Knowing about aggregate initializations now, how would you write a constructor for this type?

template <typename H, typename... T>
struct Multilist<H, T...> {
    H x;
    Multilist<T...> next;
};

Multilist<int, string, float> foo{42, "XXX", 1.23};

Friday, 8 April 2016

Code and Google translate: awesomeness

Some time ago I found out one of my articles was translated to another language (yay for that, woo for not letting me know about it). To understand what my own article said, I had to use Google translate on the site. Guess what? c++ and Google translate can produce hilarious results:


# The include "throw.h" the extern "the C" {void seppuku () {throw statement the Exception () ; }}

Another one I liked:


the struct the Exception {};
#ifdef __cplusplus
  the extern "the C" {
#endif

void seppuku (); # Ifdef __cplusplus } # endif

Now you know it. Next time you're looking at some incomprehensible c++ code, run it through Google translate. It may improve it.

Tuesday, 5 April 2016

Ubuntu 15.10: Ubuntu ME

Warning: semi-useless rant ahead. TL;DR: Avoid Ubuntu 15.10 - it's the closest Linux has ever been to Windows ME.

I have been using Ubuntu for a while now. From the time when Canonical actually mailed real, physical CDs of the distro. So get of my lawn.

In all of my Linux years I have never, ever, had such a horrible installation experience as I did this weekend with Ubuntu 15.10. I may go as far as saying not even Windows ME was this horrible to install. I hit dozens of critical show-stopper bugs, from poor UEFI support to an installer that crashed when clicking "Go back". And that's only the installation, don't get me started on the new KDE Plasma 5 desktop... (hint: my big desktop screen is NOT a phone. Swiping to login? Bad idea for a mouse).

A few hints for any other poor souls that made the fatal mistake of installing Ubuntu ME:

  • UEFI? Say no. Get a different computer if you can. Try to set it in legacy mode if you can not.
  • Try not to repartition and install Ubuntu on the same go. Even more so if you have UEFI. First install, then rearrange partitions with a live cd.
  • If you get a few (or a few dozen) "system crash notifications" when starting up your GUI, check /var/crash. Delete everything from there.
  • If you want Kubuntu, don't install Ubuntu and then apt-get install kubuntu-desktop. That's broken. If you want Kubuntu just get its install image.
  • Don't install Kubuntu. Really, it's horrible and it crashes. (You though I called 15.10 Ubuntu ME for no reason?)
  • Don't like Gnome? XFCE is usable and can be configured to look more or less like a sane version of KDE. It still crashes but at least it's quick to boot.
  • If you get a disk check on every startup just disable it on fstab. No, it's not nice. I haven't found any other workarounds yet.
I have no idea when has Ubuntu gone so horribly bad, but I'm not looking forward to installing any Ubuntu distro anytime soon. I wonder what Slackware looks like these days.

2016? Still not the year of the Linux desktop.

Update: XFCE is great... except it doesn't really support moving the mouse. Seems Ubuntu is having a nostalgic release and decided to introduce old bugs from 2012!

Thursday, 24 March 2016

Gimple

Lately I've been toying around with gcc to learn a bit better how its optimization phases work. Understanding Gimple, the intermediate representation used by gcc, is a useful skill for this. Of course actually *understanding* it is quite an ambitious and daunting task, so it may be a bit more useful to skim through it.

Turns out that using -fdump-tree-all and -fdump-rtl-all its possible to get a lot of interesting information on the phases the compiler follows to get your code optimized, but the sheer amount of information produced makes it rather hard to make sense out of it. During the next few posts (weeks? months? probably until I satisfy my curiosity about gcc) I will be investigating a little bit the output of the -fdump options in gcc, to see what can be learned from it.

Thursday, 3 March 2016

Vim tip: Replacing builtin commands

If you spent a day writting a cool new version of the "tabnew" Vim command, you'll probably want it to be the default command used to open new tabs. Right?

Luckily, there's an easy way to replace built in commands with custom ones: cabbrev. cabbrev will do a textual replacement, so if you add "cabbrev tabnew TabNew" to your vimrc, eachtime you type "tabnew" it will be translated to TabNew.

Bonus tip: The command is actually, "abbrev", not "cabbrev". The "c" stands for command: it's telling Vim that you want the abbrev command applied in command mode. You can also use it as "nabbrev" to have it applied in normal mode. "abbrev" it's a nice way to correct common typos!

Tuesday, 1 March 2016

Public service announcement: searching your terminal's output

Short tip today, but a life-changer one: you don't need to copy&paste your terminal's scrollback to search on it, you can do it in place. At least in terminator that's possible (and I hear it's also doable in Gnome's default terminal application). Just press Ctrl+Shift+F. No more copy and pasting to vim!

Thursday, 25 February 2016

Vim tip: autocommands

Whenever you find yourself thinking "I wish Vim could do this automagically for me", you probably are thinking about autocommands. With autocommands, autocmd for short or au for lazy people, will let you tell Vim, "Hey, use this callback when an event occurs".

The basic structure is pretty simple: "autocmd Event FileType Action". So, for example, "autocmd BufEnter *.txt call Rot13()" would tell vim to set a callback on BufEnter, that is whenever you change buffers, for all *.txt files, which will rot13 your text. Feel free to use this for actually useful things, like spell checking or auto indenting.

Tuesday, 23 February 2016

Bash tip: idiom to get the first error code from a pipe

When writing a bash script, often times you'll end up with something like this:

real_command | filter_stuff | prettify | do_something_else

The problem arises when you try to figure out if your command succeeded or not. If you `echo $?` you'll get the return code for the last chain in the pipe. You don't really care about the output value of do_something_else, do you?

I haven't found a solution I really like to this problem, but this idiom is handy:

out=`real_command` && echo $out | filter_stuff | prettify | do_something_else
echo $?

Now $? will hold the value of real_command, and you can actually use it to diagnose the real problem.

Thursday, 18 February 2016

smaps: A quick memory analysis

Many times you see your process' memory consumption skyrocketing even though you're quite certain you have no memory leaks. This usually marks for the beginning of a very lengthy debugging process with valgrind or a similar tool, but even so some times you might get stuck trying to debug some third party library.

There's a quick tip in Linux that can help you track down a lib gone haywire:

cat /proc/<pid>/smaps

smaps will report every mapped section of memory for a certain process, how big the memory allocation is and which binary created the allocation.

Tuesday, 16 February 2016

Some new set operations in C++11 stl

The std header has a few cool additions that make life easier in C++11:

void f() {
  vector<int> v = {1, 2, 3, 4, 5, 60, 70, 80, 90};

  auto less_than_10 = [](int x){ return x < 10; };
  if (all_of(v.begin(), v.end(), less_than_10)) {
    cout << "Yay!";
  }
}

Besides all_of, in you can also find any_of and none_of.

Bonus: do you find that initializer list hideous? Just use std::iota, from stl too:

vector<int> v(100, 0);
iota(v.begin(), v.end(), 0);

Friday, 12 February 2016

Goto hell

Small and funny easter egg I found by accident today: stop using "adb shell" to access your device. You're wasting precious keystrokes. Instead, you should be using "adb hell". Yes, 'adb hell' works just as well as 'adb shell' - but it's even more awesome. Go and try it!

Thursday, 11 February 2016

PSA: OEM unlocks may result in wiped filesystems

o, I bricked my tablet. Turns out the bootloader couldn't mount /data: after doing an oem unlock thingy, /data gets wiped and (this is the part the manual I was following didn't warn me about) no filesys is created.

If this happens, go back to recovery mode, then adb shell and run 'mount /data'. This will give you an error like "Can't mount /dev/block/mmcblk0p23". Write down the /dev/block id and run 'mke2fs -t ext4 /dev/block/mmcblk0p30'. That should fix it.

In some systems you may be missing libext2_quota.so. If this happens, just look for libext2_quota.so in the interwebs, then adb push this file into /sbin.

Tuesday, 9 February 2016

KDE: Lock screen from CLI

For some reason, one of my (seriously outdated) Kubuntu installations has the nasty habit of not locking the screen when pressing Ctrl+Alt+L. Not always, though. It seems to do this only when I'm in a hurry and need to quickly lock my PC before walking away. This happens often enough to be annoying, but not so frequently as to bother me enough to look for a proper solution. Instead of looking for a proper solution, trying to determine what's stealing the focus of the Ctrl+Alt+L key command, I just settled for an easier workaround: lock the screen from the command line. I use the terminal most of the time anyway, so why not just use it to lock the screen as well? The magic incantation is easy, if a bit cryptic at first:
qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock
"qdbus" is a broadcasting service for KDE (Qt, actually). This command basically tells the screen saver service to lock the screen. Works every time, and with an alias in my bashrc, I don't need to remember that horribly long command. Now I only need to determine if my computer detecting when I'm in a hurry is a sign of sentience, and whether this is a threat to mankind. Will report soon.

Thursday, 4 February 2016

VLCFreemote: no need to leave the couch

I've been quite prolific in my Github account recently, if I may say so myself. The latest of my open-source projects which I think is more or less ready to be "released to the world" is VlcFreemote, a remote control for VLC in Android. From its README file:

How many times have you been comfortably watching a movie from the couch only to find out you forgot the subtitles? How about being snugly tucked under a blanket, only to find out you need to brave the cold of winter just to add a new episode of your latest binge-watching series? Yeah, that can easily ruin your day.

Worry no more: with VlcFreemote you can now install a tiny Android app to control your VLC server.

FAQ:

  • Another VLC remote? Why?There are a few VLC remote controls out there. I think this is the only once that's open source (not 100% sure). It has some nice extra features I haven't found in other remote controls too: bookmarks, automagic movie-skip (jump forward by a percentage of the file length, much more useful than it sounds!) a compact layout and other small things probably not even worth mentioning. In the future, whenever I get some free time, I'd like to add the ability to start VLC automatically from SSH, a feature I would use a lot and I have seen nowhere else.
  • Why isn't this in Google play?Mostly cause I'm lazy and cheap. Getting a Google Play account costs 10 dollars or so, and I'm too lazy and too cheap to get one. Want me to upload it to Google Play? Feel free to buy me a beer. If not you can just get the APK from Github, or download the source code and build it yourself.

Tuesday, 2 February 2016

Don't exit gdb just to run make!

f you're more or less successful in your debugging session, it's quite likely that you'll have to modify some source code so you can actually fix a bug. And if you're more or less careful, you might want to validate your changes actually work. We saw some time ago that you don't need to restart gdb after a recompile because gdb is already smart enough to know that the binary changed.

Turns out you don't even need to drop from gdb to a shell: just type make (using the parameters you'd usually call make with) and watch gdb take care of building your binary again.

Rebuilding your project like this is not only useful to save time: you can also keep your breakpoints and they should still make sense, assuming you didn't refactor your code too much.

Thursday, 28 January 2016

On the poor state of geotagging applications for Linux

tl;dr

I hacked together IMGeotagger, a Geotagger for Linux (though it should work in Windows too) that uses Google maps.

Not-so-tl;dr-version

Recently, after coming back from a trip, I tried to geotag (*) my pictures. I don't have a fancy GPS device for my camera but I do have a fairly good memory. There are applications that will let you drop your pics to a map, then get the GPS coordinates out of that. Unfortunately, the current state of geotagging applications in Linux is just sad.

Gotten Geography mostly works. I don't find it very nice to use, though. Pictag doesn't even work anymore, although I have hacked a version which at least manages to start in modern Ubuntu setups. That puts it more or less at the same level as Gotten Geography. Both suffer from a fatal problem: there is no latin charset maps for places that don't use a latin alfabet. Now, this is clearly not a fault in either program.

Both Gotten and Pictag use the (incredibly awesome) Open Street Map project. OSM provides some default map rendered tiles, and those are in the "local" language. Transliterating the local written name of a street is not an easy task. The rules in each place are completely different, some places have a completely different name in latin chars than they do in the local alphabet and a million other problems that can't be solved as a general case.

What to do when there are no readily available OSM tiles with latin chars? There is a fairly good product that does provide latin names for most (all?) places in the world: Google maps. Now, there is a reason neither Gotten nor Pictag use Google maps for geotagging: Google maps has no (free?) API to get tiles which you can embed in an application. It does let users view their maps in a browser, though. And the map URI is a nice and easy way to translate from map-tiles to map-coordinates.

I'm not 100% sure if IMGeotagger falls under Google maps terms of use, so I may have to take it down in the future. What it does is pretty simple: you use a browser to select a place, then IMGeotagger retrieves the location from the URI of the browser. This will break when Google maps changes their URI structure; until then, IMGeotagger works pretty well and it uses a really nice map (sorry OSM, G. Maps are pretty good).

You can grab the IMGeotagger (and its source code, as it's open source) from https://github.com/nicolasbrailo/IMGeotagger.

(*) What's geotagging? That's adding GPS coordinates on the exif metadata of your pictures. This is only useful to nerds and very pedantic people who enjoy analyzing photo albums to get GPS plots and other nerdy things like that.

Tuesday, 26 January 2016

gdb-tui and the previous-command problem

Raise your hand if you have run gdb in tui (graphical) mode, only to find you can't refer to the previous command when pressing "up". I can't see you but I know this is true for pretty much everyone reading this blog. All three of you.

In the gdb-TUI mode, the arrow keys are used by the active window for scrolling. This means they are not available for readline, the component that takes care of the magic invocations needed to bring back the previous command from the land of the dead. Luckily there are alternative readline keybindings: just try C-p, C-n, C-b and C-f. Takes a while getting used to it but you can finally use gdb-TUI and forget about copy-pasting every gdb command.

Bonus tip: if pressing "up" (or C-p) in gdb doesn't bring back the previous command, it probably means you don't have the readline package installed. Go ahead an install it. It'll change your life.