code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def getcaps(): """Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list collects all the entries for that MIME type from all available mailcap files. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view". """ caps = {} for mailcap in listmailcapfiles(): try: fp = open(mailcap, 'r') except IOError: continue with fp: morecaps = readmailcapfile(fp) for key, value in morecaps.iteritems(): if not key in caps: caps[key] = value else: caps[key] = caps[key] + value return caps
Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list collects all the entries for that MIME type from all available mailcap files. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view".
getcaps
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailcap.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailcap.py
MIT
def listmailcapfiles(): """Return a list of all mailcap files found on the system.""" # XXX Actually, this is Unix-specific if 'MAILCAPS' in os.environ: str = os.environ['MAILCAPS'] mailcaps = str.split(':') else: if 'HOME' in os.environ: home = os.environ['HOME'] else: # Don't bother with getpwuid() home = '.' # Last resort mailcaps = [home + '/.mailcap', '/etc/mailcap', '/usr/etc/mailcap', '/usr/local/etc/mailcap'] return mailcaps
Return a list of all mailcap files found on the system.
listmailcapfiles
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailcap.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailcap.py
MIT
def readmailcapfile(fp): """Read a mailcap file and return a dictionary keyed by MIME type. Each MIME type is mapped to an entry consisting of a list of dictionaries; the list will contain more than one such dictionary if a given MIME type appears more than once in the mailcap file. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view". """ caps = {} while 1: line = fp.readline() if not line: break # Ignore comments and blank lines if line[0] == '#' or line.strip() == '': continue nextline = line # Join continuation lines while nextline[-2:] == '\\\n': nextline = fp.readline() if not nextline: nextline = '\n' line = line[:-2] + nextline # Parse the line key, fields = parseline(line) if not (key and fields): continue # Normalize the key types = key.split('/') for j in range(len(types)): types[j] = types[j].strip() key = '/'.join(types).lower() # Update the database if key in caps: caps[key].append(fields) else: caps[key] = [fields] return caps
Read a mailcap file and return a dictionary keyed by MIME type. Each MIME type is mapped to an entry consisting of a list of dictionaries; the list will contain more than one such dictionary if a given MIME type appears more than once in the mailcap file. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view".
readmailcapfile
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailcap.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailcap.py
MIT
def parseline(line): """Parse one entry in a mailcap file and return a dictionary. The viewing command is stored as the value with the key "view", and the rest of the fields produce key-value pairs in the dict. """ fields = [] i, n = 0, len(line) while i < n: field, i = parsefield(line, i, n) fields.append(field) i = i+1 # Skip semicolon if len(fields) < 2: return None, None key, view, rest = fields[0], fields[1], fields[2:] fields = {'view': view} for field in rest: i = field.find('=') if i < 0: fkey = field fvalue = "" else: fkey = field[:i].strip() fvalue = field[i+1:].strip() if fkey in fields: # Ignore it pass else: fields[fkey] = fvalue return key, fields
Parse one entry in a mailcap file and return a dictionary. The viewing command is stored as the value with the key "view", and the rest of the fields produce key-value pairs in the dict.
parseline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailcap.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailcap.py
MIT
def parsefield(line, i, n): """Separate one key-value pair in a mailcap entry.""" start = i while i < n: c = line[i] if c == ';': break elif c == '\\': i = i+2 else: i = i+1 return line[start:i].strip(), i
Separate one key-value pair in a mailcap entry.
parsefield
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailcap.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailcap.py
MIT
def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]): """Find a match for a mailcap entry. Return a tuple containing the command line, and the mailcap entry used; (None, None) if no match is found. This may invoke the 'test' command of several matching entries before deciding which entry to use. """ entries = lookup(caps, MIMEtype, key) # XXX This code should somehow check for the needsterminal flag. for e in entries: if 'test' in e: test = subst(e['test'], filename, plist) if test and os.system(test) != 0: continue command = subst(e[key], MIMEtype, filename, plist) return command, e return None, None
Find a match for a mailcap entry. Return a tuple containing the command line, and the mailcap entry used; (None, None) if no match is found. This may invoke the 'test' command of several matching entries before deciding which entry to use.
findmatch
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailcap.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailcap.py
MIT
def getcontext(self): """Return the name of the current folder.""" context = pickline(os.path.join(self.getpath(), 'context'), 'Current-Folder') if not context: context = 'inbox' return context
Return the name of the current folder.
getcontext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def setcontext(self, context): """Set the name of the current folder.""" fn = os.path.join(self.getpath(), 'context') f = open(fn, "w") f.write("Current-Folder: %s\n" % context) f.close()
Set the name of the current folder.
setcontext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def listfolders(self): """Return the names of the top-level folders.""" 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 top-level folders.
listfolders
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def listsubfolders(self, name): """Return the names of the subfolders in a given folder (prefixed with the given folder name).""" fullname = os.path.join(self.path, name) # Get the link count so we can avoid listing folders # that have no subfolders. 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) # Stop looking for subfolders when # we've seen them all nlinks = nlinks - 1 if nlinks == 2: break subfolders.sort() return subfolders
Return the names of the subfolders in a given folder (prefixed with the given folder name).
listsubfolders
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def listallsubfolders(self, name): """Return the names of subfolders in a given folder, recursively.""" fullname = os.path.join(self.path, name) # Get the link count so we can avoid listing folders # that have no subfolders. 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 # Stop looking for subfolders when # we've seen them all nlinks = nlinks - 1 if nlinks == 2: break subfolders.sort() return subfolders
Return the names of subfolders in a given folder, recursively.
listallsubfolders
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def makefolder(self, name): """Create a new folder (or raise os.error if it cannot be created).""" 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)
Create a new folder (or raise os.error if it cannot be created).
makefolder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def deletefolder(self, name): """Delete a folder. This removes files in the folder but not subdirectories. Raise os.error if deleting the folder itself fails.""" 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)
Delete a folder. This removes files in the folder but not subdirectories. Raise os.error if deleting the folder itself fails.
deletefolder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def listmessages(self): """Return the list of messages currently present in the folder. As a side effect, set self.last to the last message (or 0).""" 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 list of messages currently present in the folder. As a side effect, set self.last to the last message (or 0).
listmessages
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def getsequences(self): """Return the set of sequences for the folder.""" 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
Return the set of sequences for the folder.
getsequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def putsequences(self, sequences): """Write the set of sequences back to the folder.""" 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()
Write the set of sequences back to the folder.
putsequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def getcurrent(self): """Return the current message. Raise Error when there is none.""" seqs = self.getsequences() try: return max(seqs['cur']) except (ValueError, KeyError): raise Error, "no cur message"
Return the current message. Raise Error when there is none.
getcurrent
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def parsesequence(self, seq): """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.""" # XXX Still not complete (see mh-format(5)). # Missing are: # - 'prev', 'next' as count # - Sequence-Negation option all = self.listmessages() # Observed behavior: test for empty folder is done first if not all: raise Error, "no messages in %s" % self.name # Common case first: all is frequently the default if seq == 'all': return all # Test for X:Y before X-Y because 'seq:-n' matches both 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): # Can't use sys.maxint because of i+count below count = len(all) try: anchor = self._parseindex(head, all) except Error, 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] # Test for X-Y next 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 # Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence try: n = self._parseindex(seq, all) except Error, 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]
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.
parsesequence
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def _parseindex(self, seq, all): """Internal: parse a message number (or cur, first, etc.).""" 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
Internal: parse a message number (or cur, first, etc.).
_parseindex
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def removemessages(self, list): """Remove one or more messages -- may raise os.error.""" 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, 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)
Remove one or more messages -- may raise os.error.
removemessages
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def refilemessages(self, list, tofolder, keepsequences=0): """Refile one or more messages -- may raise os.error. 'tofolder' is an open folder object.""" 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 copying try: shutil.copy2(path, topath) os.unlink(path) except (IOError, os.error), 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)
Refile one or more messages -- may raise os.error. 'tofolder' is an open folder object.
refilemessages
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def _copysequences(self, fromfolder, refileditems): """Helper for refilemessages() to copy sequences.""" 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)
Helper for refilemessages() to copy sequences.
_copysequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def movemessage(self, n, tofolder, ton): """Move one message over a specific destination message, which may or may not already exist.""" path = self.getmessagefilename(n) # Open it to check that it exists 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: # Try copying 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])
Move one message over a specific destination message, which may or may not already exist.
movemessage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def copymessage(self, n, tofolder, ton): """Copy one message over a specific destination message, which may or may not already exist.""" path = self.getmessagefilename(n) # Open it to check that it exists 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
Copy one message over a specific destination message, which may or may not already exist.
copymessage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def createmessage(self, n, txt): """Create a message, with text from the open file 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
Create a message, with text from the open file txt.
createmessage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def removefromallsequences(self, list): """Remove one or more messages from all sequences (including last) -- but not from 'cur'!!!""" 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)
Remove one or more messages from all sequences (including last) -- but not from 'cur'!!!
removefromallsequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def getheadertext(self, pred = None): """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).""" 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 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).
getheadertext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def getbodytext(self, decode = 1): """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.""" 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()
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.
getbodytext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def getbodyparts(self): """Only for multipart messages: return the message's body as a list of SubMessage objects. Each submessage object behaves (almost) as a Message object.""" 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
Only for multipart messages: return the message's body as a list of SubMessage objects. Each submessage object behaves (almost) as a Message object.
getbodyparts
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def getbody(self): """Return body, either a string or a list of messages.""" if self.getmaintype() == 'multipart': return self.getbodyparts() else: return self.getbodytext()
Return body, either a string or a list of messages.
getbody
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mhlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mhlib.py
MIT
def choose_boundary(): """Return a string usable as a multipart boundary. The string chosen is unique within a single program run, and incorporates the user id (if available), process id (if available), and current time. So it's very unlikely the returned string appears in message text, but there's no guarantee. The boundary contains dots so you have to quote it in the header.""" global _prefix import time if _prefix is None: import socket try: hostid = socket.gethostbyname(socket.gethostname()) except socket.gaierror: hostid = '127.0.0.1' try: uid = repr(os.getuid()) except AttributeError: uid = '1' try: pid = repr(os.getpid()) except AttributeError: pid = '1' _prefix = hostid + '.' + uid + '.' + pid return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())
Return a string usable as a multipart boundary. The string chosen is unique within a single program run, and incorporates the user id (if available), process id (if available), and current time. So it's very unlikely the returned string appears in message text, but there's no guarantee. The boundary contains dots so you have to quote it in the header.
choose_boundary
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetools.py
MIT
def decode(input, output, encoding): """Decode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.decode(input, output) if encoding == 'quoted-printable': import quopri return quopri.decode(input, output) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.decode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) if encoding in decodetab: pipethrough(input, decodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
Decode common content-transfer-encodings (base64, quopri, uuencode).
decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetools.py
MIT
def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) if encoding in encodetab: pipethrough(input, encodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
Encode common content-transfer-encodings (base64, quopri, uuencode).
encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetools.py
MIT
def add_type(self, type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ self.types_map[strict][ext] = type exts = self.types_map_inv[strict].setdefault(type, []) if ext not in exts: exts.append(ext)
Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types.
add_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def guess_type(self, url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to '.tar.gz'. (This is table-driven too, using the dictionary suffix_map.) Optional `strict' argument when False adds a bunch of commonly found, but non-standard types. """ scheme, url = urllib.splittype(url) if scheme == 'data': # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value # type/subtype defaults to "text/plain" comma = url.find(',') if comma < 0: # bad data URL return None, None semi = url.find(';', 0, comma) if semi >= 0: type = url[:semi] else: type = url[:comma] if '=' in type or '/' not in type: type = 'text/plain' return type, None # never compressed, so encoding is None base, ext = posixpath.splitext(url) while ext in self.suffix_map: base, ext = posixpath.splitext(base + self.suffix_map[ext]) if ext in self.encodings_map: encoding = self.encodings_map[ext] base, ext = posixpath.splitext(base) else: encoding = None types_map = self.types_map[True] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding elif strict: return None, encoding types_map = self.types_map[False] if ext in types_map: return types_map[ext], encoding elif ext.lower() in types_map: return types_map[ext.lower()], encoding else: return None, encoding
Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to '.tar.gz'. (This is table-driven too, using the dictionary suffix_map.) Optional `strict' argument when False adds a bunch of commonly found, but non-standard types.
guess_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def guess_all_extensions(self, type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ type = type.lower() extensions = self.types_map_inv[True].get(type, []) if not strict: for ext in self.types_map_inv[False].get(type, []): if ext not in extensions: extensions.append(ext) return extensions
Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
guess_all_extensions
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def guess_extension(self, type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ extensions = self.guess_all_extensions(type, strict) if not extensions: return None return extensions[0]
Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
guess_extension
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def readfp(self, fp, strict=True): """ Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ while 1: line = fp.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: self.add_type(type, '.' + suff, strict)
Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types.
readfp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: if '\0' not in ctype: yield ctype i += 1 default_encoding = sys.getdefaultencoding() with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue try: mimetype = mimetype.encode(default_encoding) except UnicodeEncodeError: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue
Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types.
read_windows_registry
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def guess_type(url, strict=True): """Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_type(url, strict)
Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitive, then case insensitive. The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped to ".tar.gz". (This is table-driven too, using the dictionary suffix_map). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
guess_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def guess_all_extensions(type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_all_extensions(type, strict)
Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
guess_all_extensions
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def guess_extension(type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_extension(type, strict)
Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
guess_extension
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def add_type(type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ if _db is None: init() return _db.add_type(type, ext, strict)
Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types.
add_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimetypes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimetypes.py
MIT
def addheader(self, key, value, prefix=0): """Add a header line to the MIME message. The key is the name of the header, where the value obviously provides the value of the header. The optional argument prefix determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to append. """ lines = value.split("\n") while lines and not lines[-1]: del lines[-1] while lines and not lines[0]: del lines[0] for i in range(1, len(lines)): lines[i] = " " + lines[i].strip() value = "\n".join(lines) + "\n" line = key + ": " + value if prefix: self._headers.insert(0, line) else: self._headers.append(line)
Add a header line to the MIME message. The key is the name of the header, where the value obviously provides the value of the header. The optional argument prefix determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to append.
addheader
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/MimeWriter.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/MimeWriter.py
MIT
def flushheaders(self): """Writes out and forgets all headers accumulated so far. This is useful if you don't need a body part at all; for example, for a subpart of type message/rfc822 that's (mis)used to store some header-like information. """ self._fp.writelines(self._headers) self._headers = []
Writes out and forgets all headers accumulated so far. This is useful if you don't need a body part at all; for example, for a subpart of type message/rfc822 that's (mis)used to store some header-like information.
flushheaders
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/MimeWriter.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/MimeWriter.py
MIT
def startbody(self, ctype, plist=[], prefix=1): """Returns a file-like object for writing the body of the message. The content-type is set to the provided ctype, and the optional parameter, plist, provides additional parameters for the content-type declaration. The optional argument prefix determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to insert at the start. """ for name, value in plist: ctype = ctype + ';\n %s=\"%s\"' % (name, value) self.addheader("Content-Type", ctype, prefix=prefix) self.flushheaders() self._fp.write("\n") return self._fp
Returns a file-like object for writing the body of the message. The content-type is set to the provided ctype, and the optional parameter, plist, provides additional parameters for the content-type declaration. The optional argument prefix determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to insert at the start.
startbody
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/MimeWriter.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/MimeWriter.py
MIT
def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1): """Returns a file-like object for writing the body of the message. Additionally, this method initializes the multi-part code, where the subtype parameter provides the multipart subtype, the boundary parameter may provide a user-defined boundary specification, and the plist parameter provides optional parameters for the subtype. The optional argument, prefix, determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to insert at the start. Subparts should be created using the nextpart() method. """ self._boundary = boundary or mimetools.choose_boundary() return self.startbody("multipart/" + subtype, [("boundary", self._boundary)] + plist, prefix=prefix)
Returns a file-like object for writing the body of the message. Additionally, this method initializes the multi-part code, where the subtype parameter provides the multipart subtype, the boundary parameter may provide a user-defined boundary specification, and the plist parameter provides optional parameters for the subtype. The optional argument, prefix, determines where the header is inserted; 0 means append at the end, 1 means insert at the start. The default is to insert at the start. Subparts should be created using the nextpart() method.
startmultipartbody
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/MimeWriter.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/MimeWriter.py
MIT
def mime_decode(line): """Decode a single line of quoted-printable text to 8bit.""" newline = '' pos = 0 while 1: res = mime_code.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ chr(int(res.group(1), 16)) pos = res.end(0) return newline + line[pos:]
Decode a single line of quoted-printable text to 8bit.
mime_decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def unmimify_part(ifile, ofile, decode_base64 = 0): """Convert a quoted-printable part of a MIME mail message to 8bit.""" multipart = None quoted_printable = 0 is_base64 = 0 is_repl = 0 if ifile.boundary and ifile.boundary[:2] == QUOTE: prefix = QUOTE else: prefix = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: return if prefix and line[:len(prefix)] == prefix: line = line[len(prefix):] pref = prefix else: pref = '' line = mime_decode_header(line) if qp.match(line): quoted_printable = 1 continue # skip this header if decode_base64 and base64_re.match(line): is_base64 = 1 continue ofile.write(pref + line) if not prefix and repl.match(line): # we're dealing with a reply message is_repl = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): break if is_repl and (quoted_printable or multipart): is_repl = 0 # read body while 1: line = ifile.readline() if not line: return line = re.sub(mime_head, '\\1', line) if prefix and line[:len(prefix)] == prefix: line = line[len(prefix):] pref = prefix else: pref = '' ## if is_repl and len(line) >= 4 and line[:4] == QUOTE+'--' and line[-3:] != '--\n': ## multipart = line[:-1] while multipart: if line == multipart + '--\n': ofile.write(pref + line) multipart = None line = None break if line == multipart + '\n': ofile.write(pref + line) nifile = File(ifile, multipart) unmimify_part(nifile, ofile, decode_base64) line = nifile.peek if not line: # premature end of file break continue # not a boundary between parts break if line and quoted_printable: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) if line and is_base64 and not pref: import base64 line = base64.decodestring(line) if line: ofile.write(pref + line)
Convert a quoted-printable part of a MIME mail message to 8bit.
unmimify_part
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def unmimify(infile, outfile, decode_base64 = 0): """Convert quoted-printable parts of a MIME mail message to 8bit.""" if type(infile) == type(''): ifile = open(infile) if type(outfile) == type('') and infile == outfile: import os d, f = os.path.split(infile) os.rename(infile, os.path.join(d, ',' + f)) else: ifile = infile if type(outfile) == type(''): ofile = open(outfile, 'w') else: ofile = outfile nifile = File(ifile, None) unmimify_part(nifile, ofile, decode_base64) ofile.flush()
Convert quoted-printable parts of a MIME mail message to 8bit.
unmimify
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def mime_encode(line, header): """Code a single line as quoted-printable. If header is set, quote some extra characters.""" if header: reg = mime_header_char else: reg = mime_char newline = '' pos = 0 if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = ('=%02x' % ord('F')).upper() pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[pos:res.start(0)] + \ ('=%02x' % ord(res.group(0))).upper() pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
Code a single line as quoted-printable. If header is set, quote some extra characters.
mime_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def mime_encode_header(line): """Code a single header line as quoted-printable.""" newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = '%s%s%s=?%s?Q?%s?=' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1)) pos = res.end(0) return newline + line[pos:]
Code a single header line as quoted-printable.
mime_encode_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def mimify_part(ifile, ofile, is_mime): """Convert an 8bit part of a MIME mail message to quoted-printable.""" has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: # change us-ascii into iso-8859-1 if chrset_res.group(2).lower() == 'us-ascii': line = '%s%s%s' % (chrset_res.group(1), CHARSET, chrset_res.group(3)) else: # change iso-8859-* into us-ascii line = '%sus-ascii%s' % chrset_res.group(1, 3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': # read bit after the end of the last part while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek if not line: # premature end of file break ofile.write(line) continue # unexpectedly no multipart separator--copy rest of file while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line)
Convert an 8bit part of a MIME mail message to quoted-printable.
mimify_part
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def mimify(infile, outfile): """Convert 8bit parts of a MIME mail message to quoted-printable.""" if type(infile) == type(''): ifile = open(infile) if type(outfile) == type('') and infile == outfile: import os d, f = os.path.split(infile) os.rename(infile, os.path.join(d, ',' + f)) else: ifile = infile if type(outfile) == type(''): ofile = open(outfile, 'w') else: ofile = outfile nifile = File(ifile, None) mimify_part(nifile, ofile, 0) ofile.flush()
Convert 8bit parts of a MIME mail message to quoted-printable.
mimify
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mimify.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mimify.py
MIT
def report(self): """Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing. """ print print " %-25s %s" % ("Name", "File") print " %-25s %s" % ("----", "----") # Print modules found keys = self.modules.keys() keys.sort() for key in keys: m = self.modules[key] if m.__path__: print "P", else: print "m", print "%-25s" % key, m.__file__ or "" # Print missing modules missing, maybe = self.any_missing_maybe() if missing: print print "Missing modules:" for name in missing: mods = self.badmodules[name].keys() mods.sort() print "?", name, "imported from", ', '.join(mods) # Print modules that may be missing, but then again, maybe not... if maybe: print print "Submodules that appear to be missing, but could also be", print "global names in the parent package:" for name in maybe: mods = self.badmodules[name].keys() mods.sort() print "?", name, "imported from", ', '.join(mods)
Print a report to stdout, listing the found modules with their paths, as well as modules that are missing, or seem to be missing.
report
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/modulefinder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/modulefinder.py
MIT
def any_missing(self): """Return a list of modules that appear to be missing. Use any_missing_maybe() if you want to know which modules are certain to be missing, and which *may* be missing. """ missing, maybe = self.any_missing_maybe() return missing + maybe
Return a list of modules that appear to be missing. Use any_missing_maybe() if you want to know which modules are certain to be missing, and which *may* be missing.
any_missing
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/modulefinder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/modulefinder.py
MIT
def any_missing_maybe(self): """Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. The reason it can't always be determined is that it's impossible to tell which names are imported when "from module import *" is done with an extension module, short of actually importing it. """ missing = [] maybe = [] for name in self.badmodules: if name in self.excludes: continue i = name.rfind(".") if i < 0: missing.append(name) continue subname = name[i+1:] pkgname = name[:i] pkg = self.modules.get(pkgname) if pkg is not None: if pkgname in self.badmodules[name]: # The package tried to import this module itself and # failed. It's definitely missing. missing.append(name) elif subname in pkg.globalnames: # It's a global in the package: definitely not missing. pass elif pkg.starimports: # It could be missing, but the package did an "import *" # from a non-Python module, so we simply can't be sure. maybe.append(name) else: # It's not a global in the package, the package didn't # do funny star imports, it's very likely to be missing. # The symbol could be inserted into the package from the # outside, but since that's not good style we simply list # it missing. missing.append(name) else: missing.append(name) missing.sort() maybe.sort() return missing, maybe
Return two lists, one with modules that are certainly missing and one with modules that *may* be missing. The latter names could either be submodules *or* just global names in the package. The reason it can't always be determined is that it's impossible to tell which names are imported when "from module import *" is done with an extension module, short of actually importing it.
any_missing_maybe
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/modulefinder.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/modulefinder.py
MIT
def testandset(self): """Atomic test-and-set -- grab the lock if it is not set, return True if it succeeded.""" if not self.locked: self.locked = True return True else: return False
Atomic test-and-set -- grab the lock if it is not set, return True if it succeeded.
testandset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mutex.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mutex.py
MIT
def lock(self, function, argument): """Lock a mutex, call the function with supplied argument when it is acquired. If the mutex is already locked, place function and argument in the queue.""" if self.testandset(): function(argument) else: self.queue.append((function, argument))
Lock a mutex, call the function with supplied argument when it is acquired. If the mutex is already locked, place function and argument in the queue.
lock
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mutex.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mutex.py
MIT
def unlock(self): """Unlock a mutex. If the queue is not empty, call the next function with its argument.""" if self.queue: function, argument = self.queue.popleft() function(argument) else: self.locked = False
Unlock a mutex. If the queue is not empty, call the next function with its argument.
unlock
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mutex.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mutex.py
MIT
def authenticators(self, host): """Return a (user, account, password) tuple for given host.""" if host in self.hosts: return self.hosts[host] elif 'default' in self.hosts: return self.hosts['default'] else: return None
Return a (user, account, password) tuple for given host.
authenticators
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/netrc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/netrc.py
MIT
def __repr__(self): """Dump the class data in the format of a .netrc file.""" rep = "" for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + "machine "+ host + "\n\tlogin " + repr(attrs[0]) + "\n" if attrs[1]: rep = rep + "account " + repr(attrs[1]) rep = rep + "\tpassword " + repr(attrs[2]) + "\n" for macro in self.macros.keys(): rep = rep + "macdef " + macro + "\n" for line in self.macros[macro]: rep = rep + line rep = rep + "\n" return rep
Dump the class data in the format of a .netrc file.
__repr__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/netrc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/netrc.py
MIT
def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=True): """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting. readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode. """ self.host = host self.port = port self.sock = socket.create_connection((host, port)) self.file = self.sock.makefile('rb') self.debugging = 0 self.welcome = self.getresp() # 'mode reader' is sometimes necessary to enable 'reader' mode. # However, the order in which 'mode reader' and 'authinfo' need to # arrive differs between some NNTP servers. Try to send # 'mode reader', and if it fails with an authorization failed # error, try again after sending authinfo. readermode_afterauth = 0 if readermode: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: # error 500, probably 'not implemented' pass except NNTPTemporaryError, e: if user and e.response[:3] == '480': # Need authorization before 'mode reader' readermode_afterauth = 1 else: raise # If no login/password was specified, try to get them from ~/.netrc # Presume that if .netc has an entry, NNRP authentication is required. try: if usenetrc and not user: import netrc credentials = netrc.netrc() auth = credentials.authenticators(host) if auth: user = auth[0] password = auth[2] except IOError: pass # Perform NNRP authentication if needed. if user: resp = self.shortcmd('authinfo user '+user) if resp[:3] == '381': if not password: raise NNTPReplyError(resp) else: resp = self.shortcmd( 'authinfo pass '+password) if resp[:3] != '281': raise NNTPPermanentError(resp) if readermode_afterauth: try: self.welcome = self.shortcmd('mode reader') except NNTPPermanentError: # error 500, probably 'not implemented' pass
Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting. readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def putline(self, line): """Internal: send one line to the server, appending CRLF.""" line = line + CRLF if self.debugging > 1: print '*put*', repr(line) self.sock.sendall(line)
Internal: send one line to the server, appending CRLF.
putline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def getline(self): """Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.""" line = self.file.readline(_MAXLINE + 1) if len(line) > _MAXLINE: raise NNTPDataError('line too long') if self.debugging > 1: print '*get*', repr(line) if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line
Internal: return one line from the server, stripping CRLF. Raise EOFError if the connection is closed.
getline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def getresp(self): """Internal: get a response from the server. Raise various errors if the response indicates an error.""" resp = self.getline() if self.debugging: print '*resp*', repr(resp) c = resp[:1] if c == '4': raise NNTPTemporaryError(resp) if c == '5': raise NNTPPermanentError(resp) if c not in '123': raise NNTPProtocolError(resp) return resp
Internal: get a response from the server. Raise various errors if the response indicates an error.
getresp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def getlongresp(self, file=None): """Internal: get a response plus following text from the server. Raise various errors if the response indicates an error.""" openedFile = None try: # If a string was passed then open a file with that name if isinstance(file, str): openedFile = file = open(file, "w") resp = self.getresp() if resp[:3] not in LONGRESP: raise NNTPReplyError(resp) list = [] while 1: line = self.getline() if line == '.': break if line[:2] == '..': line = line[1:] if file: file.write(line + "\n") else: list.append(line) finally: # If this method created the file, then it must close it if openedFile: openedFile.close() return resp, list
Internal: get a response plus following text from the server. Raise various errors if the response indicates an error.
getlongresp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def newnews(self, group, date, time, file=None): """Process a NEWNEWS command. Arguments: - group: group name or '*' - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of message ids""" cmd = 'NEWNEWS ' + group + ' ' + date + ' ' + time return self.longcmd(cmd, file)
Process a NEWNEWS command. Arguments: - group: group name or '*' - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of message ids
newnews
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def list(self, file=None): """Process a LIST command. Return: - resp: server response if successful - list: list of (group, last, first, flag) (strings)""" resp, list = self.longcmd('LIST', file) for i in range(len(list)): # Parse lines into "group last first flag" list[i] = tuple(list[i].split()) return resp, list
Process a LIST command. Return: - resp: server response if successful - list: list of (group, last, first, flag) (strings)
list
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def description(self, group): """Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.""" resp, lines = self.descriptions(group) if len(lines) == 0: return "" else: return lines[0][1]
Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.
description
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def descriptions(self, group_pattern): """Get descriptions for a range of groups.""" line_pat = re.compile("^(?P<group>[^ \t]+)[ \t]+(.*)$") # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first resp, raw_lines = self.longcmd('LIST NEWSGROUPS ' + group_pattern) if resp[:3] != "215": # Now the deprecated XGTITLE. This either raises an error # or succeeds with the same output structure as LIST # NEWSGROUPS. resp, raw_lines = self.longcmd('XGTITLE ' + group_pattern) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return resp, lines
Get descriptions for a range of groups.
descriptions
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def group(self, name): """Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles (string) - first: first article number (string) - last: last article number (string) - name: the group name""" resp = self.shortcmd('GROUP ' + name) if resp[:3] != '211': raise NNTPReplyError(resp) words = resp.split() count = first = last = 0 n = len(words) if n > 1: count = words[1] if n > 2: first = words[2] if n > 3: last = words[3] if n > 4: name = words[4].lower() return resp, count, first, last, name
Process a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles (string) - first: first article number (string) - last: last article number (string) - name: the group name
group
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def statparse(self, resp): """Internal: parse the response of a STAT, NEXT or LAST command.""" if resp[:2] != '22': raise NNTPReplyError(resp) words = resp.split() nr = 0 id = '' n = len(words) if n > 1: nr = words[1] if n > 2: id = words[2] return resp, nr, id
Internal: parse the response of a STAT, NEXT or LAST command.
statparse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def artcmd(self, line, file=None): """Internal: process a HEAD, BODY or ARTICLE command.""" resp, list = self.longcmd(line, file) resp, nr, id = self.statparse(resp) return resp, nr, id, list
Internal: process a HEAD, BODY or ARTICLE command.
artcmd
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def xhdr(self, hdr, str, file=None): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings""" pat = re.compile('^([0-9]+) ?(.*)\n?') resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file) for i in range(len(lines)): line = lines[i] m = pat.match(line) if m: lines[i] = m.group(1, 2) return resp, lines
Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings
xhdr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def xover(self, start, end, file=None): """Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range Returns: - resp: server response if successful - list: list of (art-nr, subject, poster, date, id, references, size, lines)""" resp, lines = self.longcmd('XOVER ' + start + '-' + end, file) xover_lines = [] for line in lines: elem = line.split("\t") try: xover_lines.append((elem[0], elem[1], elem[2], elem[3], elem[4], elem[5].split(), elem[6], elem[7])) except IndexError: raise NNTPDataError(line) return resp,xover_lines
Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range Returns: - resp: server response if successful - list: list of (art-nr, subject, poster, date, id, references, size, lines)
xover
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def xgtitle(self, group, file=None): """Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings""" line_pat = re.compile("^([^ \t]+)[ \t]+(.*)$") resp, raw_lines = self.longcmd('XGTITLE ' + group, file) lines = [] for raw_line in raw_lines: match = line_pat.search(raw_line.strip()) if match: lines.append(match.group(1, 2)) return resp, lines
Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings
xgtitle
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def xpath(self,id): """Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article""" resp = self.shortcmd("XPATH " + id) if resp[:3] != '223': raise NNTPReplyError(resp) try: [resp_num, path] = resp.split() except ValueError: raise NNTPReplyError(resp) else: return resp, path
Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article
xpath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def date (self): """Process the DATE command. Arguments: None Returns: resp: server response if successful date: Date suitable for newnews/newgroups commands etc. time: Time suitable for newnews/newgroups commands etc.""" resp = self.shortcmd("DATE") if resp[:3] != '111': raise NNTPReplyError(resp) elem = resp.split() if len(elem) != 2: raise NNTPDataError(resp) date = elem[1][2:8] time = elem[1][-6:] if len(date) != 6 or len(time) != 6: raise NNTPDataError(resp) return resp, date, time
Process the DATE command. Arguments: None Returns: resp: server response if successful date: Date suitable for newnews/newgroups commands etc. time: Time suitable for newnews/newgroups commands etc.
date
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def post(self, f): """Process a POST command. Arguments: - f: file containing the article Returns: - resp: server response if successful""" resp = self.shortcmd('POST') # Raises error_??? if posting is not allowed if resp[0] != '3': raise NNTPReplyError(resp) while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.' + line self.putline(line) self.putline('.') return self.getresp()
Process a POST command. Arguments: - f: file containing the article Returns: - resp: server response if successful
post
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def ihave(self, id, f): """Process an IHAVE command. Arguments: - id: message-id of the article - f: file containing the article Returns: - resp: server response if successful Note that if the server refuses the article an exception is raised.""" resp = self.shortcmd('IHAVE ' + id) # Raises error_??? if the server already has it if resp[0] != '3': raise NNTPReplyError(resp) while 1: line = f.readline() if not line: break if line[-1] == '\n': line = line[:-1] if line[:1] == '.': line = '.' + line self.putline(line) self.putline('.') return self.getresp()
Process an IHAVE command. Arguments: - id: message-id of the article - f: file containing the article Returns: - resp: server response if successful Note that if the server refuses the article an exception is raised.
ihave
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def quit(self): """Process a QUIT command and close the socket. Returns: - resp: server response if successful""" resp = self.shortcmd('QUIT') self.file.close() self.sock.close() del self.file, self.sock return resp
Process a QUIT command and close the socket. Returns: - resp: server response if successful
quit
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nntplib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nntplib.py
MIT
def join(path, *paths): """Join two or more pathname components, inserting "\\" as needed.""" result_drive, result_path = splitdrive(path) for p in paths: p_drive, p_path = splitdrive(p) if p_path and p_path[0] in '\\/': # Second path is absolute if p_drive or not result_drive: result_drive = p_drive result_path = p_path continue elif p_drive and p_drive != result_drive: if p_drive.lower() != result_drive.lower(): # Different drives => ignore the first path entirely result_drive = p_drive result_path = p_path continue # Same drive in different case result_drive = p_drive # Second path is relative to the first if result_path and result_path[-1] not in '\\/': result_path = result_path + '\\' result_path = result_path + p_path ## add separator between UNC and non-absolute path if (result_path and result_path[0] not in '\\/' and result_drive and result_drive[-1:] != ':'): return result_drive + sep + result_path return result_drive + result_path
Join two or more pathname components, inserting "\" as needed.
join
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def splitdrive(p): """Split a pathname into drive/UNC sharepoint and relative path specifiers. Returns a 2-tuple (drive_or_unc, path); either part may be empty. If you assign result = splitdrive(p) It is always true that: result[0] + result[1] == p If the path contained a drive letter, drive_or_unc will contain everything up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") If the path contained a UNC path, the drive_or_unc will contain the host name and share up to but not including the fourth directory separator character. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") Paths cannot contain both a drive letter and a UNC path. """ if len(p) > 1: normp = p.replace(altsep, sep) if (normp[0:2] == sep*2) and (normp[2:3] != sep): # is a UNC path: # vvvvvvvvvvvvvvvvvvvv drive letter or UNC path # \\machine\mountpoint\directory\etc\... # directory ^^^^^^^^^^^^^^^ index = normp.find(sep, 2) if index == -1: return '', p index2 = normp.find(sep, index + 1) # a UNC path can't have two slashes in a row # (after the initial two) if index2 == index + 1: return '', p if index2 == -1: index2 = len(p) return p[:index2], p[index2:] if normp[1] == ':': return p[:2], p[2:] return '', p
Split a pathname into drive/UNC sharepoint and relative path specifiers. Returns a 2-tuple (drive_or_unc, path); either part may be empty. If you assign result = splitdrive(p) It is always true that: result[0] + result[1] == p If the path contained a drive letter, drive_or_unc will contain everything up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir") If the path contained a UNC path, the drive_or_unc will contain the host name and share up to but not including the fourth directory separator character. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir") Paths cannot contain both a drive letter and a UNC path.
splitdrive
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def splitunc(p): """Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have a UNC part. """ if p[1:2] == ':': return '', p # Drive letter present firstTwo = p[0:2] if firstTwo == '//' or firstTwo == '\\\\': # is a UNC path: # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter # \\machine\mountpoint\directories... # directory ^^^^^^^^^^^^^^^ normp = p.replace('\\', '/') index = normp.find('/', 2) if index <= 2: return '', p index2 = normp.find('/', index + 1) # a UNC path can't have two slashes in a row # (after the initial two) if index2 == index + 1: return '', p if index2 == -1: index2 = len(p) return p[:index2], p[index2:] return '', p
Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have a UNC part.
splitunc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def split(p): """Split a pathname. Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty.""" d, p = splitdrive(p) # set i to index beyond p's last slash i = len(p) while i and p[i-1] not in '/\\': i = i - 1 head, tail = p[:i], p[i:] # now tail has no slashes # remove trailing slashes from head, unless it's all slashes head2 = head while head2 and head2[-1] in '/\\': head2 = head2[:-1] head = head2 or head return d + head, tail
Split a pathname. Return tuple (head, tail) where tail is everything after the final slash. Either part may be empty.
split
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def ismount(path): """Test whether a path is a mount point (defined as root of drive)""" unc, rest = splitunc(path) if unc: return rest in ("", "/", "\\") p = splitdrive(path)[1] return len(p) == 1 and p[0] in '/\\'
Test whether a path is a mount point (defined as root of drive)
ismount
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.""" warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.", stacklevel=2) try: names = os.listdir(top) except os.error: return func(arg, top, names) for name in names: name = join(top, name) if isdir(name): walk(name, func, arg)
Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.
walk
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def expanduser(path): """Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] not in '/\\': i = i + 1 if 'HOME' in os.environ: userhome = os.environ['HOME'] elif 'USERPROFILE' in os.environ: userhome = os.environ['USERPROFILE'] elif not 'HOMEPATH' in os.environ: return path else: try: drive = os.environ['HOMEDRIVE'] except KeyError: drive = '' userhome = join(drive, os.environ['HOMEPATH']) if i != 1: #~user userhome = join(dirname(userhome), path[1:i]) return userhome + path[i:]
Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.
expanduser
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def expandvars(path): """Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" if '$' not in path and '%' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' if isinstance(path, _unicode): encoding = sys.getfilesystemencoding() def getenv(var): return os.environ[var.encode(encoding)].decode(encoding) else: def getenv(var): return os.environ[var] res = '' index = 0 pathlen = len(path) while index < pathlen: c = path[index] if c == '\'': # no expansion within single quotes path = path[index + 1:] pathlen = len(path) try: index = path.index('\'') res = res + '\'' + path[:index + 1] except ValueError: res = res + c + path index = pathlen - 1 elif c == '%': # variable or '%' if path[index + 1:index + 2] == '%': res = res + c index = index + 1 else: path = path[index+1:] pathlen = len(path) try: index = path.index('%') except ValueError: res = res + '%' + path index = pathlen - 1 else: var = path[:index] try: res = res + getenv(var) except KeyError: res = res + '%' + var + '%' elif c == '$': # variable or '$$' if path[index + 1:index + 2] == '$': res = res + c index = index + 1 elif path[index + 1:index + 2] == '{': path = path[index+2:] pathlen = len(path) try: index = path.index('}') var = path[:index] try: res = res + getenv(var) except KeyError: res = res + '${' + var + '}' except ValueError: res = res + '${' + path index = pathlen - 1 else: var = '' index = index + 1 c = path[index:index + 1] while c != '' and c in varchars: var = var + c index = index + 1 c = path[index:index + 1] try: res = res + getenv(var) except KeyError: res = res + '$' + var if c != '': index = index - 1 else: res = res + c index = index + 1 return res
Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.
expandvars
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def normpath(path): """Normalize path, eliminating double slashes, etc.""" # Preserve unicode (if path is unicode) backslash, dot = (u'\\', u'.') if isinstance(path, _unicode) else ('\\', '.') if path.startswith(('\\\\.\\', '\\\\?\\')): # in the case of paths with these prefixes: # \\.\ -> device names # \\?\ -> literal paths # do not do any normalization, but return the path unchanged return path path = path.replace("/", "\\") prefix, path = splitdrive(path) # We need to be careful here. If the prefix is empty, and the path starts # with a backslash, it could either be an absolute path on the current # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It # is therefore imperative NOT to collapse multiple backslashes blindly in # that case. # The code below preserves multiple backslashes when there is no drive # letter. This means that the invalid filename \\\a\b is preserved # unchanged, where a\\\b is normalised to a\b. It's not clear that there # is any better behaviour for such edge cases. if prefix == '': # No drive letter - preserve initial backslashes while path[:1] == "\\": prefix = prefix + backslash path = path[1:] else: # We have a drive letter - collapse initial backslashes if path.startswith("\\"): prefix = prefix + backslash path = path.lstrip("\\") comps = path.split("\\") i = 0 while i < len(comps): if comps[i] in ('.', ''): del comps[i] elif comps[i] == '..': if i > 0 and comps[i-1] != '..': del comps[i-1:i+1] i -= 1 elif i == 0 and prefix.endswith("\\"): del comps[i] else: i += 1 else: i += 1 # If the path is now empty, substitute '.' if not prefix and not comps: comps.append(dot) return prefix + backslash.join(comps)
Normalize path, eliminating double slashes, etc.
normpath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def abspath(path): """Return the absolute version of a path.""" if not isabs(path): if isinstance(path, _unicode): cwd = os.getcwdu() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path)
Return the absolute version of a path.
abspath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def abspath(path): """Return the absolute version of a path.""" if path: # Empty path must return current working directory. try: path = _getfullpathname(path) except WindowsError: pass # Bad path - return unchanged. elif isinstance(path, _unicode): path = os.getcwdu() else: path = os.getcwd() return normpath(path)
Return the absolute version of a path.
abspath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ntpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ntpath.py
MIT
def url2pathname(url): """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.""" # e.g. # ///C|/foo/bar/spam.foo # and # ///C:/foo/bar/spam.foo # become # C:\foo\bar\spam.foo import string, urllib # Windows itself uses ":" even in URLs. url = url.replace(':', '|') if not '|' in url: # No drive specifier, just convert slashes if url[:4] == '////': # path is something like ////host/path/on/remote/host # convert this to \\host\path\on\remote\host # (notice halving of slashes at the start of the path) url = url[2:] components = url.split('/') # make sure not to convert quoted slashes :-) return urllib.unquote('\\'.join(components)) comp = url.split('|') if len(comp) != 2 or comp[0][-1] not in string.ascii_letters: error = 'Bad URL: ' + url raise IOError, error drive = comp[0][-1].upper() path = drive + ':' components = comp[1].split('/') for comp in components: if comp: path = path + '\\' + urllib.unquote(comp) # Issue #11474: url like '/C|/' should convert into 'C:\\' if path.endswith(':') and url.endswith('/'): path += '\\' return path
OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.
url2pathname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nturl2path.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nturl2path.py
MIT
def pathname2url(p): """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.""" # e.g. # C:\foo\bar\spam.foo # becomes # ///C:/foo/bar/spam.foo import urllib if not ':' in p: # No drive specifier, just convert slashes and quote the name if p[:2] == '\\\\': # path is something like \\host\path\on\remote\host # convert this to ////host/path/on/remote/host # (notice doubling of slashes at the start of the path) p = '\\\\' + p components = p.split('\\') return urllib.quote('/'.join(components)) comp = p.split(':') if len(comp) != 2 or len(comp[0]) > 1: error = 'Bad path: ' + p raise IOError, error drive = urllib.quote(comp[0].upper()) components = comp[1].split('\\') path = '///' + drive + ':' for comp in components: if comp: path = path + '/' + urllib.quote(comp) return path
OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.
pathname2url
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/nturl2path.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/nturl2path.py
MIT
def _format_text(self, text): """ Format a paragraph of free-form text for inclusion in the help output at the current indentation level. """ text_width = max(self.width - self.current_indent, 11) indent = " "*self.current_indent return textwrap.fill(text, text_width, initial_indent=indent, subsequent_indent=indent)
Format a paragraph of free-form text for inclusion in the help output at the current indentation level.
_format_text
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): metavar = option.metavar or option.dest.upper() short_opts = [self._short_opt_fmt % (sopt, metavar) for sopt in option._short_opts] long_opts = [self._long_opt_fmt % (lopt, metavar) for lopt in option._long_opts] else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts return ", ".join(opts)
Return a comma-separated list of option strings & metavariables.
format_option_strings
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def _update_careful(self, dict): """ Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored. """ for attr in dir(self): if attr in dict: dval = dict[attr] if dval is not None: setattr(self, attr, dval)
Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored.
_update_careful
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def destroy(self): """ Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser (and all objects referenced by it) can be garbage-collected promptly. After calling destroy(), the OptionParser is unusable. """ OptionContainer.destroy(self) for group in self.option_groups: group.destroy() del self.option_list del self.option_groups del self.formatter
Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser (and all objects referenced by it) can be garbage-collected promptly. After calling destroy(), the OptionParser is unusable.
destroy
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def parse_args(self, args=None, values=None): """ parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is a Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options. """ rargs = self._get_args(args) if values is None: values = self.get_default_values() # Store the halves of the argument list as attributes for the # convenience of callbacks: # rargs # the rest of the command-line (the "r" stands for # "remaining" or "right-hand") # largs # the leftover arguments -- ie. what's left after removing # options and their arguments (the "l" stands for "leftover" # or "left-hand") self.rargs = rargs self.largs = largs = [] self.values = values try: stop = self._process_args(largs, rargs, values) except (BadOptionError, OptionValueError), err: self.error(str(err)) args = largs + rargs return self.check_values(values, args)
parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is a Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options.
parse_args
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT