none none none
none

Programming



Some Thoughts

Programming is an art. It can actually be an art, like painting can produce wonderful pictures or just get a wall white...

Some links on this topic:

General programming links


C

C is simply the most powerful language, allowing you to do all you want. And with structs and function pointers, you really do not need object orientation built into the language. Do yourself and the world a favor and use opaque pointers and function pointers rather than start using C++ - which is just a pain.

Links to some interesting C stuff:

Some preprocessor fun to concatenate strings in C:

#define CONCAT(x,y)    x "" y
#define STRING(z)      #z
#define COMBINE(a,b)  CONCAT( STRING(a), STRING(b) )

you can then use these defines like this:

#define PREFIX     /usr/local
#define PIDFILE    COMBINE( PREFIX, /var/run/daemon.pid )
FILE *file = fopen(PIDFILE, "w+");

..and a little snippet to get the return value of a UNIX process:

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
    printf("%d", system(argv[1])>>8);
}

an alternativ would of course be to just use the shells builtin:

echo $?


function to change user (for dropping privileges when started as root)

#include <pwd.h>
#include <unistd.h>

int drop_privileges(char *user) {
        struct passwd *runas_pw;
        uid_t user_id;
        gid_t group_id;

        runas_pw = getpwnam(user);
        if (NULL == runas_pw) {
                return -1;
        }

        user_id = runas_pw->pw_uid;
        group_id = runas_pw->pw_gid;

        if (0 != setgid(group_id)) {
                return -2;
        }
        if (0 != setuid(user_id)) {
                return -3;
        }

        return 0;
}


function to test endianess at run-time

#include <stdbool.h>
#include <stdint.h>

bool isbigendian() {
    union {
        uint16_t i16;
        uint8_t i8[2];
    } u;
    u.i16 = (uint16_t)0x4321;

    /* ckeck contents of lower byte for most significant byte value */
    if ((uint8_t)0x43 == u.i8[0]) {
        return true;
    } else {
        return false;
    }
}


print signed 8 bit integer as binary (for your CS homework); can easily be transformed in versions for other integer sizes

#include <stdint.h>
#include <stdio.h>

void bprint8(int8_t n) {
    uint8_t b;
    for (b = 1<<7; b > 0; b >>= 1) 
        printf("%d", b & n ? 1 : 0);
}


gcc preprocessor macros to detect gcc version

/* gcc >= 3.1.0 */
#if __GNUC__ > 3 || \
  (__GNUC__ == 3 && \
  (__GNUC_MINOR__ > 1 || \
  (__GNUC_MINOR__ == 1 && \
  __GNUC_PATCHLEVEL__ > 0)))
#include <special-header-4-gcc31.h>
some_gcc31_function( 42 );
#endif
/* gcc > 4.1.0 */
#if GCC_VERSION > 40100
do_stuff();
#endif

And finally the mandatory square root function.

/* square root function with fixed boundary */
#include <math.h>
#define BOUNDARY 0.01

float sqroot(float x) {
    float r = 1.0;
    do {
        r = (r + x/r)/2;
    } while (fabs(r*r-x) > BOUNDARY);
    return r;
}

C-sharp

I had to use the .NET runtime environment for the EPTA-Project in Winter 2002/03, where I first used C#. My recommendation for .NET is: Dont use J#, try C#. Java is cooler, but J# is annoying in conjunction with .NET.

Currently I am evaluating mono on OS-X. There is still some cool IDE missing, but apart from that: same language as Java, different library names (which is annoying).


D

The D programming language sounds interesting, though I have some doubts if it ever will find some use.


Fortran

Errr... we used Fortran in the Parallel Algorithms course - mainly because of the where statement and the parallelizing compiler we used. I'm not familiar with the Fortran 2000 standard, but I rather dislike Fortran 77. Well, there may be a coincidence to me not being too experienced in this language; but to explicitely import the parameters of a function within it is really annoying. At least there are other people who dislike Fortran, too (at least the pre Fortran 90 stuff).

! sqare root function in Fortran 95
function sqroot(x) result(r)
    real, intent(in) :: x
    r = 1.0
    do while (abs(r*r-x) > 0.01)
        r = (r+(x/r))/2.0
    end do
