My own programming style convention for most languages

I write code mainly in R, and from times to times, in C, C++, SAS, bash, python, and perl. There are style guides out there that help make your code more consistent and readable to yourself and others. Here is a style guide for C++, and here is Google’s style guide for R and here is Hadley Wickam’s guide for R. For R, I agree more with Google’s style guide than Hadley Wickam’s because I absolutely hate typing the underscore (personal preference) and because Google’s style guide seems more related to that of the C++’s guide. Style guides differ by languages because the languages are different (restrictions on names, etc.).

My brain goes crazy if I have to remember and apply multiple styles, so I want to use a convention that I can use consistently for all languages. This boils down to refraining from using special characters such as “-“, “.”, and “_” in names as these characters can have special meaning in different languages. Here it goes:

  • constants: the letter k or n followed by a description. For example, kConstant or nSim.
  • variable names: description words where the first word is lower case and every subsequent words are lower case but with an upper case first letter. For example, varBeta1 for variance of beta1.
  • function names: a verb followed by description words, with each word capitalized except. For example, savePlot and computeGRhoGamma. This is the same as the variable names. I originally was going to follow the Google R style guide instead of the C++ style guide, but opted for the latter because the reasoning made sense: the distinction is obvious based on syntax when a function is called (has parentheses and possibly arguments).
  • function arguments: depending on the type of argument, use the variable names or function names style for each. To help distinguish an argument that takes in a function, the argument should begin with f if it takes in a function. For example, drop=TRUE and fSummarize=summarizeDefault.

When breaking these conventions lead to a better understanding of the code (easier on the brain), I will not hesitate to break them. For example, using i, j, k as iterator variables, using na.rm as functional argument in R, or rKM for a function that draw random numbers from a Kaplan-Meier survival curve.

Now, if only I can just magically transform all of my own code into this convention. I’m going to really hate going back to old code that doesn’t follow my own style, especially when they refer to code in packages that I will update according to my new convention.

flags for compiling source code: pkg-config command

so i was trying to compile some C code on my server at school that involves the math and the GNU Scientific Library (gsl) libraries. that is, the source has the following lines:

 <pre class="src src-C"><span style="color: #b0c4de;">#include</span> <span style="color: #ffa07a;">&lt;stdio.h&gt;</span>

#include <math.h> #include <gsl/gsl_integration.h>

those link the header files. however, when compiling, gcc would complain that they can’t see functions such as sqrt, abs, etc, from the math library. it also complains about my call to a function from the gsl library. i googled the math library stuff and realized i need to pass the ‘-lm’ argument in gcc for the math library. similarly, i saw somewhere that refers to the ‘-gsl’ argument. however, this did not work for me. i tried many things. some more googling, i found this thread that shows the ‘pkg-config’ command that shows exactly what arguments u need for which library.

So, i get:

 <pre class="src src-sh">$ pkg-config --libs gsl

-lgsl -lgslcblas -lm

so i just need to execute:

 <pre class="src src-sh">gcc -lgsl -lgslcblas -lm myprogram.c

i really don’t understand how the GNU compilers work. on my mac, i don’t have to pass those arguments. on my debian server, i need to. at first i thought that including the header was enough. will need to learn more about this stuff.

PS I also remember using this command when i had a hard time compiling shell-fm on my mac os x.

UPDATE: so on my mac os x, after installing gsl, i need to use ‘gcc -lgsl myprog.c’ to use the gsl library. things are fine now. I also want to note that i could not compile GSL form source on my debian server…had to rely on apt-get.

stumpwm on mac os x

stumpwm is to window managing (tiling?) system what emacs is to text editing and conkeror is to web browsing.

very cool. if i was on a linux laptop/desktop like i used to be, i would definitely use this. i’m even debating on quitting my mac os x for this (with emacs and conkeror). however, i most likely won’t since mac os x is pretty stable and most new stuff will be compatible with it (ease of use, plug and play).

i wanted to get stumpwm working on mac os x (intel based) like this post, but i never got it to work. somehow, i got it to work. my steps:

  1. update xquartz like the post said.
  2. install sbcl via macports.

