desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Set the input stream\'s current position.
Resets the codec buffers used for keeping state.'
| def seek(self, offset, whence=0):
| self.stream.seek(offset, whence)
self.reset()
|
'Return the next decoded line from the input stream.'
| def next(self):
| line = self.readline()
if line:
return line
raise StopIteration
|
'Inherit all other methods from the underlying stream.'
| def __getattr__(self, name, getattr=getattr):
| return getattr(self.stream, name)
|
'Creates a StreamReaderWriter instance.
stream must be a Stream-like object.
Reader, Writer must be factory functions or classes
providing the StreamReader, StreamWriter interface resp.
Error handling is done in the same way as defined for the
StreamWriter/Readers.'
| def __init__(self, stream, Reader, Writer, errors='strict'):
| self.stream = stream
self.reader = Reader(stream, errors)
self.writer = Writer(stream, errors)
self.errors = errors
|
'Return the next decoded line from the input stream.'
| def next(self):
| return self.reader.next()
|
'Inherit all other methods from the underlying stream.'
| def __getattr__(self, name, getattr=getattr):
| return getattr(self.stream, name)
|
'Creates a StreamRecoder instance which implements a two-way
conversion: encode and decode work on the frontend (the
input to .read() and output of .write()) while
Reader and Writer work on the backend (reading and
writing to the stream).
You can use these objects to do transparent direct
recodings from e.g. latin-1 to... | def __init__(self, stream, encode, decode, Reader, Writer, errors='strict'):
| self.stream = stream
self.encode = encode
self.decode = decode
self.reader = Reader(stream, errors)
self.writer = Writer(stream, errors)
self.errors = errors
|
'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__(*args, **kwds):
| if (not args):
raise TypeError("descriptor '__init__' of 'OrderedDict' object needs an argument")
self = args[0]
args = args[1:]
if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
try:
self.__root
... |
'od.__setitem__(i, y) <==> od[i]=y'
| def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
| if (key not in self):
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
return dict_setitem(self, key, value)
|
'od.__delitem__(y) <==> del od[y]'
| def __delitem__(self, key, dict_delitem=dict.__delitem__):
| dict_delitem(self, key)
(link_prev, link_next, _) = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev
|
'od.__iter__() <==> iter(od)'
| def __iter__(self):
| root = self.__root
curr = root[1]
while (curr is not root):
(yield curr[2])
curr = curr[1]
|
'od.__reversed__() <==> reversed(od)'
| def __reversed__(self):
| root = self.__root
curr = root[0]
while (curr is not root):
(yield curr[2])
curr = curr[0]
|
'od.clear() -> None. Remove all items from od.'
| def clear(self):
| 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 (dict.__eq__(self, other) and all(_imap(_eq, self, other)))
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__(*args, **kwds):
| if (not args):
raise TypeError("descriptor '__init__' of 'Counter' object needs an argument")
self = args[0]
args = args[1:]
if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
super(Counter, self).__init__(... |
'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(*args, **kwds):
| if (not args):
raise TypeError("descriptor 'update' of 'Counter' object needs an argument")
self = args[0]
args = args[1:]
if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
iterable = (args[0] if args else... |
'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(*args, **kwds):
| if (not args):
raise TypeError("descriptor 'subtract' of 'Counter' object needs an argument")
self = args[0]
args = args[1:]
if (len(args) > 1):
raise TypeError(('expected at most 1 arguments, got %d' % len(args)))
iterable = (args[0] if args el... |
'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, zip64=None):
| 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)
if (len(chunk) > self._offset):
self._readbuffer = (chunk + self._readbuffer[self._offset:])
self._offset = 0
else:
self._offset -= len(chunk)
return self._readbuffer[self._offset:(s... |
'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 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:
with self.open(zinfo.filename, 'r') as f:
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
|
'The comment text associated with the ZIP file.'
| @property
def comment(self):
| return self._comment
|
'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
should... |
'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):
| arcname = member.filename.replace('/', os.path.sep)
if os.path.altsep:
arcname = arcname.replace(os.path.altsep, os.path.sep)
arcname = os.path.splitdrive(arcname)[1]
arcname = os.path.sep.join((x for x in arcname.split(os.path.sep) if (x not in ('', os.path.curdir, os.path.pardir))))
if (os... |
'Check for errors before writing a file to the archive.'
| def _writecheck(self, zinfo):
| if (zinfo.filename in self.NameToInfo):
import warnings
warnings.warn(('Duplicate name: %r' % zinfo.filename), stacklevel=3)
if (self.mode not in ('w', 'a')):
raise RuntimeError, 'write() requires mode "w" or "a"'
if (not self.fp):
raise RuntimeError, 'At... |
'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
if (zinfo.filename[(-1)] == '/'):
zinfo.external_attr = (16893 << 16)
zinfo.external_attr |= 16... |
'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
try:
if ((self.mode in ('w', 'a')) and self._didModify):
pos1 = self.fp.tell()
for zinfo in self.filelist:
dt = zinfo.date_time
dosdate = ((((dt[0] - 1980) << 9) | (dt[1] << 5)) | dt[2])
dostime ... |
'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 (delim == '\r'):
line = (delim + line)
delim = ''
... |
'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')
if ((time.tzname != self.tzname) or (time.daylight !... |
'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 occurring 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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.