desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return the next decoded line from the input stream.'
def next(self):
data = self.reader.next() (data, bytesencoded) = self.encode(data, self.errors) return data
'Inherit all other methods from the underlying stream.'
def __getattr__(self, name, getattr=getattr):
return getattr(self.stream, name)
'Initialize an ordered dictionary. The signature is the same as regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.'
def __init__(self, *args, **kwds):
if (len(args) > 1): raise TypeError(('expected at most 1 arguments, got %d' % len(args))) try: self.__root except AttributeError: self.__root = root = [] root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds)
'od.__setitem__(i, y) <==> od[i]=y'
def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
if (key not in self): root = self.__root last = root[PREV] last[NEXT] = root[PREV] = self.__map[key] = [last, root, key] dict_setitem(self, key, value)
'od.__delitem__(y) <==> del od[y]'
def __delitem__(self, key, PREV=0, NEXT=1, dict_delitem=dict.__delitem__):
dict_delitem(self, key) (link_prev, link_next, key) = self.__map.pop(key) link_prev[NEXT] = link_next link_next[PREV] = link_prev
'od.__iter__() <==> iter(od)'
def __iter__(self):
(NEXT, KEY) = (1, 2) root = self.__root curr = root[NEXT] while (curr is not root): (yield curr[KEY]) curr = curr[NEXT]
'od.__reversed__() <==> reversed(od)'
def __reversed__(self):
(PREV, KEY) = (0, 2) root = self.__root curr = root[PREV] while (curr is not root): (yield curr[KEY]) curr = curr[PREV]
'od.clear() -> None. Remove all items from od.'
def clear(self):
for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() dict.clear(self)
'od.keys() -> list of keys in od'
def keys(self):
return list(self)
'od.values() -> list of values in od'
def values(self):
return [self[key] for key in self]
'od.items() -> list of (key, value) pairs in od'
def items(self):
return [(key, self[key]) for key in self]
'od.iterkeys() -> an iterator over the keys in od'
def iterkeys(self):
return iter(self)
'od.itervalues -> an iterator over the values in od'
def itervalues(self):
for k in self: (yield self[k])
'od.iteritems -> an iterator over the (key, value) pairs in od'
def iteritems(self):
for k in self: (yield (k, self[k]))
'od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.'
def pop(self, key, default=__marker):
if (key in self): result = self[key] del self[key] return result if (default is self.__marker): raise KeyError(key) return default
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
def setdefault(self, key, default=None):
if (key in self): return self[key] self[key] = default return default
'od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.'
def popitem(self, last=True):
if (not self): raise KeyError('dictionary is empty') key = next((reversed(self) if last else iter(self))) value = self.pop(key) return (key, value)
'od.__repr__() <==> repr(od)'
def __repr__(self, _repr_running={}):
call_key = (id(self), _get_ident()) if (call_key in _repr_running): return '...' _repr_running[call_key] = 1 try: if (not self): return ('%s()' % (self.__class__.__name__,)) return ('%s(%r)' % (self.__class__.__name__, self.items())) finally: del _repr_run...
'Return state information for pickling'
def __reduce__(self):
items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return (self.__class__, (items,))
'od.copy() -> a shallow copy of od'
def copy(self):
return self.__class__(self)
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. If not specified, the value defaults to None.'
@classmethod def fromkeys(cls, iterable, value=None):
self = cls() for key in iterable: self[key] = value return self
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.'
def __eq__(self, other):
if isinstance(other, OrderedDict): return ((len(self) == len(other)) and (self.items() == other.items())) return dict.__eq__(self, other)
'od.__ne__(y) <==> od!=y'
def __ne__(self, other):
return (not (self == other))
'od.viewkeys() -> a set-like object providing a view on od\'s keys'
def viewkeys(self):
return KeysView(self)
'od.viewvalues() -> an object providing a view on od\'s values'
def viewvalues(self):
return ValuesView(self)
'od.viewitems() -> a set-like object providing a view on od\'s items'
def viewitems(self):
return ItemsView(self)
'Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts. >>> c = Counter() # a new, empty counter >>> c = Counter(\'gallahad\') # a new counter from an iterable >>> c =...
def __init__(self, iterable=None, **kwds):
super(Counter, self).__init__() self.update(iterable, **kwds)
'The count of elements not in the Counter is zero.'
def __missing__(self, key):
return 0
'List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. >>> Counter(\'abcdeabcdabcaba\').most_common(3) [(\'a\', 5), (\'b\', 4), (\'c\', 3)]'
def most_common(self, n=None):
if (n is None): return sorted(self.iteritems(), key=_itemgetter(1), reverse=True) return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))
'Iterator over elements repeating each as many times as its count. >>> c = Counter(\'ABCABC\') >>> sorted(c.elements()) [\'A\', \'A\', \'B\', \'B\', \'C\', \'C\'] # Knuth\'s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_f...
def elements(self):
return _chain.from_iterable(_starmap(_repeat, self.iteritems()))
'Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter(\'which\') >>> c.update(\'witch\') # add elements from another iterable >>> d = Counter(\'watch\') >>> c.update(d) # add elements from another cou...
def update(self, iterable=None, **kwds):
if (iterable is not None): if isinstance(iterable, Mapping): if self: self_get = self.get for (elem, count) in iterable.iteritems(): self[elem] = (self_get(elem, 0) + count) else: super(Counter, self).update(iterable...
'Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter(\'which\') >>> c.subtract(\'witch\') # sub...
def subtract(self, iterable=None, **kwds):
if (iterable is not None): self_get = self.get if isinstance(iterable, Mapping): for (elem, count) in iterable.items(): self[elem] = (self_get(elem, 0) - count) else: for elem in iterable: self[elem] = (self_get(elem, 0) - 1) if kwd...
'Return a shallow copy.'
def copy(self):
return self.__class__(self)
'Like dict.__delitem__() but does not raise KeyError for missing values.'
def __delitem__(self, elem):
if (elem in self): super(Counter, self).__delitem__(elem)
'Add counts from two counters. >>> Counter(\'abbb\') + Counter(\'bcc\') Counter({\'b\': 4, \'c\': 2, \'a\': 1})'
def __add__(self, other):
if (not isinstance(other, Counter)): return NotImplemented result = Counter() for (elem, count) in self.items(): newcount = (count + other[elem]) if (newcount > 0): result[elem] = newcount for (elem, count) in other.items(): if ((elem not in self) and (count >...
'Subtract count, but keep only results with positive counts. >>> Counter(\'abbbc\') - Counter(\'bccd\') Counter({\'b\': 2, \'a\': 1})'
def __sub__(self, other):
if (not isinstance(other, Counter)): return NotImplemented result = Counter() for (elem, count) in self.items(): newcount = (count - other[elem]) if (newcount > 0): result[elem] = newcount for (elem, count) in other.items(): if ((elem not in self) and (count <...
'Union is the maximum of value in either of the input counters. >>> Counter(\'abbb\') | Counter(\'bcc\') Counter({\'b\': 3, \'c\': 2, \'a\': 1})'
def __or__(self, other):
if (not isinstance(other, Counter)): return NotImplemented result = Counter() for (elem, count) in self.items(): other_count = other[elem] newcount = (other_count if (count < other_count) else count) if (newcount > 0): result[elem] = newcount for (elem, count)...
'Intersection is the minimum of corresponding counts. >>> Counter(\'abbb\') & Counter(\'bcc\') Counter({\'b\': 1})'
def __and__(self, other):
if (not isinstance(other, Counter)): return NotImplemented result = Counter() for (elem, count) in self.items(): other_count = other[elem] newcount = (count if (count < other_count) else other_count) if (newcount > 0): result[elem] = newcount return result
'Return the per-file header as a string.'
def FileHeader(self):
dt = self.date_time dosdate = ((((dt[0] - 1980) << 9) | (dt[1] << 5)) | dt[2]) dostime = (((dt[3] << 11) | (dt[4] << 5)) | (dt[5] // 2)) if (self.flag_bits & 8): CRC = compress_size = file_size = 0 else: CRC = self.CRC compress_size = self.compress_size file_size = se...
'Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32().'
def _GenerateCRCTable():
poly = 3988292384 table = ([0] * 256) for i in range(256): crc = i for j in range(8): if (crc & 1): crc = (((crc >> 1) & 2147483647) ^ poly) else: crc = ((crc >> 1) & 2147483647) table[i] = crc return table
'Compute the CRC32 primitive on one byte.'
def _crc32(self, ch, crc):
return (((crc >> 8) & 16777215) ^ self.crctable[((crc ^ ord(ch)) & 255)])
'Decrypt a single character.'
def __call__(self, c):
c = ord(c) k = (self.key2 | 2) c = (c ^ (((k * (k ^ 1)) >> 8) & 255)) c = chr(c) self._UpdateKeys(c) return c
'Read and return a line from the stream. If limit is specified, at most limit bytes will be read.'
def readline(self, limit=(-1)):
if ((not self._universal) and (limit < 0)): i = (self._readbuffer.find('\n', self._offset) + 1) if (i > 0): line = self._readbuffer[self._offset:i] self._offset = i return line if (not self._universal): return io.BufferedIOBase.readline(self, limit) ...
'Returns buffered bytes without advancing the position.'
def peek(self, n=1):
if (n > (len(self._readbuffer) - self._offset)): chunk = self.read(n) self._offset -= len(chunk) return self._readbuffer[self._offset:(self._offset + 512)]
'Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached..'
def read(self, n=(-1)):
buf = '' if (n is None): n = (-1) while True: if (n < 0): data = self.read1(n) elif (n > len(buf)): data = self.read1((n - len(buf))) else: return buf if (len(data) == 0): return buf buf += data
'Read up to n bytes with at most one read() system call.'
def read1(self, n):
if ((n < 0) or (n is None)): n = self.MAX_N len_readbuffer = (len(self._readbuffer) - self._offset) if ((self._compress_left > 0) and (n > (len_readbuffer + len(self._unconsumed)))): nbytes = ((n - len_readbuffer) - len(self._unconsumed)) nbytes = max(nbytes, self.MIN_READ_SIZE) ...
'Open the ZIP file with mode read "r", write "w" or append "a".'
def __init__(self, file, mode='r', compression=ZIP_STORED, allowZip64=False):
if (mode not in ('r', 'w', 'a')): raise RuntimeError('ZipFile() requires mode "r", "w", or "a"') if (compression == ZIP_STORED): pass elif (compression == ZIP_DEFLATED): if (not zlib): raise RuntimeError, 'Compression requires the (missing) z...
'Read the directory, making sure we close the file if the format is bad.'
def _GetContents(self):
try: self._RealGetContents() except BadZipfile: if (not self._filePassed): self.fp.close() self.fp = None raise
'Read in the table of contents for the ZIP file.'
def _RealGetContents(self):
fp = self.fp try: endrec = _EndRecData(fp) except IOError: raise BadZipfile('File is not a zip file') if (not endrec): raise BadZipfile, 'File is not a zip file' if (self.debug > 1): print endrec size_cd = endrec[_ECD_SIZE] offset...
'Return a list of file names in the archive.'
def namelist(self):
l = [] for data in self.filelist: l.append(data.filename) return l
'Return a list of class ZipInfo instances for files in the archive.'
def infolist(self):
return self.filelist
'Print a table of contents for the zip file.'
def printdir(self):
print ('%-46s %19s %12s' % ('File Name', 'Modified ', 'Size')) for zinfo in self.filelist: date = ('%d-%02d-%02d %02d:%02d:%02d' % zinfo.date_time[:6]) print ('%-46s %s %12d' % (zinfo.filename, date, zinfo.file_size))
'Read all the files and check the CRC.'
def testzip(self):
chunk_size = (2 ** 20) for zinfo in self.filelist: try: f = self.open(zinfo.filename, 'r') while f.read(chunk_size): pass except BadZipfile: return zinfo.filename
'Return the instance of ZipInfo given \'name\'.'
def getinfo(self, name):
info = self.NameToInfo.get(name) if (info is None): raise KeyError(('There is no item named %r in the archive' % name)) return info
'Set default password for encrypted files.'
def setpassword(self, pwd):
self.pwd = pwd
'Return file bytes (as a string) for name.'
def read(self, name, pwd=None):
return self.open(name, 'r', pwd).read()
'Return file-like object for \'name\'.'
def open(self, name, mode='r', pwd=None):
if (mode not in ('r', 'U', 'rU')): raise RuntimeError, 'open() requires mode "r", "U", or "rU"' if (not self.fp): raise RuntimeError, 'Attempt to read ZIP archive that was already closed' if self._filePassed: zef_file = self.fp else: ...
'Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member\' may be a filename or a ZipInfo object. You can specify a different directory using `path\'.'
def extract(self, member, path=None, pwd=None):
if (not isinstance(member, ZipInfo)): member = self.getinfo(member) if (path is None): path = os.getcwd() return self._extract_member(member, path, pwd)
'Extract all members from the archive to the current working directory. `path\' specifies a different directory to extract to. `members\' is optional and must be a subset of the list returned by namelist().'
def extractall(self, path=None, members=None, pwd=None):
if (members is None): members = self.namelist() for zipinfo in members: self.extract(zipinfo, path, pwd)
'Extract the ZipInfo object \'member\' to a physical file on the path targetpath.'
def _extract_member(self, member, targetpath, pwd):
if ((targetpath[(-1):] in (os.path.sep, os.path.altsep)) and (len(os.path.splitdrive(targetpath)[1]) > 1)): targetpath = targetpath[:(-1)] if (member.filename[0] == '/'): targetpath = os.path.join(targetpath, member.filename[1:]) else: targetpath = os.path.join(targetpath, member.fil...
'Check for errors before writing a file to the archive.'
def _writecheck(self, zinfo):
if (zinfo.filename in self.NameToInfo): if self.debug: print 'Duplicate name:', zinfo.filename if (self.mode not in ('w', 'a')): raise RuntimeError, 'write() requires mode "w" or "a"' if (not self.fp): raise RuntimeError, 'Attempt to write ZIP ...
'Put the bytes from filename into the archive under the name arcname.'
def write(self, filename, arcname=None, compress_type=None):
if (not self.fp): raise RuntimeError('Attempt to write to ZIP archive that was already closed') st = os.stat(filename) isdir = stat.S_ISDIR(st.st_mode) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] if (arcname is None): arcname = filename ...
'Write a file into the archive. The contents is the string \'bytes\'. \'zinfo_or_arcname\' is either a ZipInfo instance or the name of the file in the archive.'
def writestr(self, zinfo_or_arcname, bytes, compress_type=None):
if (not isinstance(zinfo_or_arcname, ZipInfo)): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())[:6]) zinfo.compress_type = self.compression zinfo.external_attr = (384 << 16) else: zinfo = zinfo_or_arcname if (not self.fp): raise Runtim...
'Call the "close()" method in case the user forgot.'
def __del__(self):
self.close()
'Close the file, and for mode "w" and "a" write the ending records.'
def close(self):
if (self.fp is None): return if ((self.mode in ('w', 'a')) and self._didModify): count = 0 pos1 = self.fp.tell() for zinfo in self.filelist: count = (count + 1) dt = zinfo.date_time dosdate = ((((dt[0] - 1980) << 9) | (dt[1] << 5)) | dt[2]) ...
'Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file an...
def writepy(self, pathname, basename=''):
(dir, name) = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, '__init__.py') if os.path.isfile(initname): if basename: basename = ('%s/%s' % (basename, name)) else: basename = name if self.d...
'Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string).'
def _get_codename(self, pathname, basename):
file_py = (pathname + '.py') file_pyc = (pathname + '.pyc') file_pyo = (pathname + '.pyo') if (os.path.isfile(file_pyo) and (os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime)): fname = file_pyo elif ((not os.path.isfile(file_pyc)) or (os.stat(file_pyc).st_mtime < os.stat(file_py).st_m...
'Constructor from field name and value.'
def __init__(self, name, value):
self.name = name self.value = value
'Return printable representation.'
def __repr__(self):
return ('MiniFieldStorage(%r, %r)' % (self.name, self.value))
'Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for intern...
def __init__(self, fp=None, headers=None, outerboundary='', environ=os.environ, keep_blank_values=0, strict_parsing=0):
method = 'GET' self.keep_blank_values = keep_blank_values self.strict_parsing = strict_parsing if ('REQUEST_METHOD' in environ): method = environ['REQUEST_METHOD'].upper() self.qs_on_post = None if ((method == 'GET') or (method == 'HEAD')): if ('QUERY_STRING' in environ): ...
'Return a printable representation.'
def __repr__(self):
return ('FieldStorage(%r, %r, %r)' % (self.name, self.filename, self.value))
'Dictionary style indexing.'
def __getitem__(self, key):
if (self.list is None): raise TypeError, 'not indexable' found = [] for item in self.list: if (item.name == key): found.append(item) if (not found): raise KeyError, key if (len(found) == 1): return found[0] else: return found
'Dictionary style get() method, including \'value\' lookup.'
def getvalue(self, key, default=None):
if (key in self): value = self[key] if (type(value) is type([])): return map(attrgetter('value'), value) else: return value.value else: return default
'Return the first value received.'
def getfirst(self, key, default=None):
if (key in self): value = self[key] if (type(value) is type([])): return value[0].value else: return value.value else: return default
'Return list of received values.'
def getlist(self, key):
if (key in self): value = self[key] if (type(value) is type([])): return map(attrgetter('value'), value) else: return [value.value] else: return []
'Dictionary style keys() method.'
def keys(self):
if (self.list is None): raise TypeError, 'not indexable' return list(set((item.name for item in self.list)))
'Dictionary style has_key() method.'
def has_key(self, key):
if (self.list is None): raise TypeError, 'not indexable' return any(((item.name == key) for item in self.list))
'Dictionary style __contains__ method.'
def __contains__(self, key):
if (self.list is None): raise TypeError, 'not indexable' return any(((item.name == key) for item in self.list))
'Dictionary style len(x) support.'
def __len__(self):
return len(self.keys())
'Internal: read data in query string format.'
def read_urlencoded(self):
qs = self.fp.read(self.length) if self.qs_on_post: qs += ('&' + self.qs_on_post) self.list = list = [] for (key, value) in urlparse.parse_qsl(qs, self.keep_blank_values, self.strict_parsing): list.append(MiniFieldStorage(key, value)) self.skip_lines()
'Internal: read a part that is itself multipart.'
def read_multi(self, environ, keep_blank_values, strict_parsing):
ib = self.innerboundary if (not valid_boundary(ib)): raise ValueError, ('Invalid boundary in multipart form: %r' % (ib,)) self.list = [] if self.qs_on_post: for (key, value) in urlparse.parse_qsl(self.qs_on_post, self.keep_blank_values, self.strict_parsing): se...
'Internal: read an atomic part.'
def read_single(self):
if (self.length >= 0): self.read_binary() self.skip_lines() else: self.read_lines() self.file.seek(0)
'Internal: read binary data.'
def read_binary(self):
self.file = self.make_file('b') todo = self.length if (todo >= 0): while (todo > 0): data = self.fp.read(min(todo, self.bufsize)) if (not data): self.done = (-1) break self.file.write(data) todo = (todo - len(data))
'Internal: read lines until EOF or outerboundary.'
def read_lines(self):
self.file = self.__file = StringIO() if self.outerboundary: self.read_lines_to_outerboundary() else: self.read_lines_to_eof()
'Internal: read lines until EOF.'
def read_lines_to_eof(self):
while 1: line = self.fp.readline((1 << 16)) if (not line): self.done = (-1) break self.__write(line)
'Internal: read lines until outerboundary.'
def read_lines_to_outerboundary(self):
next = ('--' + self.outerboundary) last = (next + '--') delim = '' last_line_lfend = True while 1: line = self.fp.readline((1 << 16)) if (not line): self.done = (-1) break if ((line[:2] == '--') and last_line_lfend): strippedline = line.str...
'Internal: skip lines until outer boundary if defined.'
def skip_lines(self):
if ((not self.outerboundary) or self.done): return next = ('--' + self.outerboundary) last = (next + '--') last_line_lfend = True while 1: line = self.fp.readline((1 << 16)) if (not line): self.done = (-1) break if ((line[:2] == '--') and last_...
'Overridable: return a readable & writable file. The file will be used as follows: - data is written to it - seek(0) - data is read from it The \'binary\' argument is unused -- the file is always opened in binary mode. This version opens a temporary file for reading and writing, and immediately deletes (unlinks) it. T...
def make_file(self, binary=None):
import tempfile return tempfile.TemporaryFile('w+b')
'Set all attributes. Order of methods called matters for dependency reasons. The locale language is set at the offset and then checked again before exiting. This is to make sure that the attributes were not set with a mix of information from more than one locale. This would most likely happen when using threads where...
def __init__(self):
self.lang = _getlang() self.__calc_weekday() self.__calc_month() self.__calc_am_pm() self.__calc_timezone() self.__calc_date_time() if (_getlang() != self.lang): raise ValueError('locale changed during initialization')
'Create keys/values. Order of execution is important for dependency reasons.'
def __init__(self, locale_time=None):
if locale_time: self.locale_time = locale_time else: self.locale_time = LocaleTime() base = super(TimeRE, self) base.__init__({'d': '(?P<d>3[0-1]|[1-2]\\d|0[1-9]|[1-9]| [1-9])', 'f': '(?P<f>[0-9]{1,6})', 'H': '(?P<H>2[0-3]|[0-1]\\d|\\d)', 'I': '(?P<I>1[0-2]|0[1-9]|[1-9])', 'j': '(?P<j...
'Convert a list to a regex string for matching a directive. Want possible matching values to be from longest to shortest. This prevents the possibility of a match occuring for a value that also a substring of a larger value that should have matched (e.g., \'abc\' matching when \'abcdef\' should have been the match).'
def __seqToRE(self, to_convert, directive):
to_convert = sorted(to_convert, key=len, reverse=True) for value in to_convert: if (value != ''): break else: return '' regex = '|'.join((re_escape(stuff) for stuff in to_convert)) regex = ('(?P<%s>%s' % (directive, regex)) return ('%s)' % regex)
'Return regex pattern for the format string. Need to make sure that any characters that might be interpreted as regex syntax are escaped.'
def pattern(self, format):
processed_format = '' regex_chars = re_compile('([\\\\.^$*+?\\(\\){}\\[\\]|])') format = regex_chars.sub('\\\\\\1', format) whitespace_replacement = re_compile('\\s+') format = whitespace_replacement.sub('\\s+', format) while ('%' in format): directive_index = (format.index('%') + 1) ...
'Return a compiled re object for the format string.'
def compile(self, format):
return re_compile(self.pattern(format), IGNORECASE)
'Initialize an instance. Optional argument x controls seeding, as for Random.seed().'
def __init__(self, x=None):
self.seed(x) self.gauss_next = None
'Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or an int or long, hash(a) is used instead.'
def seed(self, a=None):
if (a is None): try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long((time.time() * 256)) super(Random, self).seed(a) self.gauss_next = None
'Return internal state; can be passed to setstate() later.'
def getstate(self):
return (self.VERSION, super(Random, self).getstate(), self.gauss_next)
'Restore internal state from object returned by getstate().'
def setstate(self, state):
version = state[0] if (version == 3): (version, internalstate, self.gauss_next) = state super(Random, self).setstate(internalstate) elif (version == 2): (version, internalstate, self.gauss_next) = state try: internalstate = tuple(((long(x) % (2 ** 32)) for x in in...
'Change the internal state to one that is likely far away from the current state. This method will not be in Py3.x, so it is better to simply reseed.'
def jumpahead(self, n):
s = (repr(n) + repr(self.getstate())) n = int(_hashlib.new('sha512', s).hexdigest(), 16) super(Random, self).jumpahead(n)
'Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. Do not supply the \'int\', \'default\', and \'maxwidth\' arguments.'
def randrange(self, start, stop=None, step=1, int=int, default=None, maxwidth=(1L << BPF)):
istart = int(start) if (istart != start): raise ValueError, 'non-integer arg 1 for randrange()' if (stop is default): if (istart > 0): if (istart >= maxwidth): return self._randbelow(istart) return int((self.random() * istart)) rais...
'Return random integer in range [a, b], including both end points.'
def randint(self, a, b):
return self.randrange(a, (b + 1))