UPDATE: actually, i think i used the sbcl for mac via this site.

  1. download the stumpwm source:

git clone git://git.savannah.nongnu.org/stumpwm.git

  1. followed the README file of stumpwm for sbcl:
  <pre class="src src-sh">$ sbcl

* (require ‘asdf) * (require ‘asdf-install) * (asdf-install:install ‘clx) * (asdf-install:install ‘cl-ppcre)

this step gave me MANY errors. i kept selecting the option to retry and continue like crazy. i finally gave up.

  1. continued with README
  <pre class="src src-sh">autoconf <span style="color: #ff4500;">##</span><span style="color: #ff4500;">get if not available. macports?</span>

./configure ##may need to specify sbcl if clisp is also installed make

stumpwm binary should be installed

  1. put following in ~/.xinitrc:

exec ~/Downloads/stumpwm/stumpwm ## path to stumpwm binary

launch programs in X (for example, xterm). look at stumpwm manual for keyboard shortcuts. very cool. this makes me REALLY want to go back to linux as my main computer.

emacs key bindings in mac os x (cocoa)

so im very used to emacs keybindings. i use it for emacs and conkeror so often times i hit M-w etc and these keys don’t work in mac os x. this sucks. i googled it, and found this and this. guess u can have emacs keybindings in mac os x…for programs that use the cocoa appkit. too bad this doesn’t work when i edit in neooffice or ms office.

my ~/Library/KeyBindings/DefaultKeybinding.dict looks like:

<pre class="src src-C"><span style="color: #ff4500;">/* </span><span style="color: #ff4500;">http://www.erasetotheleft.com/post/mac-os-x-key-bindings/ </span><span style="color: #ff4500;">*/</span>

/* http://www.gnufoo.org/macosx/ / / ~/Library/KeyBindings/DefaultKeyBinding.dict / / The original bindings are from Mike Ferris of lorax.com as shipped * with his TextExtras package. They were further modified by Mishka Gorodnitzky * (misaka@pobox.com), Patrick Linskey, and Llew Mason. / { “~f” = “moveWordForward:”; / M-f / “~b” = “moveWordBackward:”; / M-b / “~<“ = “moveToBeginningOfDocument:”; / M-< / “~>” = “moveToEndOfDocument:”; / M-> / “~v” = “pageUp:”; / M-v / “\^v” = “pageDown:”; / C-v / “~d” = “deleteWordForward:”; / M-d / “~\^h” = “deleteWordBackward:”; / M-C-h / “~\010″ = “deleteWordBackward:”; / M-backspace / “~\177″ = “deleteWordBackward:”; / M-delete / “~\UF728″ = “deleteWordForward:”; / delete / “\UF729″ = “moveToBeginningOfDocument:”; / home / “\UF72B” = “moveToEndOfDocument:”; / end / “@\UF729″ = “moveToBeginningOfParagraph:”; / A-home / “@\UF72B” = “moveToEndOfParagraph:”; / A-end / “@\UF700″ = “moveToBeginningOfDocument:”; / A-up / “@\UF701″ = “moveToEndOfDocument:”; / A-down / “\^\UF700″ = “pageUp:”; / C-up / “\^\UF701″ = “pageDown:”; / C-down / “\UF72C” = “pageUp:”; / page-up / “\UF72D” = “pageDown:”; / page-down / “\^/” = “undo:”; / C-/ / “~c” = “capitalizeWord:”; / M-c / “~u” = “uppercaseWord:”; / M-u / “~l” = “lowercaseWord:”; / M-l / “\^t” = “transpose:”; / C-t / “~t” = “transposeWords:”; / M-t / “~/” = “complete:”; / M-/ / “\^g” = “_cancelKey:”; / C-g / “\^a” = “moveToBeginningOfLine:”; / C-a / “\^e” = “moveToEndOfLine:”; / C-e */ “~w” = “copy:”; “\^w” = “cut:”; “\^y” = “paste:”; }

Compiling and Cross-compiling R packages for Windows (win32)

so recently i’m learning how to compile and cross-compile R packages from source for windows machines, which means i have to create windows binaries. the first option is to build on a windows system, and the 2nd is to cross-build on an intel-based linux or mac system. i will outline my experience.

