Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, August 24, 2012

Vim tips (especially for the Scandinavian keyboard)

Despite being a Vim user for 9 years I have often felt unhappy about the fact how inefficiently I'm using the editor. I decided to dedicate some time and become more proficient in Vim. Most of the new power comes with the increased use of Vim's basic stuff, e.g. the change command and simply trying to find the simplest way to define what to yank, delete, and where to jump.

Some of the new power comes with better key mappings. This is especially true for Scandinavian keyboard owners like me which is be default unsuitable for Vim. This post is about .vimrc.

The first thing is always enforce use of hjkl for simple navigation by disabling the arrow keys in normal and insert modes.

map <up> <nop>
map <down> <nop>
map <left> <nop>
map <right> <nop>
imap <up> <nop>
imap <down> <nop>
imap <left> <nop>
imap <right> <nop>

Let's note that in Vim hjkl for navigation is usually the most inefficient way.

In Finland the ~ character is behind a combination of altgr, ~, space. That is three keypresses. The ~ toggles between lowercase and uppercase in Vim. The following mapping brings it behind one keypress as it's meant to be.

map § ~ "for Finnish/Swedish keyboard

Often search is the quickest way to define a desired location in the document. Again on the Finnish keyboard the / is behind two keypresses. Search should be behind one press, so it was mapped to space.

map <space> /

Switching between windows should be quicker. I mapped Ctrl with hjkl for window navigation.

map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l

For buffer navigation I mapped leader (the comma) with ö and ä. This is again useful for the unfortunate using Scandinavion keyboard, which by the way is not at all optimal for programming either.

map <leader>ö :bNext<cr>
map <leader>ä :bprev<cr>

For switching to paste mode and back I have previously used the :set paste and :set nopaste commands. Now it is mapped to leader pp which toggles between the modes quickly.

map <leader>pp :setlocal paste!<cr>

Finally, some coffeescript friendly configuration. The compilation stuff demands the coffee.vim plugin which everybody has already.

In coffeescript string interpolation is "done like #{oh boy}". The Scandinavian keyboard users' wrists are in pain. The following very warm and fluffy insert mapping injects the #{} in the context, puts the cursor after the { and stays in the insert mode.

imap <leader>§ #{}<esc>i "The § is located left to 1 on the Scandi kb.

Coffeescript programmers need to check the compiled javascript from time to time. I have mapped leader c to CoffeeCompile which opens the current buffer's compiled version in a new split window.

map <leader>c :CoffeeCompile<CR>

For checking the visually selected region's compiled code, I use

vmap <leader>c <esc>:'<,'>:CoffeeCompile<CR>

I don't want to pollute my source code directories with the compiled .js files. The following can be used to change the compile target path.

let coffee_make_options = '--bare --output ~/tmp/coffeecompiles/'.expand("%:h")

The following setting does CoffeeCompile automatically when a .coffee buffer is saved. Useful!

au BufWritePost *.coffee silent CoffeeMake! -b | cwindow | redraw!

Disclaimer! Most of the stuff here has been found from the net from various forgotten sites, so I reject all credit, except for the #{} mapping which me and my co-founder came up with - yes we write a lot of coffeescript every day!

Wednesday, September 1, 2010

Interfacing Win32 API from Qt

If you ever need to do this sin, just include qt_windows.h and you are free to access native Win32 API.

To ensure the monster still compiles on other platforms, you may even use #ifdef Q_WS_WIN evilness as well.

Enjoy your objectionable life.

Friday, October 23, 2009

New startup and a word about types

It's been a while. I joined a new tech startup in Helsinki and have had no time to write to my blog. But I'm always returning! See?

My summer adventures at TKK went smoothly and I'm happy that I had the opportunity to work in a very interesting project and enhance my C/C++ skills there. Now I'm writing mostly Python and it feels great after months of C, almost like if somebody just imported antigravity. I have to admit, I have long been a strong proponent of explicit typing as it is a form of self-documentation, but when you just need to build something quickly, as in startups, explicit types are simply slowing you down. I need to add that I'd still love static typing, something Python does not offer.

Days are already dark in Helsinki and it's getting cold. Now we have to face six months of darkness, which is always so... intriguing. I have always wondered though how quickly it passes. Now that I have Python with me, the spring will surely return in no time.

Have you ever wondered why your relatives are always asking for your help with computers? It's not that they are stupid, but the computers are still way too difficult to use. That's going to change in the next decade(s). I bet the whole platonic idea of the computer is going to change. It'll be more like that everything is a computer, and we will start calling these devices something else that more accurately describes their function.

