Perl and CPAN

Perl is a scripting language. Some people really like it. I have my own feelings about it, but that’s for another day. Perl has a system to install add-on modules called CPAN, that competes and conflicts with the native package manager on a Linux install, but sometimes the only way to install a random package is to use CPAN. Here’s a quick little guide on how to do that. Standard disclaimers apply.


sudo perl -MCPAN -e shell
install Bundle:CPAN
(press enter a bunch of times to allow CPAN to access the web and do updates)
reload cpan
install Module::Whatever

Repeat that last line for each package the perl script requires. Takes a lot of trial-and-error to find all the packages you need to install. Good luck.

Using command line arguments in Python in IDLE.

I’m not a big fan of integrated development environments (IDEs), but they can be nice to help people get introduced to a new language, or even to programming in general. Processing and Arduino wouldn’t be as easy for new people to use if they didn’t have a decent IDE.

Most useful scripts accept command line arguments to configure their behavior, but sometimes it is difficult to set command line parameters from within an IDE. I was recently working on a python project with a friend living in Florida, new to the world of programming, so I showed him how to use Python’s IDLE interface, a nice IDE for Python work. Unfortunately, there is no way to set command line arguments from IDLE, so our scripts weren’t working in the IDE. I found a way to manually set the command line arguments if a Python script is run from IDLE, but doesn’t interfere if the script is run from the console.

To use, insert this code right after the start of your main-line code, right before you do your parsing and validation of the input parameters. Be sure that the specified arguments below match what your program is expecting.


try:
    __file__
except:
    sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']

Tab completion and symlinked directories

Tab Completion is a very useful and time saving features of most modern command line interpreters. When you try to tab complete a symlinked directory, by default in BASH, it won’t put a trailing slash, even if the directory name is un-ambiguous. Example:

Normal directory:
$ cd Pic<tab>
$ cd Pictures/

Symlinked directory:
$ cd Pic<tab>
$ cd Pictures<tab>
$ cd Pictures/

Solution:
To tweak your shell to treat symlinked directories the same as regular directories for the purposes of tab completion, you can add these two lines to your ~/.inputrc file:

set mark-directories On
set mark-symlinked-directories On

QuickCG

When working with Java or (I presume) .NET, there is a standard, built-in way to do 2-dimensional graphics, such as drawing pixels or shapes on a blank canvas. These built-in graphics systems are very nice for displaying your own custom charts or graphs of the data being worked with, for example, plotting the lifetime of a human trying to escape from velociraptors.

QuickCG Screenshot

When programming in C or C++, there isn’t a standard way to do graphics, at least none that I am aware of. During my final semester at the University of Minnesota, I took a robotics class that required us to program the robots in a C++ environment. The robots we were using all had SICK laser scanners, and we wanted to plot the raw laser-data so that we could ensure that everything was working correctly.

While trying to find a decently simple way to make 2D drawings from C/C++, we discovered a very simple graphics library called QuickCG, which is a very thin wrapper around the standard SDL (Simple DirectMedia Layer) libraries. This package (actually it’s only a source and header file) includes examples and good documentation on the project website, and is extremely easy to use.

more »

Java Code Profiling

Here is a very small Java class to help time function calls or sections of code. Of course, it won’t be exactly right on (due to scheduling issues, etc), but it’s pretty good at helping with initial profiling and performance measurements.


public class Stopwatch
{
    private long start;
    private long stop;
    
    public void start()
    {
        // start timing
        start = System.currentTimeMillis();
    }
    
    public void stop()
    {
        // stop timing
        stop = System.currentTimeMillis();
    }
    
    public long elapsedTimeMillis()
    {
        return stop - start;
    }
    
    public String toString()
    {
        // print execution time
        return "elapsedTimeMillis: " + Long.toString(elapsedTimeMillis());
    }
}

HexDump Function

When programming at a low level, it’s often handy to be able to dump data to the console as raw hex values. Over the years I’ve written a handful of nearly identical routines to do this, but I’ve finally collected them into one function to rule them all. This function will dump a buffer to screen, 16 bytes per line, in both hex and ASCII format.