Send it off to a Build Farm If you have the source package ready for install on a linux based system, you can send it off to a server and have it automatically build. This is probably the easiest way.

Building R packages and binaries on a Windows system. References: http://cran.r-project.org/doc/manuals/R-admin.html#Building-from-source http://faculty.chicagobooth.edu/peter.rossi/research/bayes%20book/bayesm/Making%20R%20Packages%20Under%20Windows.pdf http://www.biostat.wisc.edu/~kbroman/Rintro/Rwinpack.html Requirements: Rtools and R source file

At the time of this writing, I am using R 2.9.2 and using Rtools29.

  1. First, install Rtools, which includes some basic unix utilities, compilers (MinGW), windows compatible perl, unicode, Tcl, and some bitmap stuff.

Install should be in C:\Rtools and C:\R. Go ahead and install everything, including the Tcl stuff. In the install, go ahead and click modify Path variable if you have admin access. if not, add the subfolders of Rtools that has bin into the user ‘Path’ variable (either for User or for System) from the Control Panel > System > something > Advanced tab > Environment variable button. The variable should be something like ‘H:\Rtools\bin;H:\Rtools\MinGW\bin\;H:\Rtools\perl\bin\’.

  1. go to start > run > cmd to open a command window. I placed my R source tar.gz file in H:\R. now, use tar zxvf to unarchive it.
  2. Move H:\R\Tcl into the R-version folder that we just unarchived. Move the folders ‘unicode’ and ‘bitmap’ from H:\R\src\gnuwin32 into R-version\src\gnuwin32. Main thing is we need the iconv.dll file.
  3. goto R-version\src\gnuwin32\. type make (or make all) to compile. this gave me a couple errors. if u don’t have Tcl in the right location, edit the R-version\src\gnu32\MkRules and change the path for Tcl. I also got an error where it couldn’t find the tmp folder, so i just created H:\tmp. R successfully compiled: see R-version\bin\.
  4. To make the windows binaries, I have a package folder prepared under mac/linux. I copied it to the windows machine, and i did something like in H:\R\ (where the package folder is in, say H:\R\MyPackage):

H:\R\R-version\bin\Rcmd.exe build –binary MyPackage The source should be compiled into a dll and i get a zip file where i could install on other windows machines.

Cross building package win32 (windows) binaries on an intel-based mac or linux Since i don’t have a windows system (i did it on my brother’s computer), it could be convenient to build this on my mac or linux system. The R core team used to support cross building, but stripped support as of v 2.9. I first outline my experience with R 2.8 on my Mac OS X. Look at the R-admin help file for cross-building in the 2.8. I also got help from this post on R-dev, and a few inquiries with the poster through email.

Requirements: R source code file MinGW for mac (I installed v.4.3.0 binaries and added the location to my PATH variable) R (mac/linux, your system) binaries (version must match that of source. i had R 2.8 currently installed at the time, so i cross-build this version). R win32 binaries (same version as well): u can install this from source using the cross-build stuff, but i kept getting errors. so, what i did, was used the windows installer and installed it using Wine on my Mac (~/.wine/drive_c/Program Files/R/R-version/ – the space in Program Files isn’t good, so i made a softlink via ln -s to ~/R)

In R-version (extracted somewher), go to /src/gnuwin32, edit MkRules, changed: BUILD=CROSS no CHM, this version picks this up by default with CROSS BINPREF=i386-mingw32-##i586-mingw32- R_EXE=/usr/bin/R###’I failed to read the instructions to set R_EXE in MkRules’

Now, suppose the name of my package is MyPackage and it is locted in Users/vinh/Downloads/Rwin (MyPackage folder is in here)

Instructions here are found in README.package of gnuwin32:

<pre class="src src-sh"><span style="color: #b0c4de;">cd</span> .../src/gnuwin32

make PKGDIR=/mysources RLIB=/R/win/library pkg-mypkg make PKGDIR=/mysources RLIB=/R/win/library lazyload-mypkg cd /R/win/library zip -r9X /dest/mypkg.zip mypkg

in my gnuwin32 folder, i did:

