Golay G24

This is a dirty implemenation of Golay correcting code using python.

This is a solution to 18.13 problem 1 from Trappe and Washington’s Crytography book. To run this, you need bash, python, and the numpy libraries. To run, run golay.sh.  The algorithm is located in golay.py

golay.py

#!/usr/bin/env python
 
from numpy import *
import sys
 
geng24 = array([[1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,0,0,0,1,0],
                [0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,1,0,0,0,1],
                [0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,0,0,0],
                [0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,1,1,1,0,0],
                [0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,1,1,1,0],
                [0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,1],
                [0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1],
                [0,0,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1],
                [0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0],
                [0,0,0,0,0,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,0,1,1],
                [0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,1],
                [0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1]])
 
B = array([[1,1,1,0,1,1,1,0,0,0,1,0],
           [1,0,1,1,0,1,1,1,0,0,0,1],
           [1,1,0,1,1,0,1,1,1,0,0,0],
           [1,0,1,0,1,1,0,1,1,1,0,0],
           [1,0,0,1,0,1,1,0,1,1,1,0],
           [1,0,0,0,1,0,1,1,0,1,1,1],
           [1,1,0,0,0,1,0,1,1,0,1,1],
           [1,1,1,0,0,0,1,0,1,1,0,1],
           [1,1,1,1,0,0,0,1,0,1,1,0],
           [1,0,1,1,1,0,0,0,1,0,1,1],
           [1,1,0,1,1,1,0,0,0,1,0,1],
           [0,1,1,1,1,1,1,1,1,1,1,1]])
 
errorvector = array([0,0,0,0,0,0,0,0,0,0,0,0])
 
def weight(obj):
  wt = 0
  for i in obj:
    wt += i
  return wt
 
geng24_transpose = geng24.transpose()
 
#r = array([1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,1,0])
#r = array([0,1,0,0,0,0,1,1,0,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1])
#r = array([0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,0,1,1,1,0,1,1,0,0])
#r = array([1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1])
 
r = []
for i in sys.argv[1].split(','):
  r.append(int(i))
r = array(r)
 
s = (dot(r,geng24_transpose) % 2 )
 
sdotb = (dot(s,B) % 2 )
 
#e = array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
e = zeros( (1,24), dtype=int8)
e = e.flat
 
if weight(s) <= 3:
  print "ERROR CORRECTION 3"
  e = array([s, array([0,0,0,0,0,0,0,0,0,0,0,0])])
  e.shape = (1,24)
  e = e.flat
 
if weight(sdotb) <= 3:
  print "ERROR CORRECTION 4"
  e_new = array([array([0,0,0,0,0,0,0,0,0,0,0,0]), sdotb])
  e_new.shape = (1,24)
  e = (e + e_new) % 2
  e = e.flat
 
for j in range(12,24):
  if weight((geng24[:,j] + s)%2) < 2:
    print "ERROR CORRECTION 5"
    e[j] = 1
    e_new = array([(geng24[:,j]+s)%2, array([0,0,0,0,0,0,0,0,0,0,0,0])])
    e_new.shape = (1,24)
    e = (e + e_new) % 2
    e = e.flat
 
for j in range(0,12):
  if weight((sdotb + B[j,:])%2) <= 2:
    print "ERROR CORRECTION 6"
    e[j] = 1
    e_new = array([array([0,0,0,0,0,0,0,0,0,0,0,0]),((sdotb + B[j,:])%2)])
    e_new.shape = (1, 24)
    e = (e + e_new) % 2
    e = e.flat
 
print "\ne =  [",
for i in e:
  print i,
print "]\n"
 
c = ((e + r)%2)
m = array(c[:12])
 
print "r = ", r
print "c = ", c
print "m = ", m

Here is golay.sh

#!/bin/bash
 
echo "Running with Example Problem"
echo "==========================="
./golay.py 1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,1,0
 
echo "
Running with Problem1"
echo "==========================="
./golay.py 0,1,0,0,0,0,1,1,0,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1
 
echo "
Running with Problem2"
echo "==========================="
./golay.py 0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,0,1,1,1,0,1,1,0,0
 
echo "
Running with Problem3"
echo "==========================="
./golay.py 1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1

isbn-10 validity identifier

Here’s a program that does the isbn error checking.

#!/usr/bin/env python

#this program checks if isbn-10 numbers are valid

import sys

def usage():
  "You're using it wrong!"

try:
  isbn = sys.argv[1].replace('-','')
except:
  usage()

isbnNum = isbn[0:9]
checksumPassed = int(isbn[9:])

sum = 0
index = 10
for i in isbnNum:
  sum += int(i)* index
  index -= 1
print "sum is ", sum
checksum = 11 - (sum % 11)

print 11 - checksum
if checksum == checksumPassed:
  print "isbn checksum is fine"
else:
  print "isbn checksum error"

python anagram finder

This is a silly little program that finds anagrams. Just hangin out practicing python-fu, and this was a challenge I found online.

#!/usr/bin/env python

"""
This is a word descrambler for each word in wordlist.

This may be terribly inefficient, but I only have 10 words
to unscramble, so it's fine

plus it only takes about .1 second per word on my am2 3000
"""

import sys

