Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-16 of 16 total

Converting Between Different Naming Convetions

From Sami Hangaslammi's recipe.
import re

def cw2us(x): # capwords to underscore notation
    return re.sub(r'(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', r"_\g<0>", x).lower()

def mc2us(x): # mixed case to underscore notation
    return cw2us(x)

def us2mc(x): # underscore to mixed case notation
    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)

def us2cw(x): # underscore to capwords notation
    s = us2mc(x)
    return s[0].upper()+s[1:]

Result
>>> cw2us("PrintHTML")
'print_html'
>>> cw2us("IOError")
'io_error'
>>> cw2us("SetXYPosition")
'set_xy_position'
>>> cw2us("GetX")
'get_x'

Convert an integer to English written form

English is a peculiar language. english_number() takes an integer, and returns the long, written form most famously used on checks and the like. Algorithm inspired by some old HP online docs.

to_19 = ( 'zero',  'one',   'two',  'three', 'four',   'five',   'six',
          'seven', 'eight', 'nine', 'ten',   'eleven', 'twelve', 'thirteen',
          'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' )
tens  = ( 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')
denom = ( '',
          'thousand',     'million',         'billion',       'trillion',       'quadrillion',
          'quintillion',  'sextillion',      'septillion',    'octillion',      'nonillion',
          'decillion',    'undecillion',     'duodecillion',  'tredecillion',   'quattuordecillion',
          'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion' )

# convert a value < 100 to English.
def _convert_nn(val):
    if val < 20:
        return to_19[val]
    for (dcap, dval) in ((k, 20 + (10 * v)) for (v, k) in enumerate(tens)):
        if dval + 10 > val:
            if val % 10:
                return dcap + '-' + to_19[val % 10]
            return dcap

# convert a value < 1000 to english, special cased because it is the level that kicks 
# off the < 100 special case.  The rest are more general.  This also allows you to
# get strings in the form of 'forty-five hundred' if called directly.
def _convert_nnn(val):
    word = ''
    (mod, rem) = (val % 100, val // 100)
    if rem > 0:
        word = to_19[rem] + ' hundred'
        if mod > 0:
            word = word + ' '
    if mod > 0:
        word = word + _convert_nn(mod)
    return word

def english_number(val):
    if val < 100:
        return _convert_nn(val)
     if val < 1000:
         return _convert_nnn(val)
    for (didx, dval) in ((v - 1, 1000 ** v) for v in range(len(denom))):
        if dval > val:
            mod = 1000 ** didx
            l = val // mod
            r = val - (l * mod)
            ret = _convert_nnn(l) + ' ' + denom[didx]
            if r > 0:
                ret = ret + ', ' + english_number(r)
            return ret

Base 2 Conversion

Converting from base 2 to int is easy
>>> int('1010', 2)
10

The opposite is a bit involved.
>>> number = 1000
>>> hex2bin = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
            "4":"0100", "5":"0101", "6":"0110", "7":"0111",
            "8":"1000", "9":"1001", "A":"1010", "B":"1011",
            "C":"1100", "D":"1101", "E":"1110", "F":"1111"}
>>> "".join([hex2bin[h] for h in '%X'%number]).lstrip('0')
'1111101000'

See the def of toBase2(number) here

Converting between 2 google map tile types

Google maps is a marvelous app.
I try to program a prototype of it on pys60
http://bigbold.com/snippets/posts/show/458

There I only show the default map, not the satellite images.
Retrieving a different mode isn't that difficult.
I read the info from here
http://intepid.com/2005-07-17/21.50/
Then I begin comparing the 2 tile types of the same area
(around California)
http://mt.google.com/mt?v=w2.5&x=20&y=49&zoom=10 (map)
http://kh.google.com/kh?v=3&t=tqtsqrqt (satellite)

Here's the conversion routine between x,y,zoom and quadtree
def quadtree(x,y, zoom):
	out = []
	m = {(0,0):'q', (0,1):'t', (1,0):'r', (1,1):'s'}
	for i in range(17-zoom):
		x, rx = divmod(x, 2)
		y, ry = divmod(y, 2)
		out.insert(0, m[(rx,ry)])
	return 't' + ''.join(out)

Then to convert back
def xyzoom(quad):
	x, y, z = 0, 0, 17
	m = {'q':(0,0), 't':(0,1), 'r':(1,0), 's':(1,1)}
 	for c in quad[1:]:
		x = x*2 + m[c][0]
		y = y*2 + m[c][1]
		z -= 1
	return x, y, z

Using them is simple
>>> quadtree(20,49,10)
'tqtsqrqt'
>>> xyzoom('tqtsqrqt')
(20, 49, 10)
>>> sat_url = 'http://kh.google.com/kh?v=3&t=' + quadtree(20,49,10)

baseX converter

you can use this function to convert an integer into any number system upto base36 (e.g. for TinyURL generation coupled with a global ID counter)

function int2baseX($val,$base=16) {
  if (0==$val) return 0;
  $symbols='0123456789abcdefgihjklmnopqrstuvwxyz';
  $result='';
  $exp=$oldpow=1;
  while($val>0 && $exp<10) {
    $pow=pow($base,$exp++);
    $mod=($val % $pow);
    $result=substr($symbols,$mod/$oldpow,1).$result;
    $val-=$mod;
    $oldpow=$pow;
  }
  return $result;
}

Mass conversion from word to HTML

I got 1000 word files. Each contains 1 main image and some decorations.
(This is actually a big book scanned into 1-file-per-page format)
I need to extract all the images. What do I do?

Python can do some automation using COM. (or something like that)
import pythoncom, win32com.client

app = win32com.client.gencache.EnsureDispatch("Word.Application")

doc = 'C:\\lang\\try\\bdham\\p1'
app.Documents.Open(doc + '.doc')
app.ActiveDocument.SaveAs(doc + '.html', FileFormat=win32com.client.constants.wdFormatHTML)
app.ActiveDocument.Close()
# now repeat with p2, p3, etc.

Actually, I should put it in a loop. But this non-loop version
is easier to read and remember.
« Newer Snippets
Older Snippets »
Showing 11-16 of 16 total