<pre class="src src-sh">make <span style="color: #eedd82;">PKGDIR</span>=/Users/vinh/Downloads/Rwin/ <span style="color: #eedd82;">RLIB</span>=/Users/vinh/R/library/ pkg-MyPackage

[it compiled my dll file] make PKGDIR=/Users/vinh/Downloads/Rwin/ RLIB=/Users/vinh/R/library/ kazyload-MyPackage cd ~/R/library zip -r9X MyPackage MyPackage

Now I have MyPackage.zip that can be installed on windows machines! Remember, ~/R is the softlinked version of where my windows version of R is.

Next, i’m going to attempt cross-compiling on R 2.9.2, where support is no longer supported, but as the post i referenced above described, this should still be do-able. I will update this.

using pastebins for irc: pastie.org

so i’ve been using erc for irc these days to get help on compiling stuff, eg, shell-fm and madplay. i usually just paste the errors i get which sometimes can be long. however, that is bad courtesy in the irc channels as that junk takes up a lot of room. jkramer from #shell-fm on the freenode told me to use a pastebin, googled it, and realized what i’ve been doing was very rude. so he sent me to pastie, and now i learned something new. paste my stuff there and send the links. pastie is a simple pastbin service, just paste. it also has a bot u can paste too, which is even more convenient.

record music from last.fm using shell-fm

as i mentioned before again and again, i’ve been working on to get shell-fm to record music from last.fm. originally, i was trying to get shell-fm pipe to tee to save the songs and play using madplay (or mplayer) based on this method. this worked. i just need to write scripts to post process the songs to get id3 tags, etc. things work, and i have something like this in my shell-fm.rc file:

<pre class="src src-sh">extern = tee <span style="color: #ffa07a;">"/Users/vinh/shell-fm-saves/%a;%t;%l;%d.mpg3"</span> | madplay -Q -

##extern = tee “/Users/vinh/shell-fm-saves/%a;%t;%l;%d.mpg3″ | mplayer -cache 32 -

however, if u look at the end of the same page, it mentions hacking the source code because u can get shell-fm to automatically save free files, and get id3 tags on there. hopped on #shell-fm on the freenode and spoke to the author. (i tried this before but it didn’t work — reason was i didnt do a make clean first…i had residuals from the fail install since its on a mac).

now, to get shell-fm to compile with recording of every songs and get id3 tags working, just install libtag via MacPorts, modify play.c (search for freetrack and comment out that part):

