desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Visit a docstring statement which may have an assignment before.'
| def visit_simple_stmt(self, node):
| if (node[0].type != token.STRING):
return self.generic_visit(node)
prev = node.get_prev_sibling()
if (not prev):
return
if ((prev.type == sym.simple_stmt) and (prev[0].type == sym.expr_stmt) and (_eq in prev[0].children)):
docstring = literals.evalString(node[0].value, self.encoding)
docstring = prepare_docstring(docstring)
self.add_docstring(prev[0], docstring)
|
'Generate tokens from the source.'
| def tokenize(self):
| if (self.tokens is not None):
return
self.tokens = list(tokenize.generate_tokens(self.source.readline))
self.source.close()
|
'Parse the generated source tokens.'
| def parse(self):
| if (self.parsetree is not None):
return
self.tokenize()
try:
self.parsetree = pydriver.parse_tokens(self.tokens)
except parse.ParseError as err:
raise PycodeError('parsing failed', err)
encoding = sys.getdefaultencoding()
comments = self.parsetree.get_prefix()
for line in comments.splitlines()[:2]:
match = _coding_re.search(line)
if (match is not None):
encoding = match.group(1)
break
self.encoding = encoding
|
'Find class and module-level attributes and their documentation.'
| def find_attr_docs(self, scope=''):
| if (self.attr_docs is not None):
return self.attr_docs
self.parse()
attr_visitor = AttrDocVisitor(number2name, scope, self.encoding)
attr_visitor.visit(self.parsetree)
self.attr_docs = attr_visitor.collected
self.parsetree = None
return attr_visitor.collected
|
'Find class, function and method definitions and their location.'
| def find_tags(self):
| if (self.tags is not None):
return self.tags
self.tokenize()
result = {}
namespace = []
stack = []
indent = 0
defline = False
expect_indent = False
def tokeniter(ignore=(token.COMMENT, token.NL)):
for tokentup in self.tokens:
if (tokentup[0] not in ignore):
(yield tokentup)
tokeniter = tokeniter()
for (type, tok, spos, epos, line) in tokeniter:
if expect_indent:
if (type != token.INDENT):
assert stack
(dtype, fullname, startline, _) = stack.pop()
endline = epos[0]
namespace.pop()
result[fullname] = (dtype, startline, endline)
expect_indent = False
if (tok in ('def', 'class')):
name = tokeniter.next()[1]
namespace.append(name)
fullname = '.'.join(namespace)
stack.append((tok, fullname, spos[0], indent))
defline = True
elif (type == token.INDENT):
expect_indent = False
indent += 1
elif (type == token.DEDENT):
indent -= 1
if (stack and (indent == stack[(-1)][3])):
(dtype, fullname, startline, _) = stack.pop()
endline = spos[0]
namespace.pop()
result[fullname] = (dtype, startline, endline)
elif (type == token.NEWLINE):
if defline:
defline = False
expect_indent = True
self.tags = result
return result
|
'Return previous child in parent\'s children, or None.'
| def get_prev_sibling(self):
| if (self.parent is None):
return None
for (i, child) in enumerate(self.parent.children):
if (child is self):
if (i == 0):
return None
return self.parent.children[(i - 1)]
|
'Return next child in parent\'s children, or None.'
| def get_next_sibling(self):
| if (self.parent is None):
return None
for (i, child) in enumerate(self.parent.children):
if (child is self):
try:
return self.parent.children[(i + 1)]
except IndexError:
return None
|
'Return the leaf node that precedes this node in the parse tree.'
| def get_prev_leaf(self):
| def last_child(node):
if isinstance(node, Leaf):
return node
elif (not node.children):
return None
else:
return last_child(node.children[(-1)])
if (self.parent is None):
return None
prev = self.get_prev_sibling()
if isinstance(prev, Leaf):
return prev
elif (prev is not None):
return last_child(prev)
return self.parent.get_prev_leaf()
|
'Return self if leaf, otherwise the leaf node that succeeds this
node in the parse tree.'
| def get_next_leaf(self):
| node = self
while (not isinstance(node, Leaf)):
assert node.children
node = node.children[0]
return node
|
'Return the line number which generated the invocant node.'
| def get_lineno(self):
| return self.get_next_leaf().lineno
|
'Return the prefix of the next leaf node.'
| def get_prefix(self):
| return self.get_next_leaf().prefix
|
'This reproduces the input source exactly.'
| def __str__(self):
| return ''.join(map(str, self.children))
|
'This reproduces the input source exactly.'
| def __str__(self):
| return (self.prefix + str(self.value))
|
'Compares two nodes for equality.'
| def _eq(self, other):
| return ((self.type, self.value) == (other.type, other.value))
|
'Visit a node.'
| def visit(self, node):
| method = ('visit_' + self.number2name[node.type])
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
|
'Called if no explicit visitor function exists for a node.'
| def generic_visit(self, node):
| if isinstance(node, Node):
for child in node:
self.visit(child)
|
'The main part of the stemming algorithm starts here.
b is a buffer holding a word to be stemmed. The letters are in b[k0],
b[k0+1] ... ending at b[k]. In fact k0 = 0 in this demo program. k is
readjusted downwards as the stemming progresses. Zero termination is
not in fact used in the algorithm.
Note that only lower case sequences are stemmed. Forcing to lower case
should be done before stem(...) is called.'
| def __init__(self):
| self.b = ''
self.k = 0
self.k0 = 0
self.j = 0
|
'cons(i) is TRUE <=> b[i] is a consonant.'
| def cons(self, i):
| if ((self.b[i] == 'a') or (self.b[i] == 'e') or (self.b[i] == 'i') or (self.b[i] == 'o') or (self.b[i] == 'u')):
return 0
if (self.b[i] == 'y'):
if (i == self.k0):
return 1
else:
return (not self.cons((i - 1)))
return 1
|
'm() measures the number of consonant sequences between k0 and j.
if c is a consonant sequence and v a vowel sequence, and <..>
indicates arbitrary presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3'
| def m(self):
| n = 0
i = self.k0
while 1:
if (i > self.j):
return n
if (not self.cons(i)):
break
i = (i + 1)
i = (i + 1)
while 1:
while 1:
if (i > self.j):
return n
if self.cons(i):
break
i = (i + 1)
i = (i + 1)
n = (n + 1)
while 1:
if (i > self.j):
return n
if (not self.cons(i)):
break
i = (i + 1)
i = (i + 1)
|
'vowelinstem() is TRUE <=> k0,...j contains a vowel'
| def vowelinstem(self):
| for i in range(self.k0, (self.j + 1)):
if (not self.cons(i)):
return 1
return 0
|
'doublec(j) is TRUE <=> j,(j-1) contain a double consonant.'
| def doublec(self, j):
| if (j < (self.k0 + 1)):
return 0
if (self.b[j] != self.b[(j - 1)]):
return 0
return self.cons(j)
|
'cvc(i) is TRUE <=> i-2,i-1,i has the form
consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.'
| def cvc(self, i):
| if ((i < (self.k0 + 2)) or (not self.cons(i)) or self.cons((i - 1)) or (not self.cons((i - 2)))):
return 0
ch = self.b[i]
if ((ch == 'w') or (ch == 'x') or (ch == 'y')):
return 0
return 1
|
'ends(s) is TRUE <=> k0,...k ends with the string s.'
| def ends(self, s):
| length = len(s)
if (s[(length - 1)] != self.b[self.k]):
return 0
if (length > ((self.k - self.k0) + 1)):
return 0
if (self.b[((self.k - length) + 1):(self.k + 1)] != s):
return 0
self.j = (self.k - length)
return 1
|
'setto(s) sets (j+1),...k to the characters in the string s,
readjusting k.'
| def setto(self, s):
| length = len(s)
self.b = ((self.b[:(self.j + 1)] + s) + self.b[((self.j + length) + 1):])
self.k = (self.j + length)
|
'r(s) is used further down.'
| def r(self, s):
| if (self.m() > 0):
self.setto(s)
|
'step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet'
| def step1ab(self):
| if (self.b[self.k] == 's'):
if self.ends('sses'):
self.k = (self.k - 2)
elif self.ends('ies'):
self.setto('i')
elif (self.b[(self.k - 1)] != 's'):
self.k = (self.k - 1)
if self.ends('eed'):
if (self.m() > 0):
self.k = (self.k - 1)
elif ((self.ends('ed') or self.ends('ing')) and self.vowelinstem()):
self.k = self.j
if self.ends('at'):
self.setto('ate')
elif self.ends('bl'):
self.setto('ble')
elif self.ends('iz'):
self.setto('ize')
elif self.doublec(self.k):
self.k = (self.k - 1)
ch = self.b[self.k]
if ((ch == 'l') or (ch == 's') or (ch == 'z')):
self.k = (self.k + 1)
elif ((self.m() == 1) and self.cvc(self.k)):
self.setto('e')
|
'step1c() turns terminal y to i when there is another vowel in
the stem.'
| def step1c(self):
| if (self.ends('y') and self.vowelinstem()):
self.b = ((self.b[:self.k] + 'i') + self.b[(self.k + 1):])
|
'step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0.'
| def step2(self):
| if (self.b[(self.k - 1)] == 'a'):
if self.ends('ational'):
self.r('ate')
elif self.ends('tional'):
self.r('tion')
elif (self.b[(self.k - 1)] == 'c'):
if self.ends('enci'):
self.r('ence')
elif self.ends('anci'):
self.r('ance')
elif (self.b[(self.k - 1)] == 'e'):
if self.ends('izer'):
self.r('ize')
elif (self.b[(self.k - 1)] == 'l'):
if self.ends('bli'):
self.r('ble')
elif self.ends('alli'):
self.r('al')
elif self.ends('entli'):
self.r('ent')
elif self.ends('eli'):
self.r('e')
elif self.ends('ousli'):
self.r('ous')
elif (self.b[(self.k - 1)] == 'o'):
if self.ends('ization'):
self.r('ize')
elif self.ends('ation'):
self.r('ate')
elif self.ends('ator'):
self.r('ate')
elif (self.b[(self.k - 1)] == 's'):
if self.ends('alism'):
self.r('al')
elif self.ends('iveness'):
self.r('ive')
elif self.ends('fulness'):
self.r('ful')
elif self.ends('ousness'):
self.r('ous')
elif (self.b[(self.k - 1)] == 't'):
if self.ends('aliti'):
self.r('al')
elif self.ends('iviti'):
self.r('ive')
elif self.ends('biliti'):
self.r('ble')
elif (self.b[(self.k - 1)] == 'g'):
if self.ends('logi'):
self.r('log')
|
'step3() dels with -ic-, -full, -ness etc. similar strategy
to step2.'
| def step3(self):
| if (self.b[self.k] == 'e'):
if self.ends('icate'):
self.r('ic')
elif self.ends('ative'):
self.r('')
elif self.ends('alize'):
self.r('al')
elif (self.b[self.k] == 'i'):
if self.ends('iciti'):
self.r('ic')
elif (self.b[self.k] == 'l'):
if self.ends('ical'):
self.r('ic')
elif self.ends('ful'):
self.r('')
elif (self.b[self.k] == 's'):
if self.ends('ness'):
self.r('')
|
'step4() takes off -ant, -ence etc., in context <c>vcvc<v>.'
| def step4(self):
| if (self.b[(self.k - 1)] == 'a'):
if self.ends('al'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'c'):
if self.ends('ance'):
pass
elif self.ends('ence'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'e'):
if self.ends('er'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'i'):
if self.ends('ic'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'l'):
if self.ends('able'):
pass
elif self.ends('ible'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'n'):
if self.ends('ant'):
pass
elif self.ends('ement'):
pass
elif self.ends('ment'):
pass
elif self.ends('ent'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'o'):
if (self.ends('ion') and ((self.b[self.j] == 's') or (self.b[self.j] == 't'))):
pass
elif self.ends('ou'):
pass
else:
return
elif (self.b[(self.k - 1)] == 's'):
if self.ends('ism'):
pass
else:
return
elif (self.b[(self.k - 1)] == 't'):
if self.ends('ate'):
pass
elif self.ends('iti'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'u'):
if self.ends('ous'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'v'):
if self.ends('ive'):
pass
else:
return
elif (self.b[(self.k - 1)] == 'z'):
if self.ends('ize'):
pass
else:
return
else:
return
if (self.m() > 1):
self.k = self.j
|
'step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1.'
| def step5(self):
| self.j = self.k
if (self.b[self.k] == 'e'):
a = self.m()
if ((a > 1) or ((a == 1) and (not self.cvc((self.k - 1))))):
self.k = (self.k - 1)
if ((self.b[self.k] == 'l') and self.doublec(self.k) and (self.m() > 1)):
self.k = (self.k - 1)
|
'In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == \' \'). The
stemmer adjusts the characters p[i] ... p[j] and returns the new
end-point of the string, k. Stemming never increases word length, so
i <= k <= j. To turn the stemmer into a module, declare \'stem\' as
extern, and delete the remainder of this file.'
| def stem(self, p, i, j):
| self.b = p
self.k = j
self.k0 = i
if (self.k <= (self.k0 + 1)):
return self.b
self.step1ab()
self.step1c()
self.step2()
self.step3()
self.step4()
self.step5()
return self.b[self.k0:(self.k + 1)]
|
'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_BACKSPACE)):
if (x > 0):
self.win.move(y, (x - 1))
elif (y == 0):
pass
elif self.stripspaces:
self.win.move((y - 1), self._end_of_line((y - 1)))
else:
self.win.move((y - 1), self.maxx)
if (ch in (curses.ascii.BS, curses.KEY_BACKSPACE)):
self.win.delch()
elif (ch == curses.ascii.EOT):
self.win.delch()
elif (ch == curses.ascii.ENQ):
if self.stripspaces:
self.win.move(y, self._end_of_line(y))
else:
self.win.move(y, self.maxx)
elif (ch in (curses.ascii.ACK, curses.KEY_RIGHT)):
if (x < self.maxx):
self.win.move(y, (x + 1))
elif (y == self.maxy):
pass
else:
self.win.move((y + 1), 0)
elif (ch == curses.ascii.BEL):
return 0
elif (ch == curses.ascii.NL):
if (self.maxy == 0):
return 0
elif (y < self.maxy):
self.win.move((y + 1), 0)
elif (ch == curses.ascii.VT):
if ((x == 0) and (self._end_of_line(y) == 0)):
self.win.deleteln()
else:
self.win.move(y, x)
self.win.clrtoeol()
elif (ch == curses.ascii.FF):
self.win.refresh()
elif (ch in (curses.ascii.SO, curses.KEY_DOWN)):
if (y < self.maxy):
self.win.move((y + 1), x)
if (x > self._end_of_line((y + 1))):
self.win.move((y + 1), self._end_of_line((y + 1)))
elif (ch == curses.ascii.SI):
self.win.insertln()
elif (ch in (curses.ascii.DLE, curses.KEY_UP)):
if (y > 0):
self.win.move((y - 1), x)
if (x > self._end_of_line((y - 1))):
self.win.move((y - 1), self._end_of_line((y - 1)))
return 1
|
'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 = (result + chr(curses.ascii.ascii(self.win.inch(y, x))))
if (self.maxy > 0):
result = (result + '\n')
return 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.expanduser(path)
if (not os.path.isdir(path)):
raise Error, 'MH() path not found'
self.path = path
|
'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_subname = os.path.join(name, subname)
subfolders.append(name_subname)
nlinks = (nlinks - 1)
if (nlinks == 2):
break
subfolders.sort()
return subfolders
|
'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.join(fullname, subname)
if os.path.isdir(fullsubname):
name_subname = os.path.join(name, subname)
subfolders.append(name_subname)
if (not os.path.islink(fullsubname)):
subsubfolders = self.listallsubfolders(name_subname)
subfolders = (subfolders + subsubfolders)
nlinks = (nlinks - 1)
if (nlinks == 2):
break
subfolders.sort()
return subfolders
|
'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
return messages
|
'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(('bad sequence in %s: %s' % (fullname, line.strip())))
key = fields[0].strip()
value = IntSet(fields[1].strip(), ' ').tolist()
sequences[key] = value
return sequences
|
'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(fullname)
except os.error:
pass
else:
f.close()
|
'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], tail[1:])
if (not isnumeric(tail)):
raise Error, ('bad message list %s' % seq)
try:
count = int(tail)
except (ValueError, OverflowError):
count = len(all)
try:
anchor = self._parseindex(head, all)
except Error as msg:
seqs = self.getsequences()
if (not (head in seqs)):
if (not msg):
msg = ('bad message list %s' % seq)
raise Error, msg, sys.exc_info()[2]
msgs = seqs[head]
if (not msgs):
raise Error, ('sequence %s empty' % head)
if (dir == '-'):
return msgs[(- count):]
else:
return msgs[:count]
else:
if (not dir):
if (head in ('prev', 'last')):
dir = '-'
if (dir == '-'):
i = bisect(all, anchor)
return all[max(0, (i - count)):i]
else:
i = bisect(all, (anchor - 1))
return all[i:(i + count)]
i = seq.find('-')
if (i >= 0):
begin = self._parseindex(seq[:i], all)
end = self._parseindex(seq[(i + 1):], all)
i = bisect(all, (begin - 1))
j = bisect(all, end)
r = all[i:j]
if (not r):
raise Error, ('bad message list %s' % seq)
return r
try:
n = self._parseindex(seq, all)
except Error as msg:
seqs = self.getsequences()
if (not (seq in seqs)):
if (not msg):
msg = ('bad message list %s' % seq)
raise Error, msg
return seqs[seq]
else:
if (n not in all):
if isnumeric(seq):
raise Error, ("message %d doesn't exist" % n)
else:
raise Error, ('no %s message' % seq)
else:
return [n]
|
'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()
if (seq == 'first'):
return all[0]
if (seq == 'last'):
return all[(-1)]
if (seq == 'next'):
n = self.getcurrent()
i = bisect(all, n)
try:
return all[i]
except IndexError:
raise Error, 'no next message'
if (seq == 'prev'):
n = self.getcurrent()
i = bisect(all, (n - 1))
if (i == 0):
raise Error, 'no prev message'
try:
return all[(i - 1)]
except IndexError:
raise Error, 'no prev message'
raise Error, None
|
'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 msg:
errors.append(msg)
else:
deleted.append(n)
if deleted:
self.removefromallsequences(deleted)
if errors:
if (len(errors) == 1):
raise os.error, errors[0]
else:
raise os.error, ('multiple errors:', errors)
|
'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)
os.unlink(path)
except (IOError, os.error) as msg:
errors.append(msg)
try:
os.unlink(topath)
except os.error:
pass
continue
tofolder.setlast(ton)
refiled[n] = ton
if refiled:
if keepsequences:
tofolder._copysequences(self, refiled.items())
self.removefromallsequences(refiled.keys())
if errors:
if (len(errors) == 1):
raise os.error, errors[0]
else:
raise os.error, ('multiple errors:', errors)
|
'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 refileditems:
if (fromn in seq):
toseq.append(ton)
changed = 1
if (new and toseq):
tosequences[name] = toseq
if changed:
self.putsequences(tosequences)
|
'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)
except os.error:
ok = 0
try:
tofolder.setlast(None)
shutil.copy2(path, topath)
ok = 1
finally:
if (not ok):
try:
os.unlink(topath)
except os.error:
pass
os.unlink(path)
self.removefromallsequences([n])
|
'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(None)
shutil.copy2(path, topath)
ok = 1
finally:
if (not ok):
try:
os.unlink(topath)
except os.error:
pass
|
'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 = (16 * 1024)
try:
f = open(path, 'w')
while 1:
buf = txt.read(BUFSIZE)
if (not buf):
break
f.write(buf)
f.close()
ok = 1
finally:
if (not ok):
try:
os.unlink(path)
except os.error:
pass
|
'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)
changed = 1
if (not seq):
del sequences[name]
if changed:
self.putsequences(sequences)
|
'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
|
'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)
|
'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)
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:
headers.append(line)
return ''.join(headers)
|
'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.decode(self.fp, output, encoding)
return output.getvalue()
|
'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)
parts = []
while mf.next():
n = ('%s.%r' % (self.number, (1 + len(parts))))
part = SubMessage(self.folder, n, mf)
parts.append(part)
mf.pop()
return parts
|
'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 values around longer than needed.'
| def itervaluerefs(self):
| with _IterationGuard(self):
for wr in self.data.itervalues():
(yield wr)
|
'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 longer than needed.'
| 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 keys around longer than needed.'
| def iterkeyrefs(self):
| with _IterationGuard(self):
for wr in self.data.iterkeys():
(yield wr)
|
'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 than needed.'
| def keyrefs(self):
| return self.data.keys()
|
'Initialize a Mailbox instance.'
| def __init__(self, path, factory=None, create=True):
| self._path = os.path.abspath(os.path.expanduser(path))
self._factory = factory
|
'Add message and return assigned key.'
| def add(self, message):
| raise NotImplementedError('Method must be implemented by subclass')
|
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
| def remove(self, key):
| raise NotImplementedError('Method must be implemented by subclass')
|
'If the keyed message exists, remove it.'
| def discard(self, key):
| try:
self.remove(key)
except KeyError:
pass
|
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
| def __setitem__(self, key, message):
| raise NotImplementedError('Method must be implemented by subclass')
|
'Return the keyed message, or default if it doesn\'t exist.'
| def get(self, key, default=None):
| try:
return self.__getitem__(key)
except KeyError:
return default
|
'Return the keyed message; raise KeyError if it doesn\'t exist.'
| def __getitem__(self, key):
| if (not self._factory):
return self.get_message(key)
else:
return self._factory(self.get_file(key))
|
'Return a Message representation or raise a KeyError.'
| def get_message(self, key):
| raise NotImplementedError('Method must be implemented by subclass')
|
'Return a string representation or raise a KeyError.'
| def get_string(self, key):
| raise NotImplementedError('Method must be implemented by subclass')
|
'Return a file-like representation or raise a KeyError.'
| def get_file(self, key):
| raise NotImplementedError('Method must be implemented by subclass')
|
'Return an iterator over keys.'
| def iterkeys(self):
| raise NotImplementedError('Method must be implemented by subclass')
|
'Return a list of keys.'
| def keys(self):
| return list(self.iterkeys())
|
'Return an iterator over all messages.'
| def itervalues(self):
| for key in self.iterkeys():
try:
value = self[key]
except KeyError:
continue
(yield value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.