end function sqroot

Haskell

Haskell is probably the most feature-full functional language I know. It integrates some fancy idea from Prolog and from mathematical concepts while not interfering with recursive functions. Haskell has the most clever and strict typing system I know. Everyone who got around learning scheme because of weak typing issues (bah): This excuse does not work with Haskell!

-- square root in Haskell 98
sqrec :: Float -> Float -> Float
sqrec r x = if abs (r * r - x) < 0.01 then r else sqrec i x
    where i = (x / r + r) / 2

sqrt :: Float -> Float
sqrt x = sqrec 1.0 x

Java

Java is without doubt elegant, though sophisticated - reduced to the max, so to say. If you are using iCal - or some other program utilizing the vCal format - you may find this article about transforming those vCal-Files with Java cool.

If you are in need of fancy Java code, look at the Sun Tech Tips. Sick of Sun, but want more Code? IBMs Java Technology Zone may be your place to hang around. If you'd prefer a more neutral tutor, try OReillys OnJava.

Cool networking stuff may be found at Strangeberry, having a Rendezvous implementation in Java. An OpenSource Webserver & Servlet Engine for your needs may be Jetty - as being a little more lightweight than Tomcat. If you only need something for html-output, check out jtidy, a library for checking and cleaning html.

For avoiding pitfals in optimizing code, there is an article about urban performance legends in Java. And here is a cool interview with David Gelernter about Computer Visions (and about Java). If you are a Mac fan or are simply interested in networking, check this article on Mac Devcenter about Zero-conf technology. Interesting stuff about call by reference vs. call by value in Java.

Java links:

/* square root in Java */
import java.lang.Math;

class MyMath {
    private static float boundary = (float)0.01;

    public static float sqroot(float x) {
        float r = (float)1.0;
        do {
            r = (r+x/r)/2;
        } while (Math.abs(r*r-x) > boundary);
        return r;
    }
}

Objective-C

Good books on Objective-C:

  • Programming in Objective-C, a very good book on the Objective-C programming language - regardless if you are on NeXT, MacOS-X or some other Unix.
  • Cocoa Programming for MacOS X, good fun to read, though focus is clearly on Cocoa and will not be of much use for any other platform than OS-X.

Objective-C links:


Pascal

You can write nice code in pascal... but in my opinion there is no niche for pascal anymore (besides perhaps being easy for beginners). A design flaw in my eyes is that for the return values of functions, you have to use the name of the function and assign the return value to it. This degrades readability and makes renaming of functions more painful than necessary.

(* square root function with fixed bound *)
function sqroot(x : real) : real;
    var r : real;
    const bound = 0.01;
begin
    r := 1;
    repeat
        r := (r+x/r)/2;
    until abs(r*r-x) < bound;
    sqroot := r;
end;

Perl

I rather dislike perl for it's 'there is more than one way to do it' maxim. This leads to fancy code that's really mindboggingly and cool - but that no one can read half a year later... I'm glad that perl is loosing ground to php and python as they both are more clean languages (if in doubt, use python as it is even more clean than php).


PHP

This page was initially realized with PHP4. But as I dont have PHP at my hosting location, I generate the pages at my notebook and upload them (automatically). PHP is nice, but currently (PHP4) OO just sucks - which is promised to be cured with the Zend2-Engine and PHP5. For real programming I generally prefer strict type-checking languages. This page used the HTML-IT template, which is really cool. I've done some work for Wundersoft with the template framework and this just rocks in terms of modularity and productiveness.

If you are in need of PHP-libraries, you should consider the PEAR library. If you already have a recent version of PHP4 installed, you can simply do a

pear install %package%
to install certain libs (you have to have write access to the PHP-library directory).

Prolog

Prolog is basically just another functional programming language - like Lisp - that brings some the interesting concept of backtracking. It is horrible inefficient due to being mostly run as interpreter, so if you need some fast scientific calculations, back off. If you are interested in solving some nasty combinatorial problems, this might be the one for you.

If you like defining addition like this, prolog definitely is for you! (or maybe Lisp or Scheme or Haskell or XSL...)