<pre class="src src-C"><span style="color: #00ffff;">if</span>( <span style="color: #ff4500;">/*</span><span style="color: #ff4500;">freetrack &amp;&amp; strlen(freetrack) &gt; 0 &amp;&amp; </span><span style="color: #ff4500;">*/</span> haskey(&amp; rc, <span style="color: #ffa07a;">"download"</span>)) {

to compile, go in the source directory, do a make clean, then do the following on a mac:

<pre class="src src-sh">cc -o shell-fm -D__darwin__ -Os -Wall -W -I./include/ -DLIBAO -I/opt/local/include -I/opt/local/include -L/opt/local/lib -lmad -lm -Wl,-framework -Wl,AudioUnit -L/opt/local/lib -lao -lpthread -DTAGLIB <span style="color: #fa8072;">`pkg-config --libs taglib_c`</span> *.c

the author helped me figure out the DTAGLIB stuff, and how to get this command originally (had to remove the main.c in the middle and change the last .a file to *.c).

did:

<pre class="src src-sh">cp ./shell-fm /usr/bin/

cd ../manual make sudo shell-fm.1 /usr/share/man/man1/

now, go to ~/.shell-fm/shell-fm.rc and put in download = /Users/vinh/shell-fm-saves/%a – %t.mp3 and all completed songs will be saved WITH id3tag

hacking/editing portfile (MacPorts) to compile madplay for use with shell-fm (last.fm)

so recently i compiled shell-fm, a command-line last.fm player. in order to record music with shell-fm, i can output the stream of incoming data into tee, which saves the data to a file and at the same time pipes it out to stdout, and have that piped to madplay, a command-line player.

i had mplayer installed, but in order to get the piping of the streaming data to work, i had to to specify a cache ‘| mplayer -cache 32 -‘ (- means to take from stdin) in order for the music to play at the right rate. otherwise, the mplayer plays at a slower rate. the shell-fm wikidot recommends madplay.

madplay doesn’t compile easily on a mac os x, so i had to resort to MacPorts for the installation. it installs fine, but madplay plays noise. googled it, and stumbled on this post. he figured out it was an endian issue.

i tried applying his patch (‘patch < temp.patch’) to the original source code, however, it didn’t compile. figured out that i need the patch and the flags (CFLAGS, LDFLAGS) from Macports as well. i didn’t know how to apply both patches. hopped on #MacPorts on the freenode, and spoke with toby.

i created the 2nd patch and called it temp.patch in /opt/local/var/macports/sources/rsync.macports.org/release/ports/audio/madplay/files. edited /opt/local/var/macports/sources/rsync.macports.org/release/ports/audio/madplay/Portfile and added temp.patch to the list of patch files. now running ‘sudo port install madplay’ did the trick after uninstalling (sources and portfiles still around). voila, i have a working install on mac os x.

toby committed the new patch to macports, so now things should work. to get the new patches, i had to run ‘sudo port -d sync’ to sync the newest patch files. i uninstalled and reinstalled and the new official patch works.

i learned how macports operated and how to apply patch files in this adventure.

installing shell-fm on mac os x

i blogged recently that i couldn’t compile shell-fm on mac os x. hopped #shell-fm on the freenode, and talked to the author himself. the error i got was:

<pre class="src src-sh">cc -o shell-fm -D__darwin__ -Os -Wall -W -I./include/ -DLIBAO -I/opt/local/include -I/opt/local/include main.c -L/opt/local/lib -lmad -lm -Wl,-framework -Wl,AudioUnit -L/opt/local/lib -lao -lpthread libshellfm.a

ld: in libshellfm.a, archive has no table of contents collect2: ld returned 1 exit status make[1]: *** Error 1 make: *** Error 2

he suggested i go to the source and do:

<pre class="src src-sh">cc -o shell-fm -D__darwin__ -Os -Wall -W -I./include/ -DLIBAO -I/opt/local/include -I/opt/local/include -L/opt/local/lib -lmad -lm -Wl,-framework -Wl,AudioUnit -L/opt/local/lib -lao -lpthread *.c

that is, remove the main.c in the middle and libshellfm.a to *.c

that did the work and i got a working binary in the source folder. ran make in the manual folder, and installed them:

<pre class="src src-sh">sudo cp ./source/shell-fm /usr/bin

sudo cp ./manual/shell-fm.1 /usr/share/man/man1/

shell-fm is working now.

ALSO: according to this site, i modified play.c before compiling in v .6 as follows:

 <pre class="src src-C"><span style="color: #ff4500;">// </span><span style="color: #ff4500;">johnaman 05/30/2009 modified per http://shell-fm.wikidot.com/hack:extern-tee-backup</span>

// // replace this line (2nd find for “haskey” in play.c ) // if(freetrack && strlen(freetrack) > 0 && haskey(& rc, “download”)) { if( /freetrack && strlen(freetrack) > 0 && / haskey(& rc, “download”)) {

create custom keyboard shortcuts / hotkeys in mac os x: spark + applescript

in any linux gui environment, u can define custom keyboard shortcuts for anything, whether its executing a shell command to anything u can think of.

i love my macbook, but i really hate how Apple WILL NOT let me customize things the way i want it. they really force you into their philosophies: we say things should be simple for everyone so we will rely on the mouse. this is BS.

well, i recently figured out a way to resize and move my emacs frame with the keyboard, and i wanted to do that with all windows on my mac like in unix. after googling, i found 2 ways:

  1. mercury mover, which costs $24. no way! the method is a lot like emacs do re mi though. this is good.
  2. use this guy’s applescripts together with spark.

Spark is a great hotkey manager. Great addon to Mac to bring yet another useful feature from linux. I first used spark with emacs remember mode for jotting down notes in the middle of my work. Will write about that next.

I think i should tweak the applescript to somehow make it like mercury mover.