Archive for the 'Programming' Category

Python: AttributeError: ‘getopt’ module has no attribute ‘GetoptError’

Wednesday, July 28th, 2010

So I was figuring out how to parse command line arguments with python and using the getopt module with the following code


#!/usr/bin/env python
import sys
import getopt

def main(argv):
   grammar = "some.xml"
   try:
      opts,args = getopt.getopt(argv,"hg:d",["help","grammar="]
   except getopt.GetoptError:
      usage()
      sys.exit(2)

if __name__ == "__main__":
    main(sys.argv[1:]

And I was getting the following error:

AttributeError: ‘getopt’ module has no attribute ‘GetoptError’

So my first problem was that I had named my script getopts.py and after renaming the script, I got the same error. Well you now need to remove the getopts.pyc file that was generated from your earlier running of the poorly named script.

How to address perl arguments

Wednesday, July 28th, 2010

If you are using perl, you may find it necessary to take some command line arguments to your scripts.  When that time comes, there is a very handy variable ARGV that contains the passed in arguments.

To get the total number of arguments passed into the script you will need to use the following:

$totcommandargs = #$ARGV + 1

is equal to the number of arguments passed in to the Perl script.

Note: you need to add one to the count to get the correct number of variables.

To address the variables you use the following to address the first argument: $ARGV[0]

will address the first argument

Since arrays are addressed by n-1, to get the first element you use 0 {zero}, for the second 1, for the third {2}, and so on.

$0 will give the name of the currently executing script.


#!/usr/bin/perl

$argcount =  $#ARGV +1;
print "The script $0 has $argcount arguments\n";

for( $i = 0; $i < $argcount;$i++)
{
print $ARGV[$i] . "\n";
}

Passing JVM options to Maven

Wednesday, June 30th, 2010

If you are using maven to build your projects , then you might have found an out of memory condition in your tests.  Well, setting the MAVEN_OPTS variable with JVM specific options will help with this.

Example:

MAVEN_OPTS=-Xmx1024

Depending on what environment you are in, you will need to set this variable.

This will give the JVM more 1024 megs to work with and you can customize the number to fit your needs.

Java formatting a number with leading zeroes

Friday, July 17th, 2009

Recently, I had a Java project that needed to encode a set of numbers and I needed a fixed number of digits used for each number. I found the DecimalFormat class a good solution for my needs.

Here is a snippet of code to show a simple way to format a number with a fixed number of digits.

import java.text.DecimalFormat;

class TestEncoder
{
        public static void main(String[] args)
        {
                // This program expects one integer
                // argument and places it in the num1
                // variable. This program is not very
                // robust as to watch for no arguments
                // or to check if the argument is not
                // an integer.
                String num1 = args[0];
                String output;

                // This creates the Decimal Format instance
                // and assigns the formatting that we want
                // to use, in this case three characters .
                DecimalFormat dfmt =
                             new DecimalFormat("000");

                // This does the work of formatting the number
                // passed in on the command line to be at least
                // three digits.
                output = dfmt.format(new Integer(num1));

                // This just displays the results of the
                // dfmt.format(new Integer(num1)) command.
                System.out.println("Output: " + output);
}
}

The Decimal format allows for many more formatting options for numbers.

Make sure to look a the API docs for the version of Java that you are using:

http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html

Tags: ,

Using Variable Argument lists in functions for C and C++

Tuesday, May 26th, 2009

Using Variable Argument lists in functions for C\C++

In C there are times when you may want to have a variable amount of arguments passed into a function.  This can be accomplished when you pass the ellipses(…)  in as the last argument on your function.  The ellipses ,(…),  stands for zero  or more arguments.
There are a set of functions available to handle accessing this data and making it available to your function.

The source code example displays a version of the code for a printf like function and how to handle the optional arguments.

One note is that the arguments passed in to this function are not typed.  The handling of the argument depends on either a specific type passed in(ints only) or as is the case of the example, a formatted string to define the types of the arguments. What this means is that if you pass random sets of arguments, (such as ints, strings,chars, floats) there is no data type that is directly associated to the variable being passed in.

Required include file
#include <stdarg.h>
/* Old include <varargs.h> From before ISO C standard, GNU C compilers still support this */

Available functions:
Macro: va_start(va_list , last-required argument)
This sets up the pointer for va_list with the avaiable argument list.

Macro: va_arg(va_list, type)

This returns the value of the next argument and modifies the va_list argument
to point to the subsequent(next) argument.  The type of the value returned by
va_arg is type as specified in the call. type must be a self promoting type
not char or short int) that matches the type of the actual argument.

Macro: va_end(va_list)

This ends the processing of the va_list element and subsequent va_arg calls
may no longer work.  Note: In the GNU C library implementation this does nothing
and is used for portability.

Sample Function Call:

  int int1 = 1;

    char char1 = "s";

    char *str1 = "test";

    /* Sample function call. */
    ecdprintf("Int=%d Char=%c String=%s\n",int1,char1,str1);

Sample Code follows:

int ecdprintf(const char *pstr, ...)

{
    const char *lstr;
    va_list argp;
    int lint;
    char *lchar;
    char strarr[255];

    /* This is the start of vararg processing. The first argument is the
         container argument of the vararg list and the second argument
         is the last fixed parameter passed into the function. */

    va_start(argp, fmt);
    for(lstr = pstr; *lstr = '\0'; lstr++)
    {
        if (*lstr != '%')
        {
            putchar(*lstr);
            continue;
        }

        switch(*++lstr)
        {
            case 'd':
                i = va_arg(argp,int);
                s = itoa(i,strarr, 10);
                putchar(i);
                break;
            case 'c':
                i = va_arg(argp, int);
                putchar(i);
                break;
             case 's':
                 lchar = va_arg(argp,char *);
                 fputs(lchar,stdout);
                 break;
              case 'x':
                 i = va_arg(argp,int);
                 s = itoa(i, fmtbuf, 16);
                 fputs(lchar, stdout);
                 break;
               case '%':
                  putchar('%');
                  break;

               default:
                    break;

             }

    }

    va_end(argp);

    }

}

This example created the a simple printf like function using characters within the string to let the function know how to deal with the extra variables used.

Tags: ,