2016-08-03 09:43

Making Emacs set the indentation style per file

Working with mixed C code bases I often run into problems with different coding styles being used at the same time in the same project. Different open source components use different philosophies, and there may even be different styles inside the same subsystem depending on the individuals that wrote the code etc.

The .emacs config file is suitable to use for setting your personal default style preferences, and it can be used to set styles per directory using matching logic etc.

There are a few C indentation styles built in into Emacs: “gnu”, “k&r”, “bsd”, “whitesmith”, “stroustrup”, “ellemtel” and “linux”. Keep to one of these to be compatible with stock Emacs installations.

In addition to this you also need to set the indentation depth and mode to use the TAB character or some specific amount of spaces.

There are two ways to set the c-style per file using special comment sections in the source code, a compact way and a more verbose variant.

The compact way requires that you make a special comment as the first line in the C source code. To set the "linux" style and the TAB character, use this as the first line:

/* -*- c-file-style: "linux"; indent-tabs-mode: t; -*- */

Another example with "ellemtel" and 3 space indentation depth:

/* -*- c-file-style: "ellemtel"; indent-tabs-mode: nil; c-basic-offset: 3; -*- */

The verbose way makes it possible to put a comment block somewhere in the source code, it does not have to be first in the file. I prefer putting it at the end of the file. Example:

/* Local Variables: */
/*   c-file-style: "linux"; */
/*   indent-tabs-mode: t; */
/* End: */

It is also allowed to use fancier comment formatting like this:

/**
 * Local Variables:
 *   c-file-style: "ellemtel";
 *   indent-tabs-mode: nil;
 *   c-basic-offset: 3;
 * End:
 */

Note that you need to reload the source file when you have added this kind of comment to actually make Emacs activate the settings for the buffer. You can use "M-x M-v" followed by ENTER to reload the current file.

The GNU Emacs manuals has a section about Specifying File Variables.

2015-06-29 22:41

Installing Windows 10 IoT on a Raspberry Pi 2 without a Windows computer

Yes, I had to try it.

Not very useful though, as the IoT install is just a base for putting apps on. No browser etc. You'll need a Windows machine and Visual Studio to do anything useful.

But.. this is how I did it:

I reused an old micro SD card, put it into my card reader. Ubuntu auto-mounted and opened up the old partitions in the file browser automatically. You should NOT use the unmount button in the graphical file browser to unmount them as this also disables the card by doing a size change of the device to 0 size. You can not copy to the card if this is done.

But instead check the last couple of lines in "dmesg". On my machine:

moggen@moggen-pc:~$ dmesg

... a lot of lines outputted ...

[   47.100287] sd 6:0:0:2: [sdd] 31356928 512-byte logical blocks: (16.0 GB/14.9 GiB)
[   47.101789] sd 6:0:0:2: [sdd] No Caching mode page found
[   47.101790] sd 6:0:0:2: [sdd] Assuming drive cache: write through
[   47.104054] sd 6:0:0:2: [sdd] No Caching mode page found
[   47.104055] sd 6:0:0:2: [sdd] Assuming drive cache: write through
[   47.105341]  sdd: sdd1 sdd2
[   47.340525] FAT-fs (sdd1): Volume was not properly unmounted. Some data may be corrupt. Please run fsck.
[   47.383595] systemd-hostnamed[3650]: Warning: nss-myhostname is not installed. Changing the local hostname
might make it unresolveable. Please install nss-myhostname!
[   48.607431] EXT4-fs (sdd2): recovery complete
[   48.612857] EXT4-fs (sdd2): mounted filesystem with ordered data mode. Opts: (null)

I can see that /dev/sdd is my SD card. I unmounted the partitions manually:

moggen@moggen-pc:~$ sudo umount /dev/sdd1
moggen@moggen-pc:~$ sudo umount /dev/sdd2

Now the card is ready. You need of course the Windows 10 IoT ISO image. Get it via this page http://ms-iot.github.io/content/en-US/Downloads.htm Get the "Windows 10 IoT Core for Raspberry Pi 2" image, click Download. The current file is about 508 MB (when this is written).

You need to install the excellent 7-Zip software on your Ubuntu machine. Run this if you don't have it already:

moggen@moggen-pc:~$ sudo apt-get install p7zip-full

Make a temporary directory somewhere and put the downloaded ISO file in it.

moggen@moggen-pc:~$ cd Downloads/
moggen@moggen-pc:~/Downloads$ mkdir temp
moggen@moggen-pc:~/Downloads$ mv IOT\ Core\ RPi.ISO temp/

Unpack the ISO with 7z:

moggen@moggen-pc:~/Downloads$ cd temp
moggen@moggen-pc:~/Downloads/temp$ 7z x IOT\ Core\ RPi.ISO 

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,4 CPUs)

Processing archive: IOT Core RPi.ISO

Extracting  Windows_10_IoT_Core_RPi2.msi

Everything is Ok

Size:       532140032
Compressed: 532776960

Unpack the MSI with 7z:

moggen@moggen-pc:~/Downloads/temp$ 7z x Windows_10_IoT_Core_RPi2.msi 

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,4 CPUs)

Processing archive: Windows_10_IoT_Core_RPi2.msi

Extracting  DISM_api_ms_win_core_apiquery_l1_1_0.dll
Extracting  DISM_api_ms_win_downlevel_advapi32_l1_1_0.dll

... more files ...

Everything is Ok

Files: 28
Size:       1235566696
Compressed: 532140032

Among the files extracted there is a big file called: File_WindowsIoTRpi2Flash.ffu. This is the file we are interested in.

The FFU format is a special image file that Microsoft uses and contains checksums and other useful stuff. But we want a raw image to put directly on the SD card without having to use the DISM tools on a Windows machine. Luckily T0x0 has made a converter in Python: https://github.com/t0x0/random/wiki/ffu2img.

Get the script with wget:

moggen@moggen-pc:~/Downloads/temp$ wget https://raw.githubusercontent.com/t0x0/random/master/ffu2img.py
--2015-06-29 22:03:19--  https://raw.githubusercontent.com/t0x0/random/master/ffu2img.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 23.235.43.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|23.235.43.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 6243 (6,1K) [text/plain]
Saving to: ‘ffu2img.py’

100%[======================================>] 6 243       --.-K/s   in 0s      

2015-06-29 22:03:19 (614 MB/s) - ‘ffu2img.py’ saved [6243/6243]

Run the script to generate a raw image from the FFU file:

moggen@moggen-pc:~/Downloads/temp$ python ffu2img.py File_WindowsIoTRpi2Flash.ffu img.raw
Input File: File_WindowsIoTRpi2Flash.ffu
Output File: img.raw
Block data entries begin: 0x800f8
Block data entries end: 0xa4c98
Block data chunks begin: 0xc0000
9401 blocks, 1203328kb written - Delay expected. Please wait.  
Write complete.

Use DD to put the image on the SD card. IMPORTANT: use the device you found with dmesg above. You can wipe your linux system if you use the wrong device with this command! ADJUST this command to use the device of the SD card on YOUR machine!!

moggen@moggen-pc:~/Downloads/temp$ sudo dd if=img.raw of=/dev/sdd bs=1M
7372+1 records in
7372+1 records out
7730495488 bytes (7,7 GB) copied, 601,936 s, 12,8 MB/s

This took about 10 minutes on my system and my micro SD card (a Transcend Ultimate 600x, 16GB). It may be faster or slower on your setup.

Assure that all bits and bytes are actually written to the card before removing it

moggen@moggen-pc:~/Downloads/temp$ sync

Now, remove the card from your reader, put it in a RPi2 and power it up!

2015-06-03 23:50

How to set up your own GIT server with Gitolite on a Digital Ocean virtual server.

Me and my business partners needed to set up our own GIT server to keep our source code repositories on. We considered putting the repositories at some home machine and allow the others to access it via internet, but after some considerations we decided to put it on a neutral place on-line instead. A good virtual server should be more reliable than our home networks and internet connections.

Our code is not open source, and we do not want to put it on GitHub. GitHub offer private closed hosting, but in the light of the recent problems with the Chinese government and their anti-campaign and DDOS attacks, we'd prefer to stay away.

We decided to set up our own Digital Ocean virtual machine for the purpose. They are cheap, seem reliable (we got friends using it and loving it) and they also offer backup of the virtual machine so we don't have to bother with that ourselves.

Registering an account and creating the virtual machine, called Droplets by DO, was pretty easy. You need to verify your mail and register a credit card or alternatively pre-pay with PayPal.

We chose the smallest sized virtual machine for $ 5 (USD) per month, and an additional $ 1 for adding scheduled backups of the machine. The smallest machine has 20GB storage, 512MB RAM and allows 1TB data traffic per month. This will be more than enough to host a small GIT server. You can always upgrade to more disk, RAM or bandwidth any time later.

We chose Ubuntu 14.04 64 bit as Linux distribution, and placed the server on a location in Europe (to stay away from NSA). Installing was extremely easy, you just have to select distribution, size, a name for the machine, the location and some settings if you require IPv6 etc. You can upload a SSH public key to be used for logging in as root when the machine is finished. It is also possible to get a root user password instead, and it is mailed to the contact address.