48 65 6c 6c 6f 20 61 6e 64 20 77 65 6c 63 6f 6d    Hello.and.welcom
65 20 74 6f 20 68 74 74 70 3a 2f 2f 77 77 77 2e    e.to.http://www.
77 61 79 6e 65 61 6e 64 6c 61 79 6e 65 2e 63 6f    wayneandlayne.co
6d 21 00                                           m!.

more »

C++ STL Gotchas: Map’s [] accessor

I’ve been working with some C++ recently at work. Today I was writing a class to manage unit conversion between various units, whether SI or imperial. I decided to use a map to make easy look up tables for the dimensionality, but I ran into a problem. I was trying to do something along the following:


std::map<int ,int> my_map;
int doFunction(int input) const
{
    int retval = my_map[input];
    return retval;
}

Notice the const quantifier at the end of the function declaration. The compiler kept complaining about discarding type quantifiers. Eventually, I noticed that the [] accessor to a map is not const, as it can also be used to insert items into the map. The proper way to preserve const-ness is to use the find method and a const_interator, as such:


std::map<int ,int> my_map;
int doFunction(int input) const
{
    std::map<int ,int>::const_iterator it = my_map.find(input);
    if (it == my_map.end())
    {
        //input not found in map
        return -1; //or some other sentinel value
    }
    retval = it->second; //retrieve the value from the key/value pair
    return retval;
}

Scons – A cross-platform, Python-based build system

In other work news, I was introduced to the scons build system, since we do a lot of cross-platform development at my job. Python is of course cross-platform, and the powers that be decided that this would be a good way to go.

Everyone who has struggled with makefiles in the past will love the simplicity and ease of use that comes with scons. A scons build file, normally called SConstruct, can be as simple as:

Program('hello.c')

What’s special about scons, is that the SConstruct file is also a python script, so you can use all the nice python syntax for things such as list concatenation, as in the following example that builds two programs that share a few common source files:

common = ['common1.c', 'common2.c']
foo_files = ['foo.c'] + common
bar_files = ['bar1.c', 'bar2.c'] + common
Program('foo', foo_files)
Program('bar', bar_files)

In large projects, the source files are naturally split into independently-buildable modules in different directories. When you try to use Make to manage this sort of hierarchal build layout, it’s usually maddening due to the reliance on environment variables and other things. With scons, you simply “conscript” the other scripts to build their part of the project:


SConscript(['drivers/SConscript',
'parser/SConscript',
'utilities/SConscript'])

Overall, scons is a pretty awesome piece of software, and I’ll hopefully be using it in the future for projects of my own.

http://www.scons.org/

Math Programming Challenges at Project Euler

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

Project Euler [via]

Fun with objdump!

In many introductory computer science discussions, the use of the increment and decrement operators is seen as sloppy and potentially confusing, especially when the pre- or post- property is used to save code. Have you ever wondered if the compiler figured out what you meant, when you said “x = x + 1″ instead of “x++” or even “x += 1″? Using a utility called objdump, you can see the assembly code the compiler actually produced.

I have created four source code files to demonstrate this functionality. To simplify the compiler’s output, I’m just creating an object file from a single function with a single statement. There’s no main method to get in the way, just the function foo(). I compiled each one of these examples with the following command:
gcc -Wall -W -g -c -o test.o test.c

  1. Increment – Since there is always an increment processor instruction, the compiler directly converts the increment statement in C to an increment long (incl) instruction:
    void foo(int x)
    {
        x++;
    }
    This is compiled to:
    void foo(int x)
    {
        0: 55 push %ebp
        1: 89 e5 mov %esp,%ebp
            x++;
        3: ff 45 08 incl 0x8(%ebp)
    }
        6: c9 leave
        7: c3 ret
  2. Plus-Equals – GCC has figured out that x += 1 is the same as x++:
    void foo(int x)
    {
        x += 1;
    }
    This is compiled to:
    void foo(int x)
    {
        0: 55 push %ebp
        1: 89 e5 mov %esp,%ebp
            x += 1;
        3: ff 45 08 incl 0x8(%ebp)
    }
        6: c9 leave
        7: c3 ret
  3. Plus
    void foo(int x)
    {
        x = x + 1;
    }
    This is compiled to:
    void foo(int x)
    {
        0: 55 push %ebp
        1: 89 e5 mov %esp,%ebp
            x = x + 1;
        3: ff 45 08 incl 0x8(%ebp)
    }
        6: c9 leave
        7: c3 ret