dk package

Submodules

dk.age module

Age (date subtraction) routines.

class dk.age.age(dob, today=None)[source]

Bases: object

The number of years, months, and days since date of birth.

dk.age.birthday_this_year(birthday, today=None)[source]

Return the date of the birthday in the current year.

dk.age.days_ago(n, dato=None)[source]

The date that is n days before dato (or today).

dk.age.next_birthday(birthday, today=None)[source]

Return the date of the next birthday for someone born on date birthday.

dk.age.previous_birthday(birthday, today=None)[source]

Return the previous birthday relative to today.

dk.age.weeks_ago(n, today=None)[source]

The date that is n weeks before today.

dk.age.years_ago(n, today=None)[source]

The date that is n years before today.

dk.asciify module

Convert unicode strings to visually similar ascii representations.

dk.asciify.ascii_name(name)[source]

Convert name from unicode to a ascii representation that (while surely a grave bastardization) can be used as a filename without (ever!) causing problems.

dk.asciify.asciify(s, spaces=None, legal=None, replacement='')[source]

Convert unicode string s to a similarly looking ascii string.

If spaces is specified, runs of space characters are replaced with exactly one spaces.

If legal is specified (as a string), only characters from legal will be in the result, otherwise all characters from ascii 32 to ascii 127 are allowed.

If replacement is passed, then any characters that are elided will be replaced by replacement.

dk.asciify.slug(txt)[source]

Same as above, but intended for URIs.

dk.dkimport module

Convenience function for importing a fqdn from a package. (to hide the baroque nature of __import__).

dk.dkimport.defined_symbols(module, attrfilter=None, itemfilter=None)[source]

Return symbols that are defined in module.

dk.dkimport.dkimport(name)[source]

Import and return the item specified by name:

Usage:

>>> item = dkimport('dk.core.dkimport.dkimport')
>>> item.__name__
'dkimport'
dk.dkimport.dkimport_functions(modname, **kw)[source]

Return all functions from all direct sub-modules of modname.

dk.dkimport.dkimport_star(modname, **kw)[source]

Import all names from module modname, similar to:

from modname import *

Available **kw arguments:

filefilter A function that receives a filename (with extension
but without path) that should return True if the filename should be included.

useful for modularly implementing functionality, yet making it dynamically available from the top namespace:

...path/cmds/a.py
    def a(): ...
...path/cmds/b.py
    def b(): ...
...path/cmds/c.py
    def c(): ...

...path/cmds/__init__.py
    from dk.dkimport import dkimport_star as _dki

    for _item in _dki('..path.cmds'):
        if hasattr(_item, '__name__'):
            globals()[_item.__name__] = _item
dk.dkimport.load_files_from(module_path, module_name, filefilter=None)[source]

Load all .py files in module.

dk.dklogger module

Convenience function for installing a module level logger:

from dk import dklogger
logger = dklogger.dklogger(__name__, debug=1, info=1)
logger.setLevel(dklogger.DEBUG)

to prevent logging to stdout, pass stream=None

dk.dklogger.dklogger(name, debug=False, info=False, fname=None, stream=<open file '<stdout>', mode 'w'>, format='%(asctime)s %(levelname)-7s\n %(pathname)s@%(funcName)s:%(lineno)d %(message)s', datefmt='%Y-%m-%d %H:%M:%S')[source]

dk.findapps module

Module for finding all apps folders.

dk.findapps.appfolder(appname)[source]

Return app folder for appname.

dk.findapps.appfolders()[source]

Find all django app folders, yield absolute paths to the folders.

dk.findapps.appname(folder)[source]

Return the app name for the (app)folder).

dk.findapps.appnames()[source]

Find the name of all the apps.

dk.findapps.is_appfolder(path)[source]

Is the path an app folder?

dk.fstr module

class dk.fstr.fstr[source]

Bases: str

String sub-class with a split() method that splits a given indexes.

Usage:

>>> r = fstr('D2008022002')
>>> print r.split(1, 5, 7, 9)
['D', '2008', '02', '20', '02']
>>> _, year, _ = r.split(1,5)
>>> year
'2008'
split(*ndxs)[source]

dk.grid module

A 2D grid with slicing.

Usage:

>>> t = grid(emptyval=0)
>>> t.apply[:5,:5] = lambda v, (y,x):y*x
>>> t
 0 0 0  0  0
 0 1 2  3  4
 0 2 4  6  8
 0 3 6  9 12
 0 4 8 12 16
