INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
r Write string s into file ( which can be a string ( str or unicode ) or a file instance ).
def spitOut(s, file, binary=False, expand=False): r"""Write string `s` into `file` (which can be a string (`str` or `unicode`) or a `file` instance).""" mode = "w" + ["b",""][not binary] file = _normalizeToFile(file, mode=mode, expand=expand) try: file.write(s) finally: file.close()
r Write all the lines to file ( which can be a string/ unicode or a file handler ).
def spitOutLines(lines, file, expand=False): r"""Write all the `lines` to `file` (which can be a string/unicode or a file handler).""" file = _normalizeToFile(file, mode="w", expand=expand) try: file.writelines(lines) finally: file.close()
r Similar to os. popen3 but returns 2 strings ( stdin stdout ) and the exit code ( unlike popen2 exit is 0 if no problems occured ( for some bizarre reason popen2 returns None... <sigh > ).
def readProcess(cmd, *args): r"""Similar to `os.popen3`, but returns 2 strings (stdin, stdout) and the exit code (unlike popen2, exit is 0 if no problems occured (for some bizarre reason popen2 returns None... <sigh>). FIXME: only works for UNIX; handling of signalled processes. """ import pope...
Run cmd ( which is searched for in the executable path ) with args and return the exit status.
def runProcess(cmd, *args): """Run `cmd` (which is searched for in the executable path) with `args` and return the exit status. In general (unless you know what you're doing) use:: runProcess('program', filename) rather than:: os.system('program %s' % filename) because the latter will...
r Like the normal splitext ( in posixpath ) but doesn t treat dotfiles ( e. g.. emacs ) as extensions. Also uses os. sep instead of/.
def splitext(p): r"""Like the normal splitext (in posixpath), but doesn't treat dotfiles (e.g. .emacs) as extensions. Also uses os.sep instead of '/'.""" root, ext = os.path.splitext(p) # check for dotfiles if (not root or root[-1] == os.sep): # XXX: use '/' or os.sep here??? return (root +...
r Like a partitioning version of filter. Returns [ itemsForWhichFuncReturnedFalse itemsForWhichFuncReturnedTrue ].
def bipart(func, seq): r"""Like a partitioning version of `filter`. Returns ``[itemsForWhichFuncReturnedFalse, itemsForWhichFuncReturnedTrue]``. Example: >>> bipart(bool, [1,None,2,3,0,[],[0]]) [[None, 0, []], [1, 2, 3, [0]]] """ if func is None: func = bool res = [[],[]] for i in...
r Return the position of item in ordered sequence seq using comparison function cmpfunc ( defaults to cmp ) and return the first found position of item or - 1 if item is not in seq. The returned position is NOT guaranteed to be the first occurence of item in seq.
def binarySearchPos(seq, item, cmpfunc=cmp): r"""Return the position of `item` in ordered sequence `seq`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found position of `item`, or -1 if `item` is not in `seq`. The returned position is NOT guaranteed to be the first occu...
r Search an ordered sequence seq for item using comparison function cmpfunc ( defaults to cmp ) and return the first found instance of item or None if item is not in seq. The returned item is NOT guaranteed to be the first occurrence of item in seq.
def binarySearchItem(seq, item, cmpfunc=cmp): r""" Search an ordered sequence `seq` for `item`, using comparison function `cmpfunc` (defaults to ``cmp``) and return the first found instance of `item`, or `None` if item is not in `seq`. The returned item is NOT guaranteed to be the first occurrence of it...
r Rotates a list l steps to the left. Accepts steps > len ( l ) or < 0.
def rotate(l, steps=1): r"""Rotates a list `l` `steps` to the left. Accepts `steps` > `len(l)` or < 0. >>> rotate([1,2,3]) [2, 3, 1] >>> rotate([1,2,3,4],-2) [3, 4, 1, 2] >>> rotate([1,2,3,4],-5) [4, 1, 2, 3] >>> rotate([1,2,3,4],1) [2, 3, 4, 1] >>> l = [1,2,3]; rotate(l) is...
r Like rotate but modifies l in - place.
def iprotate(l, steps=1): r"""Like rotate, but modifies `l` in-place. >>> l = [1,2,3] >>> iprotate(l) is l True >>> l [2, 3, 1] >>> iprotate(iprotate(l, 2), -3) [1, 2, 3] """ if len(l): steps %= len(l) if steps: firstPart = l[:steps] del ...
r Returns all unique items in iterable in the * same * order ( only works if items in seq are hashable ).
def unique(iterable): r"""Returns all unique items in `iterable` in the *same* order (only works if items in `seq` are hashable). """ d = {} return (d.setdefault(x,x) for x in iterable if x not in d)
Returns the elements in iterable that aren t unique ; stops after it found reportMax non - unique elements.
def notUnique(iterable, reportMax=INF): """Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples: >>> list(notUnique([1,1,2,2,3,3])) [1, 2, 3] >>> list(notUnique([1,1,2,2,3,3], 1)) [1] """ hash = {} n=0 if repo...
r Divide iterable in n lists so that every n th element belongs to list n.
def unweave(iterable, n=2): r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to list `n`. Example: >>> unweave((1,2,3,4,5), 3) [[1, 4], [2, 5], [3]] """ res = [[] for i in range(n)] i = 0 for x in iterable: res[i % n].append(x) i += 1 retu...
r weave ( seq1 [ seq2 ] [... ] ) - > iter ( [ seq1 [ 0 ] seq2 [ 0 ]... ] ).
def weave(*iterables): r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]). >>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C'])) [1, 4, 6, 2, 5, 7, 3, 6, 8] Any iterable will work. The first exhausted iterable determines when to stop. FIXME rethink stopping semantics. >>> list...
r Return a list of items in indexable at positions indices.
def atIndices(indexable, indices, default=__unique): r"""Return a list of items in `indexable` at positions `indices`. Examples: >>> atIndices([1,2,3], [1,1,0]) [2, 2, 1] >>> atIndices([1,2,3], [1,1,0,4], 'default') [2, 2, 1, 'default'] >>> atIndices({'a':3, 'b':0}, ['a']) [3] """ ...
r Move an n - item ( default 2 ) windows s steps ( default 1 ) at a time over iterable.
def window(iterable, n=2, s=1): r"""Move an `n`-item (default 2) windows `s` steps (default 1) at a time over `iterable`. Examples: >>> list(window(range(6),2)) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] >>> list(window(range(6),3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)] >>> list(w...
r Iterate n - wise ( default pairwise ) over iter. Examples:
def group(iterable, n=2, pad=__unique): r"""Iterate `n`-wise (default pairwise) over `iter`. Examples: >>> for (first, last) in group("Akira Kurosawa John Ford".split()): ... print "given name: %s surname: %s" % (first, last) ... given name: Akira surname: Kurosawa given name: John sur...
>>> list ( iterate ( lambda x: x// 2 ) ( 128 )) [ 128 64 32 16 8 4 2 1 0 ] >>> list ( iterate ( lambda x: x// 2 n = 2 ) ( 128 )) [ 128 64 ]
def iterate(f, n=None, last=__unique): """ >>> list(iterate(lambda x:x//2)(128)) [128, 64, 32, 16, 8, 4, 2, 1, 0] >>> list(iterate(lambda x:x//2, n=2)(128)) [128, 64] """ if n is not None: def funciter(start): for i in xrange(n): yield start; start = f(start) else: ...
>>> list ( dropwhilenot ( lambda x: x == 3 range ( 10 ))) [ 3 4 5 6 7 8 9 ]
def dropwhilenot(func, iterable): """ >>> list(dropwhilenot(lambda x:x==3, range(10))) [3, 4, 5, 6, 7, 8, 9] """ iterable = iter(iterable) for x in iterable: if func(x): break else: return yield x for x in iterable: yield x
r Repeat each item in iterable n times.
def stretch(iterable, n=2): r"""Repeat each item in `iterable` `n` times. Example: >>> list(stretch(range(3), 2)) [0, 0, 1, 1, 2, 2] """ times = range(n) for item in iterable: for i in times: yield item
r Yield chunks of iterable split at the points in indices:
def splitAt(iterable, indices): r"""Yield chunks of `iterable`, split at the points in `indices`: >>> [l for l in splitAt(range(10), [2,5])] [[0, 1], [2, 3, 4], [5, 6, 7, 8, 9]] splits past the length of `iterable` are ignored: >>> [l for l in splitAt(range(10), [2,5,10])] [[0, 1], [2, 3, 4],...
Return a copy of dict d updated with dict e.
def update(d, e): """Return a copy of dict `d` updated with dict `e`.""" res = copy.copy(d) res.update(e) return res
r Return an inverted version of dict d so that values become keys and vice versa. If multiple keys in d have the same value an error is raised unless allowManyToOne is true in which case one of those key - value pairs is chosen at random for the inversion.
def invertDict(d, allowManyToOne=False): r"""Return an inverted version of dict `d`, so that values become keys and vice versa. If multiple keys in `d` have the same value an error is raised, unless `allowManyToOne` is true, in which case one of those key-value pairs is chosen at random for the inversio...
r Like flatten but lazy.
def iflatten(seq, isSeq=isSeq): r"""Like `flatten` but lazy.""" for elt in seq: if isSeq(elt): for x in iflatten(elt, isSeq): yield x else: yield elt
r Returns a flattened version of a sequence seq as a list. Parameters:
def flatten(seq, isSeq=isSeq): r"""Returns a flattened version of a sequence `seq` as a `list`. Parameters: - `seq`: The sequence to be flattened (any iterable). - `isSeq`: The function called to determine whether something is a sequence (default: `isSeq`). *Beware that this function should ...
>>> positionIf ( lambda x: x > 3 range ( 10 )) 4
def positionIf(pred, seq): """ >>> positionIf(lambda x: x > 3, range(10)) 4 """ for i,e in enumerate(seq): if pred(e): return i return -1
r Return the set union of seq1 and seqs duplicates removed order random.
def union(seq1=(), *seqs): r"""Return the set union of `seq1` and `seqs`, duplicates removed, order random. Examples: >>> union() [] >>> union([1,2,3]) [1, 2, 3] >>> union([1,2,3], {1:2, 5:1}) [1, 2, 3, 5] >>> union((1,2,3), ['a'], "bcd") ['a', 1, 2, 3, 'd', 'b', 'c'] >>> un...
r Return a list with all elements in seq2 removed from seq1 order preserved.
def without(seq1, seq2): r"""Return a list with all elements in `seq2` removed from `seq1`, order preserved. Examples: >>> without([1,2,3,1,2], [1]) [2, 3, 2] """ if isSet(seq2): d2 = seq2 else: d2 = set(seq2) return [elt for elt in seq1 if elt not in d2]
>>> some ( lambda x: x [ 0 False None ] ) False >>> some ( lambda x: x [ None 0 2 3 ] ) 2 >>> some ( operator. eq [ 0 1 2 ] [ 2 1 0 ] ) True >>> some ( operator. eq [ 1 2 ] [ 2 1 ] ) False
def some(predicate, *seqs): """ >>> some(lambda x: x, [0, False, None]) False >>> some(lambda x: x, [None, 0, 2, 3]) 2 >>> some(operator.eq, [0,1,2], [2,1,0]) True >>> some(operator.eq, [1,2], [2,1]) False """ try: if len(seqs) == 1: return ifilter(bool,imap(predicate...
r Like some but only returns True if all the elements of iterables satisfy predicate.
def every(predicate, *iterables): r"""Like `some`, but only returns `True` if all the elements of `iterables` satisfy `predicate`. Examples: >>> every(bool, []) True >>> every(bool, [0]) False >>> every(bool, [1,1]) True >>> every(operator.eq, [1,2,3],[1,2]) True >>> eve...
r Call f n times with args and kwargs. Useful e. g. for simplistic timing.
def nTimes(n, f, *args, **kwargs): r"""Call `f` `n` times with `args` and `kwargs`. Useful e.g. for simplistic timing. Examples: >>> nTimes(3, sys.stdout.write, 'hallo\n') hallo hallo hallo """ for i in xrange(n): f(*args, **kwargs)
r Return the time ( in ms ) it takes to call a function ( the first argument ) with the remaining arguments and kwargs.
def timeCall(*funcAndArgs, **kwargs): r"""Return the time (in ms) it takes to call a function (the first argument) with the remaining arguments and `kwargs`. Examples: To find out how long ``func('foo', spam=1)`` takes to execute, do: ``timeCall(func, foo, spam=1)`` """ func, args = func...
r Replace all ( frm to ) tuples in args in string s.
def replaceStrs(s, *args): r"""Replace all ``(frm, to)`` tuples in `args` in string `s`. >>> replaceStrs("nothing is better than warm beer", ... ('nothing','warm beer'), ('warm beer','nothing')) 'warm beer is better than nothing' """ if args == (): return s mapping = dict((frm,...
r Inverse of escape. >>> unescape ( r \ x41 \ n \ x42 \ n \ x43 ) A \ nB \ nC >>> unescape ( r \ u86c7 ) u \ u86c7 >>> unescape ( u ah ) u ah
def unescape(s): r"""Inverse of `escape`. >>> unescape(r'\x41\n\x42\n\x43') 'A\nB\nC' >>> unescape(r'\u86c7') u'\u86c7' >>> unescape(u'ah') u'ah' """ if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode): return unescapeUnicode(s) else: return unescap...
r Return line and column of pos ( 0 - based! ) in s. Lines start with 1 columns with 0.
def lineAndColumnAt(s, pos): r"""Return line and column of `pos` (0-based!) in `s`. Lines start with 1, columns with 0. Examples: >>> lineAndColumnAt("0123\n56", 5) (2, 0) >>> lineAndColumnAt("0123\n56", 6) (2, 1) >>> lineAndColumnAt("0123\n56", 0) (1, 0) """ if pos >= len(...
r Like print but a function. I. e. prints out all arguments as print would do. Specify output stream like this::
def prin(*args, **kwargs): r"""Like ``print``, but a function. I.e. prints out all arguments as ``print`` would do. Specify output stream like this:: print('ERROR', `out="sys.stderr"``). """ print >> kwargs.get('out',None), " ".join([str(arg) for arg in args])
r Truncate s if necessary to fit into a line of width maxCol ( default: 79 ) also replacing newlines with newlineReplacement ( default None: in which case everything after the first newline is simply discarded ).
def fitString(s, maxCol=79, newlineReplacement=None): r"""Truncate `s` if necessary to fit into a line of width `maxCol` (default: 79), also replacing newlines with `newlineReplacement` (default `None`: in which case everything after the first newline is simply discarded). Examples: >>> fitStr...
r Pickle name and value of all those variables in outOf ( default: all global variables ( as seen from the caller )) that are named in varNamesStr into a file called filename ( if no extension is given. bpickle is appended ). Overwrites file without asking unless you specify overwrite = 0. Load again with loadVars.
def saveVars(filename, varNamesStr, outOf=None, **opts): r"""Pickle name and value of all those variables in `outOf` (default: all global variables (as seen from the caller)) that are named in `varNamesStr` into a file called `filename` (if no extension is given, '.bpickle' is appended). Overwrites file...
r Like saveVars but appends additional variables to file.
def addVars(filename, varNamesStr, outOf=None): r"""Like `saveVars`, but appends additional variables to file.""" filename, varnames, outOf = __saveVarsHelper(filename, varNamesStr, outOf) f = None try: f = open(filename, "rb") h = cPickle.load(f) f.close() h.update(dict...
Return the variables pickled pickled into filename with saveVars as a dict.
def loadDict(filename): """Return the variables pickled pickled into `filename` with `saveVars` as a dict.""" filename = os.path.expanduser(filename) if not splitext(filename)[1]: filename += ".bpickle" f = None try: f = open(filename, "rb") varH = cPickle.load(f) finally: ...
r Load variables pickled with saveVars. Parameters:
def loadVars(filename, ask=True, into=None, only=None): r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the ...
r Create a short info string detailing how a program was invoked. This is meant to be added to a history comment field of a data file were it is important to keep track of what programs modified it and how.
def runInfo(prog=None,vers=None,date=None,user=None,dir=None,args=None): r"""Create a short info string detailing how a program was invoked. This is meant to be added to a history comment field of a data file were it is important to keep track of what programs modified it and how. !!!:`args` should be ...
r Creates functions that print out their argument ( between optional pre and post strings ) and return it unmodified. This is usefull for debugging e. g. parts of expressions without having to modify the behavior of the program.
def makePrintReturner(pre="", post="" ,out=None): r"""Creates functions that print out their argument, (between optional `pre` and `post` strings) and return it unmodified. This is usefull for debugging e.g. parts of expressions, without having to modify the behavior of the program. Example: >...
Returns a verbose version of container instance cont that will execute onGet onSet and onDel ( if not None ) every time __getitem__ __setitem__ and __delitem__ are called passing self key ( and value in the case of set ). E. g:
def asVerboseContainer(cont, onGet=None, onSet=None, onDel=None): """Returns a 'verbose' version of container instance `cont`, that will execute `onGet`, `onSet` and `onDel` (if not `None`) every time __getitem__, __setitem__ and __delitem__ are called, passing `self`, `key` (and `value` in the...
r Convinience function to implement __repr__. kwargs values are repr ed. Special behavior for instance = None: just the arguments are formatted.
def mkRepr(instance, *argls, **kwargs): r"""Convinience function to implement ``__repr__``. `kwargs` values are ``repr`` ed. Special behavior for ``instance=None``: just the arguments are formatted. Example: >>> class Thing: ... def __init__(self, color, shape, taste=None):...
Utility function to remove ** kwargs parsing boiler - plate in __init__:
def d2attrs(*args, **kwargs): """Utility function to remove ``**kwargs`` parsing boiler-plate in ``__init__``: >>> kwargs = dict(name='Bill', age=51, income=1e7) >>> self = ezstruct(); d2attrs(kwargs, self, 'income', 'name'); self ezstruct(income=10000000.0, name='Bill') >>> ...
>>> pairwise ( operator. sub [ 4 3 2 1 - 10 ] ) [ 1 1 1 11 ] >>> import numpy >>> pairwise ( numpy. subtract numpy. array ( [ 4 3 2 1 - 10 ] )) array ( [ 1 1 1 11 ] )
def pairwise(fun, v): """ >>> pairwise(operator.sub, [4,3,2,1,-10]) [1, 1, 1, 11] >>> import numpy >>> pairwise(numpy.subtract, numpy.array([4,3,2,1,-10])) array([ 1, 1, 1, 11]) """ if not hasattr(v, 'shape'): return list(ipairwise(fun,v)) else: return fun(v[:-1],v[...
>>> argmax ( [ 4 2 - 5 ] ) 0 >>> argmax ( [ 4 2 - 5 ] key = abs ) 2 >>> argmax ( [ 4 2 - 5 ] key = abs both = True ) ( 2 5 )
def argmax(iterable, key=None, both=False): """ >>> argmax([4,2,-5]) 0 >>> argmax([4,2,-5], key=abs) 2 >>> argmax([4,2,-5], key=abs, both=True) (2, 5) """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmax = reduce(max, izip(i...
See argmax.
def argmin(iterable, key=None, both=False): """See `argmax`. """ if key is not None: it = imap(key, iterable) else: it = iter(iterable) score, argmin = reduce(min, izip(it, count())) if both: return argmin, score return argmin
Returns true if num is ( sort of ) an integer. >>> isInt ( 3 ) == isInt ( 3. 0 ) == 1 True >>> isInt ( 3. 2 ) False >>> import numpy >>> isInt ( numpy. array ( 1 )) True >>> isInt ( numpy. array ( [ 1 ] )) False
def isInt(num): """Returns true if `num` is (sort of) an integer. >>> isInt(3) == isInt(3.0) == 1 True >>> isInt(3.2) False >>> import numpy >>> isInt(numpy.array(1)) True >>> isInt(numpy.array([1])) False """ try: len(num) # FIXME fails for Numeric but Numeric is...
Similar to map but the instead of collecting the return values of func in a list the items of each return value are instaed collected ( so func must return an iterable type ).
def mapConcat(func, *iterables): """Similar to `map` but the instead of collecting the return values of `func` in a list, the items of each return value are instaed collected (so `func` must return an iterable type). Examples: >>> mapConcat(lambda x:[x], [1,2,3]) [1, 2, 3] >>> mapConcat(la...
>>> list ( unfold ( 1234 lambda x: divmod ( x 10 ))) [:: - 1 ] [ 1 2 3 4 ] >>> sum ( imap ( operator. mul unfold ( 1234 lambda x: divmod ( x 10 )) iterate ( lambda x: x * 10 ) ( 1 ))) 1234 >>> g = unfold ( 1234 lambda x: divmod ( x 10 )) >>> reduce (( lambda ( total pow ) digit: ( total + pow * digit 10 * pow )) g ( 0 ...
def unfold(seed, by, last = __unique): """ >>> list(unfold(1234, lambda x: divmod(x,10)))[::-1] [1, 2, 3, 4] >>> sum(imap(operator.mul,unfold(1234, lambda x:divmod(x,10)), iterate(lambda x:x*10)(1))) 1234 >>> g = unfold(1234, lambda x:divmod(x,10)) >>> reduce((lambda (total,pow),digit:(total...
* R * ight reduce. >>> reduceR ( lambda x y: x/ y [ 1. 2. 3. 4 ] ) == 1./ ( 2./ ( 3./ 4. )) == ( 1./ 2. ) * ( 3./ 4. ) True >>> reduceR ( lambda x y: x - y iter ( [ 1 2 3 ] ) 4 ) == 1 - ( 2 - ( 3 - 4 )) == ( 1 - 2 ) + ( 3 - 4 ) True
def reduceR(f, sequence, initial=__unique): """*R*ight reduce. >>> reduceR(lambda x,y:x/y, [1.,2.,3.,4]) == 1./(2./(3./4.)) == (1./2.)*(3./4.) True >>> reduceR(lambda x,y:x-y, iter([1,2,3]),4) == 1-(2-(3-4)) == (1-2)+(3-4) True """ try: rev = reversed(sequence) except TypeError: rev = re...
Compose funcs to a single function.
def compose(*funcs): """Compose `funcs` to a single function. >>> compose(operator.abs, operator.add)(-2,-3) 5 >>> compose()('nada') 'nada' >>> compose(sorted, set, partial(filter, None))(range(3)[::-1]*2) [1, 2] """ # slightly optimized for most common cases and hence verbose i...
>>> romanNumeral ( 13 ) XIII >>> romanNumeral ( 2944 ) MMCMXLIV
def romanNumeral(n): """ >>> romanNumeral(13) 'XIII' >>> romanNumeral(2944) 'MMCMXLIV' """ if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n) roman = 'I IV V IX X XL L XC C CD D CM M'.split() arabic = [1, 4, 5, 9, 10, 40, 50, 90, 10...
>>> first ( 3 iter ( [ 1 2 3 4 ] )) [ 1 2 3 ] >>> first ( 3 iter ( [ 1 2 3 4 ] ) iter ) #doctest: + ELLIPSIS <itertools. islice object at... > >>> first ( 3 iter ( [ 1 2 3 4 ] ) tuple ) ( 1 2 3 )
def first(n, it, constructor=list): """ >>> first(3,iter([1,2,3,4])) [1, 2, 3] >>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS <itertools.islice object at ...> >>> first(3,iter([1,2,3,4]), tuple) (1, 2, 3) """ return constructor(itertools.islice(it,n))
>>> first ( 10 drop ( 10 xrange ( sys. maxint ) iter )) [ 10 11 12 13 14 15 16 17 18 19 ]
def drop(n, it, constructor=list): """ >>> first(10,drop(10,xrange(sys.maxint),iter)) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] """ return constructor(itertools.islice(it,n,None))
Same as self. dryRun if self. dry else same as self. wetRun.
def run(self, func, *args, **kwargs): """Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``.""" if self.dry: return self.dryRun(func, *args, **kwargs) else: return self.wetRun(func, *args, **kwargs)
Instead of running function with * args and ** kwargs just print out the function call.
def dryRun(self, func, *args, **kwargs): """Instead of running function with `*args` and `**kwargs`, just print out the function call.""" print >> self.out, \ self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs)
Iterate over all the bridges in the system.
def iterbridges(): ''' Iterate over all the bridges in the system. ''' net_files = os.listdir(SYSFS_NET_PATH) for d in net_files: path = os.path.join(SYSFS_NET_PATH, d) if not os.path.isdir(path): continue if os.path.exists(os.path.join(path, b"bridge")): yiel...
Create new bridge with the given name
def addbr(name): ''' Create new bridge with the given name ''' fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name) return Bridge(name)
Iterate over all the interfaces in this bridge.
def iterifs(self): ''' Iterate over all the interfaces in this bridge. ''' if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif") net_files = os.listdir(if_path) for iface in net_files: yield iface
Add the interface with the given name to this bridge. Equivalent to brctl addif [ bridge ] [ interface ].
def addif(self, iface): ''' Add the interface with the given name to this bridge. Equivalent to brctl addif [bridge] [interface]. ''' if type(iface) == ifconfig.Interface: devindex = iface.index else: devindex = ifconfig.Interface(iface).index ifreq = ...
Remove the interface with the given name from this bridge. Equivalent to brctl delif [ bridge ] [ interface ]
def delif(self, iface): ''' Remove the interface with the given name from this bridge. Equivalent to brctl delif [bridge] [interface]''' if type(iface) == ifconfig.Interface: devindex = iface.index else: devindex = ifconfig.Interface(iface).index ifreq...
Brings down the bridge interface and removes it. Equivalent to ifconfig [ bridge ] down && brctl delbr [ bridge ].
def delete(self): ''' Brings down the bridge interface, and removes it. Equivalent to ifconfig [bridge] down && brctl delbr [bridge]. ''' self.down() fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name) return self
Get a random ( i. e. unique ) string identifier
def _get_random_id(): """ Get a random (i.e., unique) string identifier""" symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(symbols) for _ in range(15))
Get a filename of a built - in library file.
def get_lib_filename(category, name): """ Get a filename of a built-in library file. """ base_dir = os.path.dirname(os.path.abspath(__file__)) if category == 'js': filename = os.path.join('js', '{0}.js'.format(name)) elif category == 'css': filename = os.path.join('css', '{0}.css'.format...
Import required Javascript libraries to Jupyter Notebook.
def output_notebook( d3js_url="//d3js.org/d3.v3.min", requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js", html_template=None ): """ Import required Javascript libraries to Jupyter Notebook. """ if html_template is None: html_template = read_lib('ht...
Create HTML code block given the graph Javascript and CSS.
def create_graph_html(js_template, css_template, html_template=None): """ Create HTML code block given the graph Javascript and CSS. """ if html_template is None: html_template = read_lib('html', 'graph') # Create div ID for the graph and give it to the JS and CSS templates so # they can refere...
Return newest compatible version.
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION] True """ java_path = find_executable('java') if not java_path: # Just ignore this...
Iterate over all the interfaces in the system. If physical is true then return only real physical interfaces ( not lo etc ).
def iterifs(physical=True): ''' Iterate over all the interfaces in the system. If physical is true, then return only real physical interfaces (not 'lo', etc).''' net_files = os.listdir(SYSFS_NET_PATH) interfaces = set() virtual = set() for d in net_files: path = os.path.join(SYSFS_NE...
Initialize the library
def init(): ''' Initialize the library ''' globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) globals()["sockfd"] = globals()["sock"].fileno()
Bring up the bridge interface. Equivalent to ifconfig [ iface ] up.
def up(self): ''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags flags = flags | IFF_U...
Return True if the interface is up False otherwise.
def is_up(self): ''' Return True if the interface is up, False otherwise. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags if flags & IFF_UP: ...
Obtain the device s mac address.
def get_mac(self): ''' Obtain the device's mac address. ''' ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14) res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq) address = struct.unpack('16sH14s', res)[2] mac = struct.unpack('6B8x', address) return ":".join(['%0...
Set the device s mac address. Device must be down for this to succeed.
def set_mac(self, newmac): ''' Set the device's mac address. Device must be down for this to succeed. ''' macbytes = [int(i, 16) for i in newmac.split(':')] ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes) fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq)
Convert an interface name to an index value.
def get_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
Ethernet has flow control! The inter - frame pause can be adjusted by auto - negotiation through an ethernet frame type with a simple two - field payload and by setting it explicitly.
def set_pause_param(self, autoneg, rx_pause, tx_pause): """ Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_f...
Return version string.
def get_version(): """Return version string.""" with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
Split a string with comma or space - separated elements into a list.
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
Generate Python 2 code from Python 3 code.
def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False): """Generate Python 2 code from Python 3 code.""" def copy(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst)): shutil.copy(src, dst) return dst return None ...
Default setup hook.
def default_hook(config): """Default setup hook.""" if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or arg.startswith('buil...
Returns the default interface
def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass...
Returns the default gateway
def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] ...
Create the module instance of the GraphiteClient.
def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
def send(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_in...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
def send_dict(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _modul...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
def send_list(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _modul...
Allow the module to be called from the cli.
def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='...
Make a TCP connection to the graphite server on port self. port
def connect(self): """ Make a TCP connection to the graphite server on port self.port """ self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(self.addr) except socket.timeout: raise Graphit...
Tries to reconnect with some delay:
def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5): """ Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and r...
Close the TCP connection with the graphite server.
def disconnect(self): """ Close the TCP connection with the graphite server. """ try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None except Exception: self.socket =...
Dispatch the different steps of sending
def _dispatch_send(self, message): """ Dispatch the different steps of sending """ if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before send" ) sending_functio...
Send _message_ to Graphite Server and attempt reconnect on failure.
def _send_and_reconnect(self, message): """Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the so...
Format a single metric/ value pair and send it to the graphite server.
def send(self, metric, value, timestamp=None, formatter=None): """ Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :...
Format a dict of metric/ values pairs and send them all to the graphite server.
def send_dict(self, data, timestamp=None, formatter=None): """ Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event ...
Check if socket have been monkey patched by gevent
def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): retur...
Covert a string that is ready to be sent to graphite into a tuple
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_mess...
Given a message send it to the graphite server.
def _send(self, message): """ Given a message send it to the graphite server. """ # An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payload. message = self.str2listtuple(message...
Make sure the metric is free of control chars spaces tabs etc.
def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """ if not self._clean_metric_name: return metric_name metric_name = str(metric_name) for _from, _to in self.cleaning_replacement_list: ...