After a few minutes the machine was up and running. SSH was not accessible directly unfortunately. The standard installation only enables the SSH key authentication method, but I chose to get a password. Luckily there is a web based console interface where you can log on into your new machine and set things up.

First thing I did was to enable ssh password authentication. To do that you need to generate host keys for sshd. I made an ECDSA key first, but I had problems logging in from an older machine, so I also added an old school RSA host key as well at a later time. Anyway, I ran these commands (as root):

ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key
ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
service ssh restart

After this you may log into the machine using the password you got by mail. The virtual Ubuntu machine is pretty slimmed down by default, and netstat only reports port 22/SSH as listening. You need to do some standard sysadmin stuff, like change the root password, create a normal user for you and maybe others etc. I added my personal account to the sudo group, enabling the sudo command.

To get going with GIT and Gitolite you should install these software packages. Do this (as root or with sudo as here):

sudo apt-get install git gitolite

You need to add a user for Gitolite. The user name "git" seems to be used by many for this, so I took that as well

sudo adduser git

Just set some name or press enter on the questions and set a password. You can disable the password as it will never be used directly with:

sudo passwd -d git

You also need to prepare a SSH key pair that is used for administration of GIT with Gitolite. Use your existing .ssh/id_rsa.pub or create some new key for this purpose. The public part of the key needs to be uploaded to the server and put where the new git user can access it. You can for example upload and put it in /tmp/. Scp and sftp can be used as you have SSH running. The key file should be named as the user name you want for the admin user in Gitolite. You can only add one key initially for administration, but you can easily add more administrator keys later. I made a local key only to be used for administration of Gitolite, but you can use any public key you like. I named mine: /tmp/moggen-local.pub

Log in into the git account with:

sudo su - git

Make sure you can access the initial admin SSH key (in my case /tmp/moggen-local.pub), and run this:

gl-setup /tmp/moggen-local.pub

This will create some directories and files and create the admin database. Gitolite is actually using a special GIT repository for managing. You clone this GIT using SSH and that key you just installed the public part of, change files, commit and push. Gitolite uses GIT triggers to react to the changes, updating users, keys, access rights, adding new repositories, deleting and so on. Very clever.

I used my local account on the virtual machine itself to clone the admin GIT repository, but the procedure is the same for external accounts. You need the matching private SSH key identity on that machine and the account you are using. Clone using a command line like this:

git clone ssh://git@mygitserver.com/gitolite-admin

You need of course to add the machine IP number to your domain name if you want to use that. You can always go directly on the IP otherwise. The important things are that the user name is "git" (the git@ part of the URI), the name of the repository and that the SSH key authentication is working properly.

If all is well you will be able to clone the admin git. It is very simple initially and only contains two directories with one file in each. conf/gitolite.conf is the main configuration file. keydir/ contains the initial ssh public key for admin. In my case moggen-local.pub

The initial Gitolite config contains this

repo    gitolite-admin
    RW+    = moggen-local

repo    testing
    RW+    = @all

This says that the user (users are in essence SSH key files) moggen-local may read and write to the admin repository. There is also a playground repository called "testing" that all users have access.

To add users, add their public SSH key named as "username".pub in keydir/ Add the new user to a repository or add a new "repo" definition. That will create the GIT repository. Example of gitolite.conf when adding my home workstation SSH key and my friend Jakov to a repository called fungame.git, and allowing the user "build" to have read-only access:

repo    gitolite-admin
    RW+    = moggen-local

repo    testing
    RW+    = @all

repo    fungame.git
    RW+    = moggen jakov
    R      = build

To make things actually happening, add the new .pub key files and the changes to the gitolite.conf, commit the changes into GIT and do a "git push". The triggers in the admin git repo will pick up the changes and perform the necessary modification. If something goes bad, it will refuse to accept the commit when pushing. Find the error, commit, and re-push.

The newly created empty GIT repository can be checked out right away:

git clone ssh://git@mygitserver.com/fungame.git

Me and Jakov may push commits to this repository, but our automated build machine is prevented from pushing changes.

All GIT repositories created by Gitolite are equipped with special GIT triggers that check that users are allowed to access or push data. As long as Gitolite is used for creating, all will be good. But be careful if you manually add existing repositories directly to the file system in the git user directories. You need to initialize them so that the security triggers are created and the access control is enabled!! Please see the documentations about this.

There are lots of tricks you can do with Gitolite. Please see the home page for more information.

As an extra bonus, I also changed the port number on the GIT server so that SSH is not on the standard TCP port 22 but some other high port to avoid lame DOS attacks etc. This affects how you log in with SSH and the GIT clone URIs. To use for example port 12345:

git clone ssh://git@mygitserver.com:12345/fungame.git
2015-03-10 09:15

How to query your memory modules in Linux

Got this tip from a friend.

sudo dmidecode -t 17

Awesome!

2014-09-03 14:52

The MogBlog engine on GitHub!

Yes, A couple of my good friends recently persuaded me to publish my blog engine. I have kept it for myself up to now, as it was in my opinion missing key features, got some annoying bugs, not perfect.. and so on. Many of my projects reach this state and die in it.

So here it is at GitHub: https://github.com/tetryonreactor/mogblog/

I chose the ISC license for it. In my opinion a more free license than GPL. It is a freedom to be able to take the code, modify it and not have to publish the modified source code. The most free license is public domain, do whateva, but a little bit of vanity makes me choose ISC.

2014-08-07 16:01

Modifying an initrd file system

I needed to do this recently.

To unpack:

mkdir root
sudo chown root:root root
sudo chmod 775 root
cd root
zcat ../initrd.gz|sudo cpio -id

Do the alterations

To repack into a new image, current directory at root/:

find ./ | sudo cpio -H newc -o | gzip >../newinitrd.gz
2014-03-13 23:59

How to install Guitar Pro 6 on a 64-bit Ubuntu 14.04

I ran into some problems installing Guitar Pro 6 on my new 64-bit Ubuntu 14.04 (alpha) environment. GP6 is a 32 bit application, but I got in to trouble when I tried to install the required i386 packets in parallel. The 32 bit sudo was in conflict with the 64 bit variant, and so was other libraries like libgtop2-7.

I tried to install a virtual 32 bit environment using LXC, but I could not get pulseaudio to work over the virtualization boundary using that technique.

But finally I managed to get it running using schroot, a chroot helper system that can be run without sudo.

I wrote an instruction of how to do it:


Download the Guitar Pro 6 linux package. In my case it was saved as ~/Downloads/gp6-full-linux-r11621.deb

Make sure we got schroot and debootstrap

sudo apt-get install schroot debootstrap

Go to chroot config directory

cd /etc/schroot

Use sudo with your prefered editor and create chroot.d/trusty_i386.conf with this content, adjust the user names to match your local user:

[trusty_i386]
description=Ubuntu 14.04 Trusty Tahr for i386
profile=guitarpro
personality=linux32
type=directory
directory=/var/schroot/trusty_i386
root-users=moggen
users=moggen
preserve-environment=true
aliases=default

Clone the profile, we need to add to the fstab

sudo cp -a desktop guitarpro

We need to add a mapping for the pulseaudio sound system to work. Pulseaudio uses socket files inside /run/user/<your-uid>/pulse/

Sudo edit guitarpro/fstab and add this line last:

/run/user      /run/user       none    rw,bind         0       0

Create the directories for the virtual root

sudo mkdir /var/schroot
sudo mkdir /var/schroot/trusty_i386

Make a bootstrap install of Ubuntu 14.04 inside the virtual root. Please use your local mirror of Ubuntu, in my case se.archive.ubuntu.com. This will download and install many packets. Run:

sudo debootstrap --arch i386 trusty /var/schroot/trusty_i386 http://se.archive.ubuntu.com/ubuntu/

You should now be able to enter the chroot (as your normal user):

cd
schroot

You will get a new prompt similar to this:

(trusty_i386)moggen@moggen-pc:~$

You will need to install a bunch of packages inside the chroot to be able to install GP6. Start with adding the "universe" packet collection.

You need to edit /etc/apt/sources.list. You only got the "vi" editor available in the base install. You can of course install an other editor with apt-get and use that. It is also possible to edit it from outside the chroot directly in your system. The path is then: /var/schroot/trusty_i386/etc/apt/sources.list

You must edit as root. Your passwords are copied to inside the chroot already, so sudo shuld work as usual.

Add "universe" packet collection to the deb source in the end of the line, so it becomes similar to this:

deb http://se.archive.ubuntu.com/ubuntu trusty main universe

Update the packets

sudo apt-get update

Attempt to install the GP6 debian package, it will fail due to missing dependancies! But we'll fix that. Your home directory is mapped to inside the chroot, so your ordinary Downloads directory is available.

sudo dpkg -i Downloads/gp6-full-linux-r11621.deb

Force installation of the dependancies, this will download and install many packets

sudo apt-get -f install

But more packets are needed before we can run GP6:

sudo apt-get install libpulse0 libSM6

Now we should be set.

Exit the chroot with ctrl-d or "exit". It will probably complain about a busy device that can't be unmounted, but it will work anyway.

