desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Read the nth word of the ESP3x EFUSE region.'
| def read_efuse(self, n):
| return self.read_reg((self.EFUSE_REG_BASE + (4 * n)))
|
'Read MAC from EFUSE region'
| def read_mac(self):
| words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack('>II', *words)
bitstring = bitstring[2:8]
try:
return tuple((ord(b) for b in bitstring))
except TypeError:
return tuple(bitstring)
|
'Return a new ImageSegment with same data, but mapped at
a new address.'
| def copy_with_new_addr(self, new_addr):
| return ImageSegment(new_addr, self.data, 0)
|
'Return a new ImageSegment which splits "split_len" bytes
from the beginning of the data. Remaining bytes are kept in
this segment object (and the start address is adjusted to match.)'
| def split_image(self, split_len):
| result = copy.copy(self)
result.data = self.data[:split_len]
self.data = self.data[split_len:]
self.addr += split_len
self.file_offs = None
result.file_offs = None
return result
|
'Load the next segment from the image file'
| def load_segment(self, f, is_irom_segment=False):
| file_offs = f.tell()
(offset, size) = struct.unpack('<II', f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if (len(segment_data) < size):
raise FatalError(('End of file reading segment 0x%x, length %d (actual lengt... |
'Save the next segment to the image file, return next checksum value if provided'
| def save_segment(self, f, segment, checksum=None):
| f.write(struct.pack('<II', segment.addr, len(segment.data)))
f.write(segment.data)
if (checksum is not None):
return ESPLoader.checksum(segment.data, checksum)
|
'Return ESPLoader checksum from end of just-read image'
| def read_checksum(self, f):
| align_file_position(f, 16)
return ord(f.read(1))
|
'Calculate checksum of loaded image, based on segments in
segment array.'
| def calculate_checksum(self):
| checksum = ESPLoader.ESP_CHECKSUM_MAGIC
for seg in self.segments:
if seg.include_in_checksum:
checksum = ESPLoader.checksum(seg.data, checksum)
return checksum
|
'Append ESPLoader checksum to the just-written image'
| def append_checksum(self, f, checksum):
| align_file_position(f, 16)
f.write(struct.pack('B', checksum))
|
'Returns True if an address starts in the irom region.
Valid for ESP8266 only.'
| def is_irom_addr(self, addr):
| return (ESP8266ROM.IROM_MAP_START <= addr < ESP8266ROM.IROM_MAP_END)
|
'Derive a default output name from the ELF name.'
| def default_output_name(self, input_file):
| return (input_file + '-')
|
'Save a set of V1 images for flashing. Parameter is a base filename.'
| def save(self, basename):
| irom_segment = self.get_irom_segment()
if (irom_segment is not None):
with open(('%s0x%05x.bin' % (basename, (irom_segment.addr - ESP8266ROM.IROM_MAP_START))), 'wb') as f:
f.write(irom_segment.data)
normal_segments = self.get_non_irom_segments()
with open(('%s0x00000.bin' % basename)... |
'Derive a default output name from the ELF name.'
| def default_output_name(self, input_file):
| irom_segment = self.get_irom_segment()
if (irom_segment is not None):
irom_offs = (irom_segment.addr - ESP8266ROM.IROM_MAP_START)
else:
irom_offs = 0
return ('%s-0x%05x.bin' % (os.path.splitext(input_file)[0], (irom_offs & (~ (ESPLoader.FLASH_SECTOR_SIZE - 1)))))
|
'Derive a default output name from the ELF name.'
| def default_output_name(self, input_file):
| return ('%s.bin' % os.path.splitext(input_file)[0])
|
'Return a fatal error object that appends the hex values of
\'result\' as a string formatted argument.'
| @staticmethod
def WithResult(message, result):
| message += (' (result was %s)' % hexify(result))
return FatalError(message)
|
'Return the raw (unformatted) numeric value of the efuse bits
Returns a simple integer or (for some subclasses) a bitstring.'
| def get_raw(self):
| value = self.esp.read_efuse(self.data_reg_offs)
return ((value & self.mask) >> self.shift)
|
'Get a formatted version of the efuse value, suitable for display'
| def get(self):
| return self.get_raw()
|
'Return true if the efuse is readable by software'
| def is_readable(self):
| if (self.read_disable_bit is None):
return True
value = ((self.esp.read_efuse(0) >> 16) & 15)
return ((value & (1 << self.read_disable_bit)) == 0)
|
'Run esptool with the specified arguments. --chip, --port and --baud
are filled in automatically from the command line. (can override default baud rate with baud param.)
Additional args passed in args parameter as a string.
Returns output from esptool.py as a string if there is any. Raises an exception if esptool.py fa... | def run_esptool(self, args, baud=None):
| if (baud is None):
baud = default_baudrate
cmd = ([sys.executable, ESPTOOL_PY, '--chip', chip, '--port', serialport, '--baud', str(baud)] + args.split(' '))
print ('Running %s...' % ' '.join(cmd))
try:
output = subprocess.check_output([str(s) for s in cmd], cwd=TEST_DIR, stderr=... |
'Run esptool.py similar to run_esptool, but expect an
error.
Verifies the error is an expected error not an unhandled exception,
and returns the output from esptool.py as a string.'
| def run_esptool_error(self, args, baud=None):
| with self.assertRaises(subprocess.CalledProcessError) as fail:
self.run_esptool(args, baud)
failure = fail.exception
self.assertEqual(RETURN_CODE_FATAL_ERROR, failure.returncode)
return failure.output.decode('utf-8')
|
'Read contents of flash back, return to caller.'
| def readback(self, offset, length):
| tf = tempfile.NamedTemporaryFile(delete=False)
self.tempfiles.append(tf.name)
tf.close()
self.run_esptool(('read_flash %d %d %s' % (offset, length, tf.name)))
with open(tf.name, 'rb') as f:
rb = f.read()
self.assertEqual(length, len(rb), ('read_flash length %d offset ... |
'Verify writing at an offset actually writes to that offset.'
| def test_correct_offset(self):
| self.run_esptool('write_flash 0x2000 images/sector.bin')
time.sleep(0.1)
three_sectors = self.readback(0, 12288)
last_sector = three_sectors[8192:]
with open('images/sector.bin', 'rb') as f:
ct = f.read()
self.assertEqual(last_sector, ct)
|
'Verify writing at an offset actually writes to that offset.'
| def test_correct_offset(self):
| res = self.run_esptool('flash_id')
self.assertTrue(('Manufacturer:' in res))
self.assertTrue(('Device:' in res))
|
'Assert an esptool binary image object contains
the data for a particular ELF section.'
| def assertImageContainsSection(self, image, elf, section_name):
| with open(elf, 'rb') as f:
e = ELFFile(f)
section = e.get_section_by_name(section_name)
self.assertTrue(section, ('%s should be in the ELF' % section_name))
sh_addr = section.header.sh_addr
data = section.data()
for seg in sorted(image.segments, key=(la... |
'Run esptool.py image_info on a binary file,
assert no red flags about contents.'
| def assertImageInfo(self, binpath, chip='esp8266'):
| cmd = [sys.executable, ESPTOOL_PY, '--chip', chip, 'image_info', binpath]
try:
output = subprocess.check_output(cmd).decode('utf-8')
print output
except subprocess.CalledProcessError as e:
print e.output
raise
self.assertFalse(('invalid' in output), 'Checksum calculati... |
'Run elf2image on elf_path'
| def run_elf2image(self, chip, elf_path, version=None, extra_args=[]):
| cmd = [sys.executable, ESPTOOL_PY, '--chip', chip, 'elf2image']
if (version is not None):
cmd += ['--version', str(version)]
cmd += ([elf_path] + extra_args)
print ('Executing %s' % ' '.join(cmd))
try:
output = str(subprocess.check_output(cmd))
print output
self... |
'RFC doesn\'t contain test vectors for SECP256k1 used in bitcoin.
This vector has been computed by Golang reference implementation instead.'
| def test_SECP256k1(self):
| self._do(generator=SECP256k1.generator, secexp=int('9d0219792467d7d37b4d43298a7d0c05', 16), hsh=sha256(b('sample')).digest(), hash_func=sha256, expected=int('8fa1f95d514760e498f28957b824ee6ec39ed64826ff4fecc2b5739ec45b91cd', 16))
|
'Calculates \'k\' from data itself, removing the need for strong
random generator and producing deterministic (reproducible) signatures.
See RFC 6979 for more details.'
| def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string):
| secexp = self.privkey.secret_multiplier
k = rfc6979.generate_k(self.curve.generator.order(), secexp, hashfunc, digest)
return self.sign_digest(digest, sigencode=sigencode, k=k)
|
'hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nist256p is
ok, but SHA256 with nist192p is not. (In the 2**-96ish unlikely event
of a hash output larger than the curve orde... | def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None):
| hashfunc = (hashfunc or self.default_hashfunc)
h = hashfunc(data).digest()
return self.sign_digest(h, entropy, sigencode, k)
|
'The curve of points satisfying y^2 = x^3 + a*x + b (mod p).'
| def __init__(self, p, a, b):
| self.__p = p
self.__a = a
self.__b = b
|
'Is the point (x,y) on this curve?'
| def contains_point(self, x, y):
| return ((((y * y) - ((((x * x) * x) + (self.__a * x)) + self.__b)) % self.__p) == 0)
|
'curve, x, y, order; order (optional) is the order of this point.'
| def __init__(self, curve, x, y, order=None):
| self.__curve = curve
self.__x = x
self.__y = y
self.__order = order
if self.__curve:
assert self.__curve.contains_point(x, y)
if order:
assert ((self * order) == INFINITY)
|
'Return True if the points are identical, False otherwise.'
| def __eq__(self, other):
| if ((self.__curve == other.__curve) and (self.__x == other.__x) and (self.__y == other.__y)):
return True
else:
return False
|
'Add one point to another point.'
| def __add__(self, other):
| if (other == INFINITY):
return self
if (self == INFINITY):
return other
assert (self.__curve == other.__curve)
if (self.__x == other.__x):
if (((self.__y + other.__y) % self.__curve.p()) == 0):
return INFINITY
else:
return self.double()
p = sel... |
'Multiply a point by an integer.'
| def __mul__(self, other):
| def leftmost_bit(x):
assert (x > 0)
result = 1
while (result <= x):
result = (2 * result)
return (result // 2)
e = other
if self.__order:
e = (e % self.__order)
if (e == 0):
return INFINITY
if (self == INFINITY):
return INFINITY
... |
'Multiply a point by an integer.'
| def __rmul__(self, other):
| return (self * other)
|
'Return a new point that is twice the old.'
| def double(self):
| if (self == INFINITY):
return INFINITY
p = self.__curve.p()
a = self.__curve.a()
l = (((((3 * self.__x) * self.__x) + a) * numbertheory.inverse_mod((2 * self.__y), p)) % p)
x3 = (((l * l) - (2 * self.__x)) % p)
y3 = (((l * (self.__x - x3)) - self.__y) % p)
return Point(self.__curve, ... |
'generator is the Point that generates the group,
point is the Point that defines the public key.'
| def __init__(self, generator, point):
| self.curve = generator.curve()
self.generator = generator
self.point = point
n = generator.order()
if (not n):
raise RuntimeError('Generator point must have order.')
if (not ((n * point) == ellipticcurve.INFINITY)):
raise RuntimeError('Generator point order i... |
'Verify that signature is a valid signature of hash.
Return True if the signature is valid.'
| def verifies(self, hash, signature):
| G = self.generator
n = G.order()
r = signature.r
s = signature.s
if ((r < 1) or (r > (n - 1))):
return False
if ((s < 1) or (s > (n - 1))):
return False
c = numbertheory.inverse_mod(s, n)
u1 = ((hash * c) % n)
u2 = ((r * c) % n)
xy = ((u1 * G) + (u2 * self.point))... |
'public_key is of class Public_key;
secret_multiplier is a large integer.'
| def __init__(self, public_key, secret_multiplier):
| self.public_key = public_key
self.secret_multiplier = secret_multiplier
|
'Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
single signature. Also, if an attacker knows a few hi... | def sign(self, hash, random_k):
| G = self.public_key.generator
n = G.order()
k = (random_k % n)
p1 = (k * G)
r = p1.x()
if (r == 0):
raise RuntimeError('amazingly unlucky random number r')
s = ((numbertheory.inverse_mod(k, n) * (hash + ((self.secret_multiplier * r) % n))) % n)
if (s == 0):
ra... |
'Encrypt a block of plain text using the AES block cipher.'
| def encrypt(self, plaintext):
| if (len(plaintext) != 16):
raise ValueError('wrong block length')
rounds = (len(self._Ke) - 1)
(s1, s2, s3) = [1, 2, 3]
a = [0, 0, 0, 0]
t = [(_compact_word(plaintext[(4 * i):((4 * i) + 4)]) ^ self._Ke[0][i]) for i in xrange(0, 4)]
for r in xrange(1, rounds):
for i in xrang... |
'Decrypt a block of cipher text using the AES block cipher.'
| def decrypt(self, ciphertext):
| if (len(ciphertext) != 16):
raise ValueError('wrong block length')
rounds = (len(self._Kd) - 1)
(s1, s2, s3) = [3, 2, 1]
a = [0, 0, 0, 0]
t = [(_compact_word(ciphertext[(4 * i):((4 * i) + 4)]) ^ self._Kd[0][i]) for i in xrange(0, 4)]
for r in xrange(1, rounds):
for i in xra... |
'Increment the counter (overflow rolls back to 0).'
| def increment(self):
| for i in xrange((len(self._counter) - 1), (-1), (-1)):
self._counter[i] += 1
if (self._counter[i] < 256):
break
self._counter[i] = 0
else:
self._counter = ([0] * len(self._counter))
|
'Provide bytes to encrypt (or decrypt), returning any bytes
possible from this or any previous calls to feed.
Call with None or an empty string to flush the mode of
operation and return any final bytes; no further calls to
feed may be made.'
| def feed(self, data=None):
| if (self._buffer is None):
raise ValueError('already finished feeder')
if (not data):
result = self._final(self._buffer, self._padding)
self._buffer = None
return result
self._buffer += to_bufferable(data)
result = to_bufferable('')
while (len(self._buffer) > 16... |
'Go to the location of the first blank on the given line,
returning the index of the last non-blank character.'
| def _end_of_line(self, y):
| last = self.maxx
while True:
if (curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP):
last = min(self.maxx, (last + 1))
break
elif (last == 0):
break
last = (last - 1)
return last
|
'Process a single editing command.'
| def do_command(self, ch):
| (y, x) = self.win.getyx()
self.lastcmd = ch
if curses.ascii.isprint(ch):
if ((y < self.maxy) or (x < self.maxx)):
self._insert_printable_char(ch)
elif (ch == curses.ascii.SOH):
self.win.move(y, 0)
elif (ch in (curses.ascii.STX, curses.KEY_LEFT, curses.ascii.BS, curses.KEY... |
'Collect and return the contents of the window.'
| def gather(self):
| result = ''
for y in range((self.maxy + 1)):
self.win.move(y, 0)
stop = self._end_of_line(y)
if ((stop == 0) and self.stripspaces):
continue
for x in range((self.maxx + 1)):
if (self.stripspaces and (x > stop)):
break
result = (... |
'Edit in the widget window and collect the results.'
| def edit(self, validate=None):
| while 1:
ch = self.win.getch()
if validate:
ch = validate(ch)
if (not ch):
continue
if (not self.do_command(ch)):
break
self.win.refresh()
return self.gather()
|
'Constructor.'
| def __init__(self, path=None, profile=None):
| if (profile is None):
profile = MH_PROFILE
self.profile = os.path.expanduser(profile)
if (path is None):
path = self.getprofile('Path')
if (not path):
path = PATH
if ((not os.path.isabs(path)) and (path[0] != '~')):
path = os.path.join('~', path)
path = os.path.ex... |
'String representation.'
| def __repr__(self):
| return ('MH(%r, %r)' % (self.path, self.profile))
|
'Routine to print an error. May be overridden by a derived class.'
| def error(self, msg, *args):
| sys.stderr.write(('MH error: %s\n' % (msg % args)))
|
'Return a profile entry, None if not found.'
| def getprofile(self, key):
| return pickline(self.profile, key)
|
'Return the path (the name of the collection\'s directory).'
| def getpath(self):
| return self.path
|
'Return the name of the current folder.'
| def getcontext(self):
| context = pickline(os.path.join(self.getpath(), 'context'), 'Current-Folder')
if (not context):
context = 'inbox'
return context
|
'Set the name of the current folder.'
| def setcontext(self, context):
| fn = os.path.join(self.getpath(), 'context')
f = open(fn, 'w')
f.write(('Current-Folder: %s\n' % context))
f.close()
|
'Return the names of the top-level folders.'
| def listfolders(self):
| folders = []
path = self.getpath()
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isdir(fullname):
folders.append(name)
folders.sort()
return folders
|
'Return the names of the subfolders in a given folder
(prefixed with the given folder name).'
| def listsubfolders(self, name):
| fullname = os.path.join(self.path, name)
nlinks = os.stat(fullname).st_nlink
if (nlinks <= 2):
return []
subfolders = []
subnames = os.listdir(fullname)
for subname in subnames:
fullsubname = os.path.join(fullname, subname)
if os.path.isdir(fullsubname):
name_... |
'Return the names of all folders and subfolders, recursively.'
| def listallfolders(self):
| return self.listallsubfolders('')
|
'Return the names of subfolders in a given folder, recursively.'
| def listallsubfolders(self, name):
| fullname = os.path.join(self.path, name)
nlinks = os.stat(fullname).st_nlink
if (nlinks <= 2):
return []
subfolders = []
subnames = os.listdir(fullname)
for subname in subnames:
if ((subname[0] == ',') or isnumeric(subname)):
continue
fullsubname = os.path.joi... |
'Return a new Folder object for the named folder.'
| def openfolder(self, name):
| return Folder(self, name)
|
'Create a new folder (or raise os.error if it cannot be created).'
| def makefolder(self, name):
| protect = pickline(self.profile, 'Folder-Protect')
if (protect and isnumeric(protect)):
mode = int(protect, 8)
else:
mode = FOLDER_PROTECT
os.mkdir(os.path.join(self.getpath(), name), mode)
|
'Delete a folder. This removes files in the folder but not
subdirectories. Raise os.error if deleting the folder itself fails.'
| def deletefolder(self, name):
| fullname = os.path.join(self.getpath(), name)
for subname in os.listdir(fullname):
fullsubname = os.path.join(fullname, subname)
try:
os.unlink(fullsubname)
except os.error:
self.error(('%s not deleted, continuing...' % fullsubname))
os.rmdir(fullname... |
'Constructor.'
| def __init__(self, mh, name):
| self.mh = mh
self.name = name
if (not os.path.isdir(self.getfullname())):
raise Error, ('no folder %s' % name)
|
'String representation.'
| def __repr__(self):
| return ('Folder(%r, %r)' % (self.mh, self.name))
|
'Error message handler.'
| def error(self, *args):
| self.mh.error(*args)
|
'Return the full pathname of the folder.'
| def getfullname(self):
| return os.path.join(self.mh.path, self.name)
|
'Return the full pathname of the folder\'s sequences file.'
| def getsequencesfilename(self):
| return os.path.join(self.getfullname(), MH_SEQUENCES)
|
'Return the full pathname of a message in the folder.'
| def getmessagefilename(self, n):
| return os.path.join(self.getfullname(), str(n))
|
'Return list of direct subfolders.'
| def listsubfolders(self):
| return self.mh.listsubfolders(self.name)
|
'Return list of all subfolders.'
| def listallsubfolders(self):
| return self.mh.listallsubfolders(self.name)
|
'Return the list of messages currently present in the folder.
As a side effect, set self.last to the last message (or 0).'
| def listmessages(self):
| messages = []
match = numericprog.match
append = messages.append
for name in os.listdir(self.getfullname()):
if match(name):
append(name)
messages = map(int, messages)
messages.sort()
if messages:
self.last = messages[(-1)]
else:
self.last = 0
retu... |
'Return the set of sequences for the folder.'
| def getsequences(self):
| sequences = {}
fullname = self.getsequencesfilename()
try:
f = open(fullname, 'r')
except IOError:
return sequences
while 1:
line = f.readline()
if (not line):
break
fields = line.split(':')
if (len(fields) != 2):
self.error(('b... |
'Write the set of sequences back to the folder.'
| def putsequences(self, sequences):
| fullname = self.getsequencesfilename()
f = None
for (key, seq) in sequences.iteritems():
s = IntSet('', ' ')
s.fromlist(seq)
if (not f):
f = open(fullname, 'w')
f.write(('%s: %s\n' % (key, s.tostring())))
if (not f):
try:
os.unlink(fu... |
'Return the current message. Raise Error when there is none.'
| def getcurrent(self):
| seqs = self.getsequences()
try:
return max(seqs['cur'])
except (ValueError, KeyError):
raise Error, 'no cur message'
|
'Set the current message.'
| def setcurrent(self, n):
| updateline(self.getsequencesfilename(), 'cur', str(n), 0)
|
'Parse an MH sequence specification into a message list.
Attempt to mimic mh-sequence(5) as close as possible.
Also attempt to mimic observed behavior regarding which
conditions cause which error messages.'
| def parsesequence(self, seq):
| all = self.listmessages()
if (not all):
raise Error, ('no messages in %s' % self.name)
if (seq == 'all'):
return all
i = seq.find(':')
if (i >= 0):
(head, dir, tail) = (seq[:i], '', seq[(i + 1):])
if (tail[:1] in '-+'):
(dir, tail) = (tail[:1], ta... |
'Internal: parse a message number (or cur, first, etc.).'
| def _parseindex(self, seq, all):
| if isnumeric(seq):
try:
return int(seq)
except (OverflowError, ValueError):
return sys.maxint
if (seq in ('cur', '.')):
return self.getcurrent()
else:
if (seq == 'first'):
return all[0]
if (seq == 'last'):
return all[(-1... |
'Open a message -- returns a Message object.'
| def openmessage(self, n):
| return Message(self, n)
|
'Remove one or more messages -- may raise os.error.'
| def removemessages(self, list):
| errors = []
deleted = []
for n in list:
path = self.getmessagefilename(n)
commapath = self.getmessagefilename((',' + str(n)))
try:
os.unlink(commapath)
except os.error:
pass
try:
os.rename(path, commapath)
except os.error as... |
'Refile one or more messages -- may raise os.error.
\'tofolder\' is an open folder object.'
| def refilemessages(self, list, tofolder, keepsequences=0):
| errors = []
refiled = {}
for n in list:
ton = (tofolder.getlast() + 1)
path = self.getmessagefilename(n)
topath = tofolder.getmessagefilename(ton)
try:
os.rename(path, topath)
except os.error:
try:
shutil.copy2(path, topath)
... |
'Helper for refilemessages() to copy sequences.'
| def _copysequences(self, fromfolder, refileditems):
| fromsequences = fromfolder.getsequences()
tosequences = self.getsequences()
changed = 0
for (name, seq) in fromsequences.items():
try:
toseq = tosequences[name]
new = 0
except KeyError:
toseq = []
new = 1
for (fromn, ton) in refiled... |
'Move one message over a specific destination message,
which may or may not already exist.'
| def movemessage(self, n, tofolder, ton):
| path = self.getmessagefilename(n)
f = open(path)
f.close()
del f
topath = tofolder.getmessagefilename(ton)
backuptopath = tofolder.getmessagefilename((',%d' % ton))
try:
os.rename(topath, backuptopath)
except os.error:
pass
try:
os.rename(path, topath)
exc... |
'Copy one message over a specific destination message,
which may or may not already exist.'
| def copymessage(self, n, tofolder, ton):
| path = self.getmessagefilename(n)
f = open(path)
f.close()
del f
topath = tofolder.getmessagefilename(ton)
backuptopath = tofolder.getmessagefilename((',%d' % ton))
try:
os.rename(topath, backuptopath)
except os.error:
pass
ok = 0
try:
tofolder.setlast(Non... |
'Create a message, with text from the open file txt.'
| def createmessage(self, n, txt):
| path = self.getmessagefilename(n)
backuppath = self.getmessagefilename((',%d' % n))
try:
os.rename(path, backuppath)
except os.error:
pass
ok = 0
BUFSIZE = 16384
try:
f = open(path, 'w')
while 1:
buf = txt.read(BUFSIZE)
if (not buf):
... |
'Remove one or more messages from all sequences (including last)
-- but not from \'cur\'!!!'
| def removefromallsequences(self, list):
| if (hasattr(self, 'last') and (self.last in list)):
del self.last
sequences = self.getsequences()
changed = 0
for (name, seq) in sequences.items():
if (name == 'cur'):
continue
for n in list:
if (n in seq):
seq.remove(n)
cha... |
'Return the last message number.'
| def getlast(self):
| if (not hasattr(self, 'last')):
self.listmessages()
return self.last
|
'Set the last message number.'
| def setlast(self, last):
| if (last is None):
if hasattr(self, 'last'):
del self.last
else:
self.last = last
return
|
'Constructor.'
| def __init__(self, f, n, fp=None):
| self.folder = f
self.number = n
if (fp is None):
path = f.getmessagefilename(n)
fp = open(path, 'r')
mimetools.Message.__init__(self, fp)
return
|
'String representation.'
| def __repr__(self):
| return ('Message(%s, %s)' % (repr(self.folder), self.number))
|
'Return the message\'s header text as a string. If an
argument is specified, it is used as a filter predicate to
decide which headers to return (its argument is the header
name converted to lower case).'
| def getheadertext(self, pred=None):
| if (pred is None):
return ''.join(self.headers)
else:
headers = []
hit = 0
for line in self.headers:
if (not line[0].isspace()):
i = line.find(':')
if (i > 0):
hit = pred(line[:i].lower())
if hit:
... |
'Return the message\'s body text as string. This undoes a
Content-Transfer-Encoding, but does not interpret other MIME
features (e.g. multipart messages). To suppress decoding,
pass 0 as an argument.'
| def getbodytext(self, decode=1):
| self.fp.seek(self.startofbody)
encoding = self.getencoding()
if ((not decode) or (encoding in ('', '7bit', '8bit', 'binary'))):
return self.fp.read()
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
output = StringIO()
mimetools.de... |
'Only for multipart messages: return the message\'s body as a
list of SubMessage objects. Each submessage object behaves
(almost) as a Message object.'
| def getbodyparts(self):
| if (self.getmaintype() != 'multipart'):
raise Error, 'Content-Type is not multipart/*'
bdry = self.getparam('boundary')
if (not bdry):
raise Error, 'multipart/* without boundary param'
self.fp.seek(self.startofbody)
mf = multifile.MultiFile(self.fp)
mf.push(bdry... |
'Return body, either a string or a list of messages.'
| def getbody(self):
| if (self.getmaintype() == 'multipart'):
return self.getbodyparts()
else:
return self.getbodytext()
|
'Constructor.'
| def __init__(self, f, n, fp):
| Message.__init__(self, f, n, fp)
if (self.getmaintype() == 'multipart'):
self.body = Message.getbodyparts(self)
else:
self.body = Message.getbodytext(self)
self.bodyencoded = Message.getbodytext(self, decode=0)
|
'String representation.'
| def __repr__(self):
| (f, n, fp) = (self.folder, self.number, self.fp)
return ('SubMessage(%s, %s, %s)' % (f, n, fp))
|
'Return an iterator that yields the weak references to the values.
The references are not guaranteed to be \'live\' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the v... | def itervaluerefs(self):
| return self.data.itervalues()
|
'Return a list of weak references to the values.
The references are not guaranteed to be \'live\' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the values around longe... | def valuerefs(self):
| return self.data.values()
|
'Return an iterator that yields the weak references to the keys.
The references are not guaranteed to be \'live\' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the key... | def iterkeyrefs(self):
| return self.data.iterkeys()
|
'Return a list of weak references to the keys.
The references are not guaranteed to be \'live\' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the keys around longer th... | def keyrefs(self):
| return self.data.keys()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.