file = open("./wordlist")
dictionary = []
dictfile = open("/usr/share/dict/words")
for i in dictfile:
  i = i.strip()
  dictionary.append(i)

for scramword in file:
  scramword = scramword.strip()  
  numletters = len(scramword)
  for word in dictionary:
    #first check that lengths are =
    if len(word) == numletters:
      isword = True
      for letter in word:
        if letter not in scramword:
          isword = False
          break
      #by this time most words are gone but there
      #may still be some superfluous guys
      for letter in scramword:
        if letter not in word:
          isword = False
          break   
      if isword:
        print word

Basic TKinter GUI format in python

Though there are many ways to format your gui code, the following seems to work well for me. It is not pretty, but the important thing is just how I laid it out.

Basically, I like making a subclass of frame for almost everything.

#!/usr/bin/env python

from Tkinter import *
import time
import tkMessageBox
import tkFileDialog
import tkSimpleDialog


class Demo(Frame):
  def __init__(self, parent=None):
    Frame.__init__(self, parent)
    self.pack()
    Label(self, text="Basic Demonstration").pack()

    errorbutton = Button(self, text="Error", command=self.showerror)
    errorbutton.bind('', self.showerroronrc) #on hover
    errorbutton.pack(side=TOP, fill=BOTH)
 
    askbutton = Button(self, text="Ask", command=self.ask)
    askbutton.pack(side=TOP, fill=BOTH)


    openbutton = Button(self, text="Open", command=self.open)
    openbutton.pack(side=TOP, fill=BOTH)

    querybutton = Button(self, text="Input", command=self.query)
    querybutton.pack(side=TOP, fill=BOTH)

    Label(self, text="Name").pack(side=LEFT)

    checkoptions = ["check1", "check2", "check3"]
    for i in checkoptions:
      checkbox = Checkbutton(self, text=i, command=self.checkbox)
      checkbox.pack(side=TOP)

    #this is used in the showerror function
    self.ent = Entry(self)
    self.ent.pack(side=RIGHT, fill=X)

  def showerror(self):
    msg = "He's dead, " + self.ent.get()
    tkMessageBox.showerror('Error!', msg)

  def showerroronrc(self, event):
    print "stop hovering!"

  def ask(self):
    self.ynanswer = tkMessageBox.askquestion("question", "Do you like me?")   
    if self.ynanswer == "no":
      print "fine, fuck you, buddy."
      Frame.quit(self)

  def open(self):
    file = tkFileDialog.askopenfilename()
    print file

  def query(self):
    myfloat = tkSimpleDialog.askfloat("Entry", "Enter a number")
    print myfloat 

  def checkbox(self):
    print "Don't check on me, bitch"

if __name__ == '__main__':
  root=Tk()
  Demo(root).pack()

  img = PhotoImage(file="./grass.gif")
  Button(root, image=img).pack(side=RIGHT)
  mainloop()

md5check directories

This is a python script that recursively md5sums all the files in your directory and compares it with another directory.  It is similar, and probably less good than

find /dirone -type f -print0 | md5sum

but this was coded to check if the directory structure copied cleanly to a *windows* box.  It seems to work ok.  TODO: only read line by line if file is over a certain size, else read line by line like it does now.

#!/usr/bin/env python

import os, sys, getopt
from Crypto.Hash import MD5
from Crypto.Hash import SHA

def usage():
  print """
  DESCRIPTION
    compares topdir1 to topdir2 using a hash algorithm

  USAGE
    hashsum.py -h 
      prints this message
    hashsum.py topdir1 topdir2 [sha1|md5]

  """

def sumcont(hasharg, dirname, fnames):
  for file in fnames:
    try:
      myfile = open(os.path.join(dirname, file))
      for i in myfile.readlines():
        hasharg.update(i)
      myfile.close()
    except:
      pass
  print "*",

if len(sys.argv) 3:
  if sys.argv[3].lower() == 'sha1':
    print "HASH ALGORITHM: sha1"
    md5_1 = SHA.new()
    md5_2 = SHA.new()
  else:
    print "HASH ALGORITHM: md5"
else:
  print "HASH ALGORITHM: md5"

os.path.walk(sys.argv[1], sumcont, md5_1)
os.path.walk(sys.argv[2], sumcont, md5_2)
print 'n'
print 'First  dir (',sys.argv[1],') hash : n', md5_1.hexdigest()
print 'Second dir (',sys.argv[2],') hash : n', md5_1.hexdigest()

recursive remove in python

In the book Programming Python’, an entire chapter is dedicated to recursive copyting of directories, recursive deletion, etc.  He uses the os tools to accomplish this.

The reason something like this is necessary is the fact that the os tools do not have a built-in recusive delete.  For example, if in my current directory I had a folder named ‘test2′, I would get the following error when trying to remove it.

>>> os.removedirs(‘./test2′)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “/usr/lib/python2.5/os.py”, line 184, in removedirs
rmdir(name)
OSError: [Errno 39] Directory not empty: ‘./test2′

The book addresses this by doing a walk and deleting all the files first.  There is an easier way.

>>> import shutil
>>> shutil.rmtree(‘./test2′)

In fact, the shutil also include utilities for common recursive tasks that are also addressed in programming python – such as recursively copys and moves.

Follow

Get every new post delivered to your Inbox.