add(0, Y, Z) :- !, Z is Y.
add(X, Y, Z) :- (X > Y), !, add(Y, X, Z)
             ;  dec(X, A), inc(Y, B), !, add(A, B, Z).

Python

Beeing named after Monty Python's Flying Circus there normally would'nt be any reason missing for learning this language. As far as I have seen, Python is really nice to code - also it comes without strict type checking. I'm not too familiar with all the libraries, but it looks promising. One strange thing to mention for C/Java-Style hackers: There are no curly braces for code-structuring! Instead this works by indentation. A nice side effect of this is that all python programs always are indented correctly. No trouble wheter to put the curly braces to the end of the line or at the beginning of the next one...

I've most recently written some code for creating a rather large dhcp-server config file and I have to admit that Python is really cool. Python is my favorite programming language for prototyping and scripting. The only problem with Python is that without strict typechecking I can't recommend it for large projects or for security stuff (thats what Java is suited for best). Python has an edge over Perl and PHP as it supports real OO and it's programs are very short though readable (Perl programs also tend to be short, but no one can read them anymore).

Have a look yourself at some python code; where else can you write such short code?

for i in [1,2,3,4,5]:
    print "This is iteration number", i
Another good one: (prints the numbers from 0 to 99 inclusive)
for i in range(100):
    print i
Especially suited for parsers:
file = open( "filename" )
for line in file.readlines():
    list = string.split( line, ";" )
        print list[1] +": "+ list[3]

Python seems to be an excellent language for education, especially for programming examples as they stay short without loosing substance.
Some python pages:

And finally some python projects:


Scheme

The famous Wizard Book Structure and Interpretation of Computer Programs from Abelson and Sussmann is available online. Also quite fancy: There are free video lectures on scheme by Abelson and Sussmann online - about 20 hours!

;; recursive square root function (with fixed boundary)
(define (sqroot x)
    (define (sqrec r x)
        (if (> 0.01 (abs (- (* r r) x)))
            r
            (sqrec (/ (+ r (/ x r)) 2) x)))
    (sqrec 1.0 x))

Shell

There is an excellent protocol from the DO-Linux lecture about shell-programming here (german). The GNU make manual also comes in very handy from time to time.
Some goodies for your .cshrc:

# full directory listings
alias l 'ls -la'
alias ll 'ls -l'

# auto completion of filenames [tab]
set autolist

# no annoying beeps
set nobeep

# default editor (for 'crontab -e', ...)
setenv EDITOR=vim

# proxy settings (set proxy-name/ip and port according)
setenv http_proxy http://proxy-name:proxy-port
setenv https_proxy https://proxy-name:proxy-port
setenv ftp_proxy ftp://proxy-name:proxy-port
Examples for common flowcontrols in csh and sh:
#!/bin/csh
if ($i == -h) then
    echo "variable $i is -h";
else
    echo "it aint...";
endif
#!/bin/sh
if tail -n 5 file.txt | grep pack; then
    echo "file.txt has 'pack' in last 5 lines"
else
    echo "nope, no 'pack' there (or file.txt missing)"
fi
#!/bin/csh
foreach i (1 2 3 4 5)
    echo $i
end
#!/bin/sh
for i in 1 2 3 4 5; do
    echo $i
done
#!/bin/csh
set i = 0
while( $i < 100 )
    echo $i
    @ i=$i + 1
end

The powerful korn-shell (ksh) even can do floating point math.

# square root in ksh
sqroot() {
    typeset -F x=$1
    typeset -F r=1
    while [[ $(( abs(r*r-x) )) > 0.01 ]] do
        r=$(( (r+x/r)/2 ))
    done
    print $r
}

XSLT

XSLT is a very funny thing. At least for programmers accustomed to functional languages like C. If you don't believe in XSLT being useful, beware: XSLT is Turing complete and - therefore of course - also as mighty as while programming. At Siemens I did some XSLT programming for generating XSD out of XMI, the (more or less) standarized XML format of UML modelling tools.

none
none none none
none none none
none Last touched on Tuesday, 19-Jun-2007 19:18:51 CEST, © Markus W. Weissmann none
none none none