Mostly Linux & Python syntax notes and hyperlinks.

Thursday, May 23, 2013

Python: given two lists of strings, create 2-d dictionary to hold int values, initialized to 0

>>> L1=['A','B','C']
>>> L2=['y','z']
>>> dd=dict()
>>> for x in L2:
...         d=dict()
...         for q in L1:
...             d[q]=0
...         dd[x]=d
...        
>>> dd
{'y': {'A': 0, 'C': 0, 'B': 0}, 'z': {'A': 0, 'C': 0, 'B': 0}}

Then to use it to count stuff:

>>> L3=['Ax','Bz','Cy','By','Cz']
>>> for x in L2:
...       for q in L1:
...           for s in L3:
...               if x in s and q in s:
...                   dd[x][q]+=1
...                  
>>> dd
{'y': {'A': 0, 'C': 1, 'B': 1}, 'z': {'A': 0, 'C': 1, 'B': 1}}

Thursday, May 16, 2013

Python: don't catch an exception if you don't know what to do with it

Big complicated tangle of code. Lots of utility methods called from different places. We got in the habit of every method enclosing a try... Except block.

But sometimes it's better to propagate an exception up to the calling method. It will know what to do about it and be closer to the error logging needed.

We missed catching some error conditions soon enough because they were lost inside a utility that trapped the exception but didn't handle it right.

linux: a tenth of a second from ksh

We needed a time stamp of the format HHMMSST
where HH = hour, MM=minutes SS=seconds and T=one tenth of a second.

If you type "man time" you can see different format strings for days to seconds to nanoseconds:
 %j day of year (001..366)
 %k hour (0..23)
 %M minute (00..59)
 %S second (00..60); the 60 is necessary to accommodate a leap second
 %N nanoseconds (000000000..999999999)


To get the nanoseconds,  you can do

 N=$(date +%N)


This worked great in bash or korn shell.

To get the tenth of a second in the bash shell, it was simple to do: 


$ N=$(date +%N)
$ echo $N 
538595000 
$ t=${N:0:1} 
$ echo $t 


In the korn shell, I got this:

$ t=${N:0:1}
ksh: : bad substitution


I needed to generate the timestamp within an already-written ksh script.
I found two methods that worked in my korn shell script: using "expr" or using "typeset"

Using expr:

$ expr $N : '\(.\{3\}\)'
115
$ expr $N : '\(.\{1\}\)'
1

using typeset 

$ echo $N 
655762000 
$ typeset -L1 t=$N 
$ echo $t
6

I used typeset:

function set_timestamp 
{
    TOSEC=$(date +%H%M%S)
    NANO=$(date +%N)

    typeset -L1 TENTH=$NANO 

    TIMESTAMP=${TOSEC}${TENTH}