Restart the chroot and tell it to start GP6:

schroot /opt/GuitarPro6/launcher.sh

Tada!

It is also possible to make an icon and run the launcher via the gnome/unity menus


Additional note: I had some trouble starting the GP6 updater when running via the command above. But the updater seems to work if I start schroot first to get the prompt and then invoke the launcher script.
2014-03-11 21:45

Date and time format in Ubuntu panel

I recently built a new home workstation and installed an alpha snapshot of Ubuntu 14.04. I'm not really a fan of the Unity desktop, so I installed and use the "gnome-session-flashback" packet to get the older Metacity GNOME environment for my desktop. On top of that, I have replaced the window manager with Openbox to get slimmed down window decorations.

The GNOME environments normally displays the current time in the clock indicator in the upper right corner of the screen. But, I'd like to display the date as well. This is no problem in Unity as the settings for this control allows some tuning of the format used, but on this flashback GNOME variant in Ubuntu 14.04, these options are not available in the settings.

This is a picture of the default clock indicator:

I found some info about how to change these settings using the gsettings command from a prompt. I ran these:

gsettings set com.canonical.indicator.datetime time-format 'custom'
gsettings set com.canonical.indicator.datetime custom-time-format '%Y-%m-%d %H:%M'

Customised clock indicator:

You can also enable week numbers in the drop down calendar:

gsettings set com.canonical.indicator.datetime show-week-numbers true

To list all options for the calendar, use:

gsettings list-recursively com.canonical.indicator.datetime
2014-01-26 00:34

Experimental Markdown support

Today I added some experimental Markdown support

I found this ready-made parser for PHP: http://www.parsedown.org/ and it was pretty easy just to drop in.

This violates my one-php-file idea somewhat. I could just copy the code straight into my single index.php, but it'll stay in a separate file for now.

This post is written with the MD formatting, and this raw code:

* MD list
* Works nice

### Heading level 3

[Link to the blog](http://moggen.org/)

Renders nicely as:

Heading level 3

Link to the blog

2013-11-26 21:23

Images embedded in HTML - Data URI Scheme

While working on the blog engine I found a technique for embedding images in the actual HTML file: Data URI Scheme, also known as RFC 2597.

This encoding scheme has been around for quite many years now and has been supported by a few browsers for some time, but unfortunately not by Internet Explorer 6 or 7 so it has been problematic to use. The usage of IE 6 and 7 is decreasing, and these versions are used by about 2-8% of all web surfers right now (there are different figures presented from different statistics providers). Surprisingly the usage of IE6 is larger than IE7.

I can live with not supporting IE6 any more.

So.. how is it done then? Quite simply with a specially crafted URL string.

This image: is created by this HTML image tag:

<img border="1" width="20" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCA
                                AAAACoBHk5AAAAAXNSR0IArs4c6QAAACVJREFUCNcFwTESACAMwzDDZe
                                mU/z+zk0eQzluZux2MFIOUjNIPrBoKCWyToNYAAAAASUVORK5CYII=" />
It is the same PNG image used as background on this page. The src URL is the PNG image Base64 encoded and prefixed by the string data:image/png;base64,. It is allowed to break lines and have whitespace inside the Base64 string.

This encoding can be used in CSS as well, for example:

body {
  background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCA
                   AAAACoBHk5AAAAAXNSR0IArs4c6QAAACVJREFUCNcFwTESACAMwzDDZe
                   mU/z+zk0eQzluZux2MFIOUjNIPrBoKCWyToNYAAAAASUVORK5CYII=');
}
2013-11-19 23:16

The MogBlog static content generator

I celebrate a small milestone for the blog engine.

I decided to simply call it MogBlog.
It is a static content generation blog tool outputting static HTML pages. I was inspired by Jekyll and Octopress, but I do not like that they are managed from a command prompt. I want a tool with a web interface. Yeah, I have used Wordpress a lot. Open source, lots of fancy stuff and plugins, but in my opinion too heavyweight requiring PHP for presenting data and a SQL database as backend.

MogBlog aims for these goals:

No database? Well, not really. I'm using one of the oldest database systems in computer history: the file system. It is actually pretty good at storing unstructured data in various formats, optimized for finding and accessing, and often heavily cached.

PHP. Not the most perfect language but it is open source and extremely wide spread.

The small milestone I wrote about in the beginning is that MogBlog now supports:

2013-11-11 19:44

Hello World!

I'm rebuilding this page to be a blog instead.

Old shit here

I'm building my own tool for this. Right now it is not very functional.
No RSS, no archives, no about page etc. But the stuff you see on this
page is created with the tool.