>>> t.apply[:5,:5] = lambda v, p:v*2
>>> t
 0 0  0  0  0
 0 2  4  6  8
 0 4  8 12 16
 0 6 12 18 24
 0 8 16 24 32
>>> t2 = grid.copy(t, lambda orig, (y,x):orig[y,x] / 2)
>>> t2
 0 0 0  0  0
 0 1 2  3  4
 0 2 4  6  8
 0 3 6  9 12
 0 4 8 12 16
class dk.grid.Empty(emptyval=None)[source]

Bases: dk.proxy.proxy

setval(v)[source]
class dk.grid.grid(rows=0, cols=0, emptyval=None)[source]

Bases: object

This is a tabular object of two dimensions that supports slice notation.

Deleted = <->
apply
apply_cell(y, x, fn)[source]
apply_iterator()[source]

You can implement the game of life style actions with this iterator:

def average((y,x)):
    return sum(t[y-1:y+1, x-1:x+1]) / 9.0
t.apply[:2, :2] = lambda value, key: average(key)
columns
classmethod copy(tgrid, fn=None)[source]
copy_area()[source]
del_cell(y, x)[source]
empty_col(x)[source]
empty_row(y)[source]
get_cell(y, x)[source]
get_col(x)[source]
get_row(y)[source]
height
insert_col(xpos=None, count=1)[source]
insert_row(ypos=None, count=1)[source]
isempty(y1, x1, y2, x2)[source]
key_iterator()[source]
keyiter(ykey, xkey, debug=False)[source]
keys
lastcol
lastrow
move_area()[source]
next_nonempty_down(ykey, xkey)[source]
next_nonempty_right(ykey, xkey)[source]
notempty(y1, x1, y2, x2)[source]
print_row(y)[source]
purge()[source]

Remove rows and columns that are empty.

raise_indexerror(y, x)[source]
range_check(y, x, throw=True)[source]
remove_col(xpos, count=1)[source]
remove_row(ypos, count=1)[source]
resize(yndx, xndx, pr=False)[source]

Resize so that self[yndx,xndx] is valid.

reverse_key_iterator()[source]
reversed
rows
set_cell(y, x, v)[source]
size
transpose()[source]
value_iterator()[source]
values
width
dk.grid.indexiter(length, ndx)[source]
class dk.grid.point[source]

Bases: tuple

x
y
dk.grid.point_xiter(start, end)[source]
dk.grid.point_yiter(start, end)[source]
class dk.grid.rect(x, y, w, h)[source]

Bases: object

NE
NW
SE
SW
corners
isomorphic(other)[source]

Same shape?

opposite(corner)[source]
x
x2
y
y2
class dk.grid.table_iterator(iterfn)[source]

Bases: object

class dk.grid.value_iterator(gridobj, ykey, xkey)[source]

Bases: object

indices(direction='RD')[source]
iter(direction='RD')[source]
ndx_base(direction='RD')[source]
rect()[source]

dk.iplist module

Collections of distinct ip-addresses.

class dk.iplist.IPList(iterable=())[source]

Bases: object

List (well, actually more of a set) of ip-addresses (well, actually using subnets...).

add(ipaddy)[source]

Add ipaddy to self.

network()[source]

Return the list of networks that cover our list of ip-addys.

pack()[source]

Convert to compressed, but db friendly, notation. This fits ~124 ip addys into 250 bytes, if they are sufficiently contigous.

unpack(b64val)[source]

Reverse steps in pack().

dk.proxy module

Proxy class that forwards __special__ methods too.

class dk.proxy.proxy(obj)[source]

Bases: object

Proxy class that forwards __special__ methods too.

dk.text module

dk.text.u(obj)

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.text.u8(obj)

Return a utf-8 representation of obj.

dk.text.unicode_repr(obj)[source]

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.text.utf8(obj)[source]

Return a utf-8 representation of obj.

dk.utidy module

Micro tidy.

Usage:

>>> print utidy('''
... <form name="FirmaForm" id="FirmaForm" method="POST" autocomplete="off"
... action="." class="fForm"><input type="hidden" name="__cmd"
... value="FirmaForm"></form>hello
... ''')
...
<form action="." autocomplete="off" class="fForm" id="FirmaForm" method="POST" name="FirmaForm">
    <input name="__cmd" type="hidden" value="FirmaForm">