Thursday, April 9, 2009

Intuitive Clojure

I just downloaded and tried Clojure for the first time. With a little help from clojure dot org, I managed to write the following snippet that demonstrates the use of tail calls, Java interoperation, exceptions and a bit of I/O. Of course, as is typical for lisps, it just worked the first time.

The program simplifies div expressions. The input is given in format <numerator> <denominator>, for example, 4/2, is given as 4 2.


 1 (defn gcd [a b]
 2     (if (= a b)
 3         a
 4         (if (> a b)
 5            (recur (- a b) b)
 6            (recur a (- b a)))))
 7
 8 (defn run []
 9     (let [line (read-line)
10           args (.split line " ")
11           len (alength args)]
12         (if (< len 2)
13            (println "Expected two arguments.")
14            (try (let [a (Integer/parseInt (aget args 0))
15                       b (Integer/parseInt (aget args 1))
16                       gcd (gcd a b)]
17                    (println a "/" b "=" (/ a gcd) "/" (/ b gcd)))
18                (catch NumberFormatException
19                    ex
20                    (println "Expected natural numbers."))))))
21 (run)

Wednesday, April 8, 2009

Lessons on JNI and dynamic libraries in Linux

I was experimenting for the first time with two things: The Java Native Library (JNI) and home-made dynamically linked libraries in Linux. It took some awkward moments until it all worked due to amateurish handling of the subject, and some bad attention. Still, it was rather amusing, and shall be documented.

By the Sun JNI example, I began by creating a Java class (C_Gcd.java) and writing the method declaration for the native method called gcd. Finally I added a static code block to the class that loads the library with System.loadLibrary, which I passed the library name (gcd) as an argument.

Next I generated the C headers (C_Gcd.h) from my Java source file using javah. After that, I created a .cpp file (I decided to use C++) in which the implementation of the native method would be. Next I wrote the actual gcd implementation.

Okay, that was easy. Next we compile the C++ code and make a shared library out of it. Here is what went wrong: I forgot that all dynamic library names are prefixed with 'lib'. I created a file called gcd.so.

Now, thinking everything was going fine, I wrote another Java class that would be using the native gcd method of the C_Gcd class. Now, I noticed that I want the gcd method to be static to avoid instatiating a C_Gcd object. So I happily went and added the static keyword to the gcd method declaration in the Java source file. Here was the second mistake: I forgot that changing the Java method declaration may, and probably will, lead to changes in the output of javah.

Now, believing it should run fine, I compiled everything again and run the Java application but got:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no gcd in java.library.path
Google reminded me of LD_LIBRARY_PATH, but setting it to the current path did not help. I kept having the same error.

Next I went to investigate the system with ldconfig. At some point I realised that not only is it a convention that all libraries are prefixed with lib, they must be! Unfortunately I went and changed the argument of System.loadLibrary to libgcd, which is of course wrong. So here was the third mistake: we refer to a library libfoo with mere foo, but I expressed, using the same example, liblibfoo. I still got the very same error.

After a moment I corrected the lattest glitch, and now, the error message changed:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Gcd.gcd(II)I
It was still an UnsatisfiedLinkError, but it dropped the talk about java.library.path.

Next, feeling desparete, I decided to take a look on the Java bytecode using javap. It looked completely healthy. I decided to take a break.

After the break, I opened the C++ sources again and began reading with no prejudice -- and there it was -- I finally saw that the C function declaration and its definition had been in conflict all the time. Corrected it, recompiled, and, uh, it finally worked!

And here we summarize on how to get JNI working painlessly under Linux:
  • Make sure to have LD_LIBRARY_PATH point to the library path. (*)
  • Make sure to name the library libFoo.so.
  • Make sure to refer to the library with mere Foo.
  • Be careful when changing the native method signatures.
(*) or launch the JVM with: java -Djava.library.path=. YourApplication in case your library is in the current directory.

For completeness, here's the source (with class names cleaned a bit):

== Gcd.java ==


public class Gcd {
public static native int gcd(int a, int b) throws IllegalArgumentException;
static {
System.loadLibrary("Gcd");
}
}



== Gcd.h ==


/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Gcd */

#ifndef _Included_Gcd
#define _Included_Gcd
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Gcd
* Method: gcd
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_Gcd_gcd
(JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif



== Gcd.cpp ==


#include "Gcd.h"

JNIEXPORT jint JNICALL
Java_Gcd_gcd(JNIEnv *env, jclass cl, jint a, jint b)
{
if (a < 0 || b < 0) {
jclass ex = env->FindClass(
"java/lang/IllegalArgumentException");
env->ThrowNew(ex, "Both arguments must be positive.");
env->DeleteLocalRef(ex);
return -1;
}
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}



== Test.java ==


public class Test {
public static void main(String[] args) {
System.out.println("gcd(12,24) = " + Gcd.gcd(12, 24));
}
}



== Makefile ==


CC=g++
INCLUDE=-I/usr/lib/jvm/java-1.5.0-sun-1.5.0.16/include/linux/ -I/usr/lib/jvm/java-1.5.0-sun-1.5.0.16/include

libGcd.so: Gcd.o
$(CC) -shared -o libGcd.so Gcd.o

Gcd.o: Gcd.cpp
$(CC) $(INCLUDE) -O3 -c Gcd.cpp

clean:
rm -f libGcd.so Gcd.o

Saturday, March 21, 2009

Thesis working hours

A Python script follows, that shows the working hour statistics.


import sys
from subprocess import *

p1 = Popen(["git", "log"], stdout=PIPE)
p2 = Popen(["grep", "^Date"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["awk", "{printf \"%d \", $5}"], stdin=p2.stdout, stdout=PIPE)
output = p3.communicate()[0]
hours = output.split()
stats = {}
for h in range(0,24):
stats[h] = 0
for h in hours:
stats[int(h)] += 1
for k in stats.keys():
print "%02d: %s" % (k, "*"*stats[k])





And the results...

00: *****
01: ***
02:
03: **
04:
05:
06:
07:
08:
09:
10: **
11: *****
12: ************
13: ************
14: **********************************
15: **********************
16: ************
17: **********
18: **
19: ***
20: ***
21: **
22: *
23:

Sunday, February 22, 2009

A CPS question and answer

Continuation passing style is a hard concept. Recently one fellow pasted the following piece of Haskell code in IRC and asked for its meaning:
cfold’ f z [] = z
cfold’ f z (x:xs) = f x z (\y -> cfold’ f y xs)

cfold f z l = cfold’ (\x t g -> f x (g t)) z l

It is a fold implemented in continuation passing style. Let's see what we can say about the type of cfold'. The function cfold' takes a function f of three arguments. The first argument of f is of some type t, the second argument is of some type t1, and the third argument is another function. The other function takes one argument of type t1 and its return value is the same as cfold's, that is, t1. Finally the return type of f is t1 as well. The second argument z of cfold' is something of type t1. The third argument of cfold' is a list of ts that is pattern matched in the definitions of cfold'. Thus, the type signature of the whole function is cfold' :: (t -> t1 -> (t1 -> t1) -> t1) -> t1 -> [t] -> t1.

Next, what can we say about the definition of cfold'? When the third argument, that is a list, is an empty list, it returns what ever is the value of its second argument of type t1. If the list is non-empty, we return what is returned by calling f when it is given x -- the head of the list (of type t), then z of type t1, and a function from t1 to t1.

At this point we start calling the first argument of cfold', that is f, a continuation. In the second definition of cfold' the control is passed to a continuation f. The continuation is a recipe of what to do next. The continuation is given the head of the list and a base value for the fold. The trailing anonymous function from t1 to t1 allows the continuation to get the result of the fold for the tail of the list.

Now, given the fold implemented in CPS, how do we, for example, multiply the elements of a list together? The continuation must contain that logic. Our continuation was a function of type (t -> t1 -> (t1 -> t1) -> t1). The first argument was the head of the list, the second argument was the base value for the fold, and the third argument was the way to get result of the fold for the tail of the list. So the definition for the continuation must be something like this:
(\x t g -> (*) x (g t))
It says that given the head of the list, x, a base value for the fold, t, and the function g that yields the result of the fold for the tail of the list when it is given t, the result of the whole fold is the list head multiplied by the value of the fold for the list tail.

Now cfold' alone is not describing much. We define cfold that passes the continuation, that does the actual folding, to cfold'.

If we try cfold with the sum function, a base value of zero and a one element list containing the number one, the expression reduces as below:
cfold (+) 0 [1]
(\f z l -> cfold' (\x t g -> f x (g t)) z l) (+) 0 [1]
cfold' (\x t g -> (+) x (g t)) 0 [1]
(\f z (x:xs) -> f x z (\y -> cfold' f y xs)) (\x t g -> (+) x (g t)) 0 [1]
(\x t g -> (+) x (g t)) 1 0 (\y -> cfold' (\x t g -> (+) x (g t)) y [])
(+) 1 ((\y -> cfold' (\x t g -> (+) x (g t)) y []) 0)
(+) 1 0
1

So for a non-empty list, cfold' calls the continuation, that performs the folding, and for an empty list it returns the base value.

Thursday, January 29, 2009

An apt definition of functional programming

While reading Jukka Paakki's paper on attribute grammars I found out that it contains a pretty apt definition of functional programming that I have been learning over the past year. So here it is for the public's delight (OCR'd, so the possible typos might not be original):

"The functional style of programming can
be summarized with the following characteristics:

  • referential transparency
  • higher-order functions
  • lazy evaluation
  • pattern matching

Referential transparency is the term used
traditionally to express that the value of
an expression depends only on the values
of its subexpressions, and that the value
of each occurrence of an object is the
same, irrespective of the context. In other
words, side effects are ruled out. Functions
being higher-order means that they are
first-class values and can, for instance,

be stored in data structures and
returned as result of function calls. Lazy
evaluation is tantamount to "nonstrictness,"
meaning that the value of an object is not
computed until it is actually needed, and
thus the value of an argument may be
undefined when calling and executing the
function. Pattern matching is a general
term
used to express the mechanism applied
when
trying to make X and Y identical in an
equation X = Y where X and Y are expressions.
Pattern matching is restricted in functional
programming to introduce bindings only to
the
left-hand side X when solving such an
equation."

(Paakki, J. 1995. Attribute grammar paradigms—a high-level methodology in language implementation. ACM Comput. Surv. 27, 2 (Jun. 1995), page 236.)
What could be added is the concept of recursion.

Thursday, March 27, 2008

Learning Haskell

Uh, no taocp today because I got stuck in Haskell.Org's haskell-98 tutorial. Functional programming has been unknown to me. We don't have a Lisp-derived language as the first language in the univ. (it's the evil Java there!) so not until ~one year ago did I start to satisfy my curiosity and downloaded the legendary Lisp lecture videos from MIT servers. I wrote some basic algorithms in Common Lisp and liked it but I never had the motivation to watch the whole lecture series nor write anything real in Common Lisp.

Having recently become a regular reddit/programming reader I've seen a lot of Haskell related articles in the hot list. At the univ. I've seen a bit of Haskell fanaticism, and functional progr. fanaticism in general, going on, too. Because of that I decided to find out more about this language.

Right now, having read one-thirds of the tutorial, I can already say that I'm happy that I opened it. Never have I seen such a beautiful definition of quicksort before:

qsort [] = []
qsort (x:xs) = qsort [ y <- xs | y < x ]
++ x ++
qsort [ y <- xs | y >= x ]

Yes, the pivot could be chosen more carefully as this can easily fall to O(n^2), but ignoring that, this is a marvelously lucid piece of code.

Tuesday, March 11, 2008

Computer Programming as an Art, 1974

While the books are being shipped I took the opportunity to read Knuth's 1974 ACM Turing Award paper titled the same as this blog entry. The paper was written a decade before I was born. Should anyone find this topic interesting, I recommend reading the paper. Below I try to summarize the main argument however.

It is explained in the paper that the term art used to mean "something devised by man's intellect, as opposed to activities derived from nature or instinct." Basically what we nowadays usually call science was previously considered art. Later the two terms began to have more independent meanings. Science was now considered to stand for knowledge and art for the application of knowledge.

Knuth's arrives in a conclusion that science is knowledge which we understand so well that we are able to teach it to a computer, while art is something which we don't fully understand. The story tells how programming has transformed from being pure intuitive art to more of a scientific matter. We have progressed in making software, being now capable to proof program correctness and do meaningful measurements of the software development process.

Knuth tell us that making software is, however, both science and art. He states that his viewpoint of programming as an art is an aesthetic one. The main goal of his work as educator is helping people learn how to write beautiful programs. The following quote from the paper may be worth mentioning.
"My feeling is that when we prepare a program, it can be like composing poetry or music; as Andrei Ershov has said, programming can give us both intellectual and emotional satisfaction, because it is a real achievement to master complexity and to establish a system of consistent rules."

The paper talks about a number of other issues as well, such as of the importance of great programming tools and languages, and different programming styles.

In the end it is claimed that a programmer who views himself as an artist will enjoy programming and also perform better. I've never though of it that way. For me it is clear that should you enjoy your work for whatever reason, that alone will enhance the quality of the work. I don't certainly feel being an artist when I'm coding, but I certainly enjoy being the creative force, a god-like transformer of pure, abstract ideas to machine readable instructions, and see the machine obeying my commands (though in the bad days the machine just can't understand me and keeps segfaulting).