</form>>
hello
class dk.utidy.HtmlTag(txt)[source]

Bases: object

attre = <_sre.SRE_Pattern object>
normalize_attrs(attrs)[source]
normalize_class(val)[source]
normalize_style(val)[source]
dk.utidy.simplify_simple_tags(html)[source]

Put tags without any nested children on one line, i.e. turn:

<h1>
    foo
</h1>

into:

<h1>foo</h1>
dk.utidy.tokenize_html(html)[source]
dk.utidy.utidy(html, level=0, indent=' ', simplify=False)[source]

micro-tidy

Normalizes the html.

dk.utils module

FIXME: many of these really should go in their own modules...

dk.utils.HourMinute(v)[source]

Format 7.10 as 7t 06m.

class dk.utils.Ordered[source]

Bases: dict

Mapping that maintains insertion order. (Should be removed and the adt versions should be used).

items()[source]
keys()[source]
values()[source]
dk.utils.dkpath(pth=None)[source]

Usage

dkpath() => (w:)/xxxxxxx/
         => (/home)/xxxxxxxx/

dkpath('app/') => ../xxxxxxxx/app/
dk.utils.hm_to_float(h, m)[source]

Convert 7, 30 to 7.5 hours.

dk.utils.hour_minute(v)[source]

Convert 7.5 (hours) to (7, 30) i.e. 7 hours and 30 minutes.

dk.utils.html2u8(s)[source]

Convert charrefs for Norwegian vowels to their utf-8 counterparts.

dk.utils.identity(x)[source]

Return the argument unchanged. This function is often called identity in programming language and type theory (the type is t -> t, which turns out to be a difficult type for most classical static type systems).

dk.utils.kr_ore(n)[source]

Convert the øre-value n to a proper NOK string value.

dk.utils.kronestring(kr)[source]

Return a string version of the integer value kr, with space as the thousand-separator.

dk.utils.latin1(obj)[source]

Return a latin-1 representation of obj.

dk.utils.lower_case(s, encoding='u8')[source]

Return a lower cased (byte-)string version of s encoded in encoding.

dk.utils.mk_post(model)[source]

Encode model (a dict-like object) into a dict where:

  • all values are strings
  • None values are removed
  • date values are expanded into year/month/day parts
Note:: this function is superceeded by maint.client._encode_date
which does this transparently for unit tests.
dk.utils.nlat(v)[source]

Normalize and recover from utf-8 stored in varchar columns.

dk.utils.normalize(v)[source]

Return a string version of v such that

normalize(u) == normalize(v) iff not (u != v)

e.g.:

normalize(None) == normalize(‘’) == normalize(u’‘)
dk.utils.orestring(n)[source]

Return a string version of the integer øre value. Either a two-digit string or a dash (as in 5,-).

dk.utils.root()[source]

Return the root of the source tree.

dk.utils.single_line(txt)[source]

Remove multiple spaces and newlines.

dk.utils.srcpath(base, pth)[source]

Return an absolute path based on the relative path pth. Useful in tests, where we don’t know what the absolute path is, and we can’t use relative paths since we don’t know which folder the tests are run from.

In a test file xxxxxxx/foo/test/test_foo.py:

path = 'foo/test'
fp = open(srcpath(path, 'data/testdata.txt'))
dk.utils.title_case(s, encoding='u8')[source]

Return a title cased (byte-)string version of s encoded in encoding.

dk.utils.title_case_lastname(s, encoding='u8')[source]

Return a title cased version of s encoded in encoding. If it looks like s is already title cased, then leave it alone (in case of manual override and complex capitalization rules for last names).

dk.utils.u(obj)

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.utils.u8(obj)

Return a utf-8 representation of obj.

dk.utils.ulower_case(val)[source]

Call val.lower(). Return ‘’ if val is None.

dk.utils.unhtml(s, toencoding=None)[source]

Convert charrefs for Norwegian vowels to their unicode counterparts.

dk.utils.unicode_repr(obj)[source]

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.utils.utf8(obj)[source]

Return a utf-8 representation of obj.

dk.utils.utitle_case(val)[source]

(safer) val.title() implementation.

dk.utils.utitle_case_lastname(s)[source]

Return a title cased version of s. If s contains a recognized special case, then return it unchanged.

Module contents