bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def test(): import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') except getopt.error, msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." print "-t: quote tabs" print "-d: decode; default encode" sys.exit(2) deco = 0 tabs = 0 for o, a in opts: if o == '-t': tabs = 1 if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr print "-t and -d are mutually exclusive" sys.exit(2) if not args: args = ['-'] sts = 0 for file in args: if file == '-': fp = sys.stdin else: try: fp = open(file) except IOError, msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue if deco: decode(fp, sys.stdout) else: encode(fp, sys.stdout, tabs) if fp is not sys.stdin: fp.close() if sts: sys.exit(sts)
def main(): import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') except getopt.error, msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." print "-t: quote tabs" print "-d: decode; default encode" sys.exit(2) deco = 0 tabs = 0 for o, a in opts: if o == '-t': tabs = 1 if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr print "-t and -d are mutually exclusive" sys.exit(2) if not args: args = ['-'] sts = 0 for file in args: if file == '-': fp = sys.stdin else: try: fp = open(file) except IOError, msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue if deco: decode(fp, sys.stdout) else: encode(fp, sys.stdout, tabs) if fp is not sys.stdin: fp.close() if sts: sys.exit(sts)
17,100
def test(): import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') except getopt.error, msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." print "-t: quote tabs" print "-d: decode; default encode" sys.exit(2) deco = 0 tabs = 0 for o, a in opts: if o == '-t': tabs = 1 if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr print "-t and -d are mutually exclusive" sys.exit(2) if not args: args = ['-'] sts = 0 for file in args: if file == '-': fp = sys.stdin else: try: fp = open(file) except IOError, msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue if deco: decode(fp, sys.stdout) else: encode(fp, sys.stdout, tabs) if fp is not sys.stdin: fp.close() if sts: sys.exit(sts)
def test(): import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'td') except getopt.error, msg: sys.stdout = sys.stderr print msg print "usage: quopri [-t | -d] [file] ..." print "-t: quote tabs" print "-d: decode; default encode" sys.exit(2) deco = 0 tabs = 0 for o, a in opts: if o == '-t': tabs = 1 if o == '-d': deco = 1 if tabs and deco: sys.stdout = sys.stderr print "-t and -d are mutually exclusive" sys.exit(2) if not args: args = ['-'] sts = 0 for file in args: if file == '-': fp = sys.stdin else: try: fp = open(file) except IOError, msg: sys.stderr.write("%s: can't open (%s)\n" % (file, msg)) sts = 1 continue if deco: decode(fp, sys.stdout) else: encode(fp, sys.stdout, tabs) if fp is not sys.stdin: fp.close() if sts: sys.exit(sts)
17,101
def run (self):
def run (self):
17,102
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
17,103
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
17,104
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
def create_inifile (self): # Create an inifile containing data describing the installation. # This could be done without creating a real file, but # a file is (at least) useful for debugging bdist_wininst.
17,105
def create_exe (self, arcname, fullname): import struct, zlib
def create_exe (self, arcname, fullname): import struct, zlib
17,106
def create_exe (self, arcname, fullname): import struct, zlib
def create_exe (self, arcname, fullname): import struct, zlib
17,107
def create_exe (self, arcname, fullname): import struct, zlib
def create_exe (self, arcname, fullname): import struct, zlib
17,108
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
17,109
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
17,110
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
17,111
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
def get_exe_bytes (self): import zlib, base64 return zlib.decompress (base64.decodestring (EXEDATA))
17,112
def read_lines_to_outerboundary(self):
def read_lines_to_outerboundary(self):
17,113
def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload() if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fast. If encoding to ASCII succeeds, we # know the data must be 7bit, otherwise treat it as 8bit. try: orig.encode('ascii') except UnicodeError: msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Transfer-Encoding'] = '7bit'
def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload() if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fast. If encoding to ASCII succeeds, we # know the data must be 7bit, otherwise treat it as 8bit. try: orig.encode('ascii') except UnicodeError: charset = msg.get_charset() output_cset = charset and charset.output_charset if output_cset and output_cset.lower().startswith('iso-2202-'): msg['Content-Transfer-Encoding'] = '7bit' else: msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Transfer-Encoding'] = '7bit'
17,114
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
17,115
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(t), size): bin = t[i:i+size] index = bincache.get(bin) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
17,116
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(t2) bincache[bin] = index t2.extend(bin) t1.append(index >> shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
17,117
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(t1)*getsize(t1) + len(t2)*getsize(t2) if trace: dump(t1, t2, shift, b) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
17,118
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = t1, t2, shift bytes = b shift, bin1, bin2 = best
17,119
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
def splitbins(bins): # split a sparse integer table into two tables, such as: # value = t2[(t1[char>>shift]<<shift)+(char&mask)] # and value == 0 means no data bytes = sys.maxint for shift in range(16): bin1 = [] bin2 = [] size = 2**shift bincache = {} for i in range(0, len(bins), size): bin = bins[i:i+size] index = bincache.get(tuple(bin)) if index is None: index = len(bin2) bincache[tuple(bin)] = index for v in bin: if v is None: bin2.append(0) else: bin2.append(v) bin1.append(index>>shift) # determine memory size b = len(bin1)*getsize(bin1) + len(bin2)*getsize(bin2) if b < bytes: best = shift, bin1, bin2 bytes = b shift, bin1, bin2 = best
17,120
def postcmd(self, stop, line): if stop: return stop return None
def postcmd(self, stop, line): if stop: return stop return None
17,121
def postcmd(self, stop, line): if stop: return stop return None
def postcmd(self, stop, line): if stop: return stop return None
17,122
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
17,123
def load_stats(self, arg): if not arg: self.stats = {} elif type(arg) == type(""): f = open(arg, 'rb') self.stats = marshal.load(f) f.close() try: file_stats = os.stat(arg) arg = time.ctime(file_stats.st_mtime) + " " + arg except: # in case this is not unix pass self.files = [ arg ] elif hasattr(arg, 'create_stats'): arg.create_stats() self.stats = arg.stats arg.stats = {} if not self.stats: raise TypeError, "Cannot create or construct a %r object from '%r''" % ( self.__class__, arg) return
def load_stats(self, arg): if not arg: self.stats = {} elif isinstance(arg, basestring): f = open(arg, 'rb') self.stats = marshal.load(f) f.close() try: file_stats = os.stat(arg) arg = time.ctime(file_stats.st_mtime) + " " + arg except: # in case this is not unix pass self.files = [ arg ] elif hasattr(arg, 'create_stats'): arg.create_stats() self.stats = arg.stats arg.stats = {} if not self.stats: raise TypeError, "Cannot create or construct a %r object from '%r''" % ( self.__class__, arg) return
17,124
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
17,125
def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days days.append(_center(s, width)) return ' '.join(days)
def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days days.append(s.center(width)) return ' '.join(days)
17,126
def weekheader(width): """Return a header for a week.""" if width >= 9: names = day_name else: names = day_abbr days = [] for i in range(_firstweekday, _firstweekday + 7): days.append(_center(names[i%7][:width], width)) return ' '.join(days)
def weekheader(width): """Return a header for a week.""" if width >= 9: names = day_name else: names = day_abbr days = [] for i in range(_firstweekday, _firstweekday + 7): days.append(names[i%7][:width].center(width)) return ' '.join(days)
17,127
def month(theyear, themonth, w=0, l=0): """Return a month's calendar string (multi-line).""" w = max(2, w) l = max(1, l) s = (_center(month_name[themonth] + ' ' + `theyear`, 7 * (w + 1) - 1).rstrip() + '\n' * l + weekheader(w).rstrip() + '\n' * l) for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n'
def month(theyear, themonth, w=0, l=0): """Return a month's calendar string (multi-line).""" w = max(2, w) l = max(1, l) s = ((month_name[themonth] + ' ' + `theyear`).center( 7 * (w + 1) - 1).rstrip() + '\n' * l + weekheader(w).rstrip() + '\n' * l) for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n'
17,128
def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from 3 strings, centered within 3 columns.""" return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) + ' ' * spacing + _center(c, colwidth))
def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from 3 strings, centered within 3 columns.""" return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) + ' ' * spacing + c.center(colwidth))
17,129
def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l) data = [] height = 0 for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): weeks = [] for cal in data: if i >= len(cal): weeks.append('') else: weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n'
def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l) data = [] height = 0 for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): weeks = [] for cal in data: if i >= len(cal): weeks.append('') else: weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n'
17,130
def add_header(self, _name, _value, **_params): """Extended header setting.
defadd_header(self,_name,_value,**_params):"""Extendedheadersetting.
17,131
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k, v in value.items(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
17,132
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: if unicode and type(k) is UnicodeType: k = k.encode(self.encoding) else: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
17,133
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(value[k], write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
def dump_struct(self, value, write, escape=escape): i = id(value) if self.memo.has_key(i): raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k in value.keys(): write("<member>\n") if type(k) is not StringType: raise TypeError, "dictionary key must be string" write("<name>%s</name>\n" % escape(k)) dump(v, write) write("</member>\n") write("</struct></value>\n") del self.memo[i]
17,134
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
17,135
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
17,136
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
def _make_spec_file(self): """Generate the text of an RPM spec file and return it as a list of strings (one per line). """ # definitions and headers spec_file = [ '%define name ' + self.distribution.get_name(), '%define version ' + self.distribution.get_version().replace('-','_'), '%define release ' + self.release.replace('-','_'), '', 'Summary: ' + self.distribution.get_description(), ]
17,137
def process_rawq(self): """Transfer from raw queue to cooked queue.
def process_rawq(self): """Transfer from raw queue to cooked queue.
17,138
def end_fill(): _getpen.end_fill()
def end_fill(): _getpen.end_fill()
17,139
def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: import re _typeprog = re.compile('^([^/:]+):') match = _typeprog.match(url) if match: scheme = match.group(1) return scheme, url[len(scheme) + 1:] return None, url
def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: import re _typeprog = re.compile('^([^/:]+):') match = _typeprog.match(url) if match: scheme = match.group(1) return scheme.lower(), url[len(scheme) + 1:] return None, url
17,140
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> import doctest >>> old = doctest._unittest_reportflags >>> doctest.set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
17,141
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
17,142
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> doctest.set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
17,143
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
17,144
def compile_path(skip_curdir=1, maxlevels=0, force=0): """Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default true) maxlevels: max recursion level (default 0) force: as for compile_dir() (default 0) """ for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: print 'Skipping current directory' else: compile_dir(dir, maxlevels, None, force)
def compile_path(skip_curdir=1, maxlevels=0, force=0): """Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default true) maxlevels: max recursion level (default 0) force: as for compile_dir() (default 0) """ for dir in sys.path: if (not dir or dir == os.curdir) and skip_curdir: print 'Skipping current directory' else: success = success and compile_dir(dir, maxlevels, None, force) return success
17,145
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]"
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: success = success and compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]"
17,146
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]"
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: success = compile_path() except KeyboardInterrupt: print "\n[interrupt]"
17,147
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]"
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfd:') except getopt.error, msg: print msg print "usage: compileall [-l] [-f] [-d destdir] [directory ...]" print "-l: don't recurse down" print "-f: force rebuild even if timestamps are up-to-date" print "-d destdir: purported directory name for error messages" print "if no directory arguments, -l sys.path is assumed" sys.exit(2) maxlevels = 10 ddir = None force = 0 for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if ddir: if len(args) != 1: print "-d destdir require exactly one directory argument" sys.exit(2) try: if args: for dir in args: compile_dir(dir, maxlevels, ddir, force) else: compile_path() except KeyboardInterrupt: print "\n[interrupt]"
17,148
def __init__(self, localaddr, remoteaddr): self._localaddr = localaddr self._remoteaddr = remoteaddr asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1) self.bind(localaddr) self.listen(5) print '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), localaddr, remoteaddr)
def __init__(self, localaddr, remoteaddr): self._localaddr = localaddr self._remoteaddr = remoteaddr asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1) self.bind(localaddr) self.listen(5) print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), localaddr, remoteaddr)
17,149
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: if self.__at_start: self.syntax_error('illegal data at start of file') self.__at_start = 0 data = rawdata[i:j] if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k self.literal = 0 continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1])
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: if self.__at_start: self.syntax_error('illegal data at start of file') self.__at_start = 0 data = rawdata[i:j] if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1])
17,150
def append(self, mailbox, flags, date_time, message): """Append message to named mailbox.
def append(self, mailbox, flags, date_time, message): """Append message to named mailbox.
17,151
def response(self, code): """Return data for response 'code' if received, or None.
def response(self, code): """Return data for response 'code' if received, or None.
17,152
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
17,153
def store(self, message_set, command, flag_list): """Alters flag dispositions for messages in mailbox.
def store(self, message_set, command, flag_list): """Alters flag dispositions for messages in mailbox.
17,154
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
def uid(self, command, *args): """Execute "command arg ..." with messages identified by UID, rather than message number.
17,155
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
17,156
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
def uid(self, command, args): """Execute "command args" with messages identified by UID, rather than message number.
17,157
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
def xatom(self, name, *args): """Allow simple extension commands notified by server in CAPABILITY response.
17,158
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
17,159
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
def xatom(self, name, arg1=None, arg2=None): """Allow simple extension commands notified by server in CAPABILITY response.
17,160
def _command(self, name, dat1=None, dat2=None, dat3=None, literal=None):
def _command(self, name, dat1=None, dat2=None, dat3=None, literal=None):
17,161
def _get_response(self):
def _get_response(self):
17,162
def _get_response(self):
def _get_response(self):
17,163
def _get_line(self):
def _get_line(self):
17,164
def _simple_command(self, name, dat1=None, dat2=None):
def _simple_command(self, name, dat1=None, dat2=None):
17,165
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
17,166
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ dttype = type(date_time) if dttype is type(1): tt = time.localtime(date_time) elif dttype is type(()): tt = date_time elif dttype is type(""): return date_time # Assume in correct format else: raise ValueError dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
17,167
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
17,168
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
def run(cmd, args): typ, dat = apply(eval('M.%s' % cmd), args) print ' %s %s\n => %s %s' % (cmd, args, typ, dat) return dat
17,169
def build_extension(self, ext):
def build_extension(self, ext):
17,170
def do_recent(self):
def do_recent(self):
17,171
def _readmodule(module, path, inpackage=None): '''Do the hard work for readmodule[_ex].''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = _readmodule(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return _readmodule(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict stack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if tokentype == DEDENT: lineno, thisindent = start # close nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] elif token == 'def': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error if stack: cur_class = stack[-1][0] if isinstance(cur_class, Class): # it's a method cur_class._addmethod(meth_name, lineno) # else it's a nested def else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) stack.append((None, thisindent)) # Marker for nested fns elif token == 'class': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) super = [] if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(fullmodule, class_name, inherit, file, lineno) if not stack: dict[class_name] = cur_class stack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: _readmodule(mod, path) else: try: _readmodule(mod, path, inpackage) except ImportError: _readmodule(mod, []) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = _readmodule(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # don't add names that start with _ for n in d: if n[0] != '_': dict[n] = d[n] except StopIteration: pass f.close() return dict
def _readmodule(module, path, inpackage=None): '''Do the hard work for readmodule[_ex].''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) elif tokentype in (NAME, OP) and level == 1: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = _readmodule(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return _readmodule(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) elif tokentype in (NAME, OP) and level == 1: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict stack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if tokentype == DEDENT: lineno, thisindent = start # close nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] elif token == 'def': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error if stack: cur_class = stack[-1][0] if isinstance(cur_class, Class): # it's a method cur_class._addmethod(meth_name, lineno) # else it's a nested def elif tokentype in (NAME, OP) and level == 1: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) stack.append((None, thisindent)) # Marker for nested fns elif token == 'class': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] elif tokentype in (NAME, OP) and level == 1: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) super = [] if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass elif tokentype in (NAME, OP) and level == 1: super.append(token) inherit = names cur_class = Class(fullmodule, class_name, inherit, file, lineno) if not stack: dict[class_name] = cur_class stack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: _readmodule(mod, path) elif tokentype in (NAME, OP) and level == 1: try: _readmodule(mod, path, inpackage) except ImportError: _readmodule(mod, []) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = _readmodule(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # don't add names that start with _ for n in d: if n[0] != '_': dict[n] = d[n] except StopIteration: pass f.close() return dict
17,172
def link (self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None): # First examine a couple of options for things that aren't implemented yet if not target_desc in (self.SHARED_LIBRARY, self.SHARED_OBJECT): raise DistutilsPlatformError, 'Can only make SHARED_LIBRARY or SHARED_OBJECT targets on the Mac' if runtime_library_dirs: raise DistutilsPlatformError, 'Runtime library dirs not implemented yet' if extra_preargs or extra_postargs: raise DistutilsPlatformError, 'Runtime library dirs not implemented yet' if len(export_symbols) != 1: raise DistutilsPlatformError, 'Need exactly one export symbol' # Next there are various things for which we need absolute pathnames. # This is because we (usually) create the project in a subdirectory of # where we are now, and keeping the paths relative is too much work right # now. sources = map(self._filename_to_abs, self.__sources) include_dirs = map(self._filename_to_abs, self.__include_dirs) if objects: objects = map(self._filename_to_abs, objects) else: objects = [] if build_temp: build_temp = self._filename_to_abs(build_temp) else: build_temp = os.curdir() if output_dir: output_filename = os.path.join(output_dir, output_filename) # The output filename needs special handling: splitting it into dir and # filename part. Actually I'm not sure this is really needed, but it # can't hurt. output_filename = self._filename_to_abs(output_filename) output_dir, output_filename = os.path.split(output_filename) # Now we need the short names of a couple of things for putting them # into the project. if output_filename[-8:] == '.ppc.slb': basename = output_filename[:-8] elif output_filename[-11:] == '.carbon.slb': basename = output_filename[:-11] else: basename = os.path.strip(output_filename)[0] projectname = basename + '.mcp' targetname = basename xmlname = basename + '.xml' exportname = basename + '.mcp.exp' prefixname = 'mwerks_%s_config.h'%basename # Create the directories we need distutils.dir_util.mkpath(build_temp, self.verbose, self.dry_run) distutils.dir_util.mkpath(output_dir, self.verbose, self.dry_run) # And on to filling in the parameters for the project builder settings = {} settings['mac_exportname'] = exportname settings['mac_outputdir'] = output_dir settings['mac_dllname'] = output_filename settings['mac_targetname'] = targetname settings['sysprefix'] = sys.prefix settings['mac_sysprefixtype'] = 'Absolute' sourcefilenames = [] sourcefiledirs = [] for filename in sources + objects: dirname, filename = os.path.split(filename) sourcefilenames.append(filename) if not dirname in sourcefiledirs: sourcefiledirs.append(dirname) settings['sources'] = sourcefilenames settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs if self.dry_run: print 'CALLING LINKER IN', os.getcwd() for key, value in settings.items(): print '%20.20s %s'%(key, value) return # Build the export file exportfilename = os.path.join(build_temp, exportname) if self.verbose: print '\tCreate export file', exportfilename fp = open(exportfilename, 'w') fp.write('%s\n'%export_symbols[0]) fp.close() # Generate the prefix file, if needed, and put it in the settings if self.__macros: prefixfilename = os.path.join(os.getcwd(), os.path.join(build_temp, prefixname)) fp = open(prefixfilename, 'w') fp.write('#include "mwerks_plugin_config.h"\n') for name, value in self.__macros: if value is None: fp.write('#define %s\n'%name) else: fp.write('#define %s "%s"\n'%(name, value)) fp.close() settings['prefixname'] = prefixname
def link (self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None): # First examine a couple of options for things that aren't implemented yet if not target_desc in (self.SHARED_LIBRARY, self.SHARED_OBJECT): raise DistutilsPlatformError, 'Can only make SHARED_LIBRARY or SHARED_OBJECT targets on the Mac' if runtime_library_dirs: raise DistutilsPlatformError, 'Runtime library dirs not implemented yet' if extra_preargs or extra_postargs: raise DistutilsPlatformError, 'Runtime library dirs not implemented yet' if len(export_symbols) != 1: raise DistutilsPlatformError, 'Need exactly one export symbol' # Next there are various things for which we need absolute pathnames. # This is because we (usually) create the project in a subdirectory of # where we are now, and keeping the paths relative is too much work right # now. sources = map(self._filename_to_abs, self.__sources) include_dirs = map(self._filename_to_abs, self.__include_dirs) if objects: objects = map(self._filename_to_abs, objects) else: objects = [] if build_temp: build_temp = self._filename_to_abs(build_temp) else: build_temp = os.curdir() if output_dir: output_filename = os.path.join(output_dir, output_filename) # The output filename needs special handling: splitting it into dir and # filename part. Actually I'm not sure this is really needed, but it # can't hurt. output_filename = self._filename_to_abs(output_filename) output_dir, output_filename = os.path.split(output_filename) # Now we need the short names of a couple of things for putting them # into the project. if output_filename[-8:] == '.ppc.slb': basename = output_filename[:-8] elif output_filename[-11:] == '.carbon.slb': basename = output_filename[:-11] else: basename = os.path.strip(output_filename)[0] projectname = basename + '.mcp' targetname = basename xmlname = basename + '.xml' exportname = basename + '.mcp.exp' prefixname = 'mwerks_%s_config.h'%basename # Create the directories we need distutils.dir_util.mkpath(build_temp, self.verbose, self.dry_run) distutils.dir_util.mkpath(output_dir, self.verbose, self.dry_run) # And on to filling in the parameters for the project builder settings = {} settings['mac_exportname'] = exportname settings['mac_outputdir'] = output_dir settings['mac_dllname'] = output_filename settings['mac_targetname'] = targetname settings['sysprefix'] = sys.prefix settings['mac_sysprefixtype'] = 'Absolute' sourcefilenames = [] sourcefiledirs = [] for filename in sources + objects: dirname, filename = os.path.split(filename) sourcefilenames.append(filename) if not dirname in sourcefiledirs: sourcefiledirs.append(dirname) settings['sources'] = sourcefilenames settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs if self.dry_run: print 'CALLING LINKER IN', os.getcwd() for key, value in settings.items(): print '%20.20s %s'%(key, value) return # Build the export file exportfilename = os.path.join(build_temp, exportname) if self.verbose: print '\tCreate export file', exportfilename fp = open(exportfilename, 'w') fp.write('%s\n'%export_symbols[0]) fp.close() # Generate the prefix file, if needed, and put it in the settings if self.__macros: prefixfilename = os.path.join(os.getcwd(), os.path.join(build_temp, prefixname)) fp = open(prefixfilename, 'w') fp.write('#include "mwerks_plugin_config.h"\n') for name, value in self.__macros: if value is None: fp.write('#define %s\n'%name) else: fp.write('#define %s "%s"\n'%(name, value)) fp.close() settings['prefixname'] = prefixname
17,173
def __init__(self,stream,errors='strict',mapping=None):
def __init__(self,stream,errors='strict',mapping=None):
17,174
def checkforhtml(self, info, url): if info.has_key('content-type'): ctype = string.lower(info['content-type']) else: if url[-1:] == "/": return 1 ctype, encoding = mimetypes.guess_type(url) if ctype == 'text/html': return 1 else: self.note(1, " Not HTML, mime type %s", ctype) return 0
def checkforhtml(self, info, url): if info.has_key('content-type'): ctype = string.lower(cgi.parse_header(info['content-type'])[0]) else: if url[-1:] == "/": return 1 ctype, encoding = mimetypes.guess_type(url) if ctype == 'text/html': return 1 else: self.note(1, " Not HTML, mime type %s", ctype) return 0
17,175
def mk16pixmap(w, h, data): """kludge a pixmap together""" rv = struct.pack("lhhhhhhhlllhhhhlll", id(data), w*2 + 0x8000, 0, 0, h, w, 0, 0, 0, # XXXX? 72<<16, 72<<16, 16, 16, # XXXX 3, 5, 0, 0, 0) print 'Our pixmap, size %d:'%len(rv) dumppixmap(rv) return Qd.RawBitMap(rv)
def mk16pixmap(w, h, data): """kludge a pixmap together""" rv = struct.pack("lhhhhhhhlllhhhhlll", id(data)+12, w*2 + 0x8000, 0, 0, h, w, 0, 0, 0, # XXXX? 72<<16, 72<<16, 16, 16, # XXXX 3, 5, 0, 0, 0) print 'Our pixmap, size %d:'%len(rv) dumppixmap(rv) return Qd.RawBitMap(rv)
17,176
def do_update(self, *args): pass currect = self.fitrect() print 'PICT:', self.pictrect print 'WIND:', currect print 'ARGS:', (self.pixmap, self.wid.GetWindowPort().portBits, self.pictrect, currect, QuickDraw.srcCopy, None) self.info() Qd.CopyBits(self.pixmap, self.wid.GetWindowPort().portBits, self.pictrect, currect, QuickDraw.srcCopy, None)
def do_update(self, *args): pass currect = self.fitrect() print 'PICT:', self.pictrect print 'WIND:', currect print 'ARGS:', (self.pixmap, self.wid.GetWindowPort().portBits, self.pictrect, currect, QuickDraw.srcCopy+QuickDraw.ditherCopy, None) self.info() Qd.CopyBits(self.pixmap, self.wid.GetWindowPort().portBits, self.pictrect, currect, QuickDraw.srcCopy, None)
17,177
def runsource(self, source): "Extend base class method: Stuff the source in the line cache first" filename = self.stuffsource(source) self.more = 0 self.save_warnings_filters = warnings.filters[:] warnings.filterwarnings(action="error", category=SyntaxWarning) if isinstance(source, types.UnicodeType): import IOBinding try: source = source.encode(IOBinding.encoding) except UnicodeError: self.tkconsole.resetoutput() self.write("Unsupported characters in input") return try: # InteractiveInterpreter.runsource() calls its runcode() method, # which is overridden (see below) return InteractiveInterpreter.runsource(self, source, filename) finally: if self.save_warnings_filters is not None: warnings.filters[:] = self.save_warnings_filters self.save_warnings_filters = None
def runsource(self, source): "Extend base class method: Stuff the source in the line cache first" filename = self.stuffsource(source) self.more = 0 self.save_warnings_filters = warnings.filters[:] warnings.filterwarnings(action="error", category=SyntaxWarning) if isinstance(source, types.UnicodeType): import IOBinding try: source = source.encode(IOBinding.encoding) except UnicodeError: self.tkconsole.resetoutput() self.write("Unsupported characters in input\n") return try: # InteractiveInterpreter.runsource() calls its runcode() method, # which is overridden (see below) return InteractiveInterpreter.runsource(self, source, filename) finally: if self.save_warnings_filters is not None: warnings.filters[:] = self.save_warnings_filters self.save_warnings_filters = None
17,178
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: self.text.insert("insert", line.strip()) self.newline_and_indent_event(event) finally: self.text.see("insert") self.text.undo_block_stop()
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") prefix = self.text.get("insert linestart", "insert") if prefix.rstrip().endswith(':'): self.newline_and_indent_event(event) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: self.text.insert("insert", line.strip()) self.newline_and_indent_event(event) finally: self.text.see("insert") self.text.undo_block_stop()
17,179
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: self.text.insert("insert", line.strip()) self.newline_and_indent_event(event) finally: self.text.see("insert") self.text.undo_block_stop()
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) prefix = self.text.get("insert linestart", "insert") self.text.insert("insert", lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: self.text.insert("insert", line.strip()) self.newline_and_indent_event(event) finally: self.text.see("insert") self.text.undo_block_stop()
17,180
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: self.text.insert("insert", line.strip()) self.newline_and_indent_event(event) finally: self.text.see("insert") self.text.undo_block_stop()
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0) new_base_indent = re.search(r'^([ \t]*)', prefix).group(0) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0) new_base_indent = re.search(r'^([ \t]*)', prefix).group(0) for line in lines[1:]: self.text.insert("insert", line.strip()) orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0) new_base_indent = re.search(r'^([ \t]*)', prefix).group(0) finally: self.text.see("insert") self.text.undo_block_stop()
17,181
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: self.text.insert("insert", line.strip()) self.newline_and_indent_event(event) finally: self.text.see("insert") self.text.undo_block_stop()
def recall(self, s, event): self.text.undo_block_start() try: self.text.tag_remove("sel", "1.0", "end") self.text.mark_set("insert", "end-1c") s = s.strip() lines = s.split('\n') prefix = self.text.get("insert linestart","insert").rstrip() if prefix and prefix[-1]==':': self.newline_and_indent_event(event) self.text.insert("insert",lines[0].strip()) if len(lines) > 1: self.newline_and_indent_event(event) for line in lines[1:]: if line.startswith(orig_base_indent): line = new_base_indent + line[len(orig_base_indent):] self.text.insert('insert', '\n'+line.rstrip()) finally: self.text.see("insert") self.text.undo_block_stop()
17,182
def __init__(self, root=None, font=None, name=None, exists=False, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name
def __init__(self, root=None, font=None, name=None, exists=False, **options): if not root: root = Tkinter._default_root if font: # get actual settings corresponding to the given font font = root.tk.splitlist(root.tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(id(self)) self.name = name
17,183
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
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[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
17,184
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[pos:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
17,185
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) pos = res.end(0) return newline + line[pos:]
17,186
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: res = mime_head.search(line) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' pos = 0 while 1: res = mime_head.search(line, pos) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
17,187
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: res = mime_head.search(line) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: res = mime_head.search(line) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[pos:res.start(0)] + mime_decode(match) pos = res.end(0) return newline + line[pos:]
17,188
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 = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: res = reg.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line 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
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 = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line 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
17,189
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 = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: res = reg.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line 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
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 = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: res = reg.search(line) if res is None: break newline = newline + line[pos:res.start(0)] + \ string.upper('=%02x' % ord(res.group(0))) 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
17,190
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
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 = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
17,191
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = '%s%s%s=?%s?Q?%s?=%s' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1), res.group(3)) pos = res.end(0) return newline + line[pos:]
17,192
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 string.lower(chrset_res.group(2)) == 'us-ascii': line = chrset_res.group(1) + \ CHARSET + chrset_res.group(3) else: # change iso-8859-* into us-ascii line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(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 ofile.write(line) continue
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 string.lower(chrset_res.group(2)) == 'us-ascii': line = '%s%s%s' % (chrset_res.group(1), CHARSET, chrset_res.group(3)) else: # change iso-8859-* into us-ascii line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(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 ofile.write(line) continue
17,193
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 string.lower(chrset_res.group(2)) == 'us-ascii': line = chrset_res.group(1) + \ CHARSET + chrset_res.group(3) else: # change iso-8859-* into us-ascii line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(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 ofile.write(line) continue
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 string.lower(chrset_res.group(2)) == 'us-ascii': line = 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 ofile.write(line) continue
17,194
def _getParser(): return ExpatParser()
def _getParser(): return xml.sax.make_parser()
17,195
def dynamics(): if verbose: print "Testing __dynamic__..." verify(object.__dynamic__ == 0) verify(list.__dynamic__ == 0) class S1: __metaclass__ = type verify(S1.__dynamic__ == 0) class S(object): pass verify(S.__dynamic__ == 0) class D(object): __dynamic__ = 1 verify(D.__dynamic__ == 1) class E(D, S): pass verify(E.__dynamic__ == 1) class F(S, D): pass verify(F.__dynamic__ == 1) try: S.foo = 1 except (AttributeError, TypeError): pass else: verify(0, "assignment to a static class attribute should be illegal") D.foo = 1 verify(D.foo == 1) # Test that dynamic attributes are inherited verify(E.foo == 1) verify(F.foo == 1) class SS(D): __dynamic__ = 0 verify(SS.__dynamic__ == 0) verify(SS.foo == 1) try: SS.foo = 1 except (AttributeError, TypeError): pass else: verify(0, "assignment to SS.foo should be illegal") # Test dynamic instances class C(object): __dynamic__ = 1 a = C() verify(not hasattr(a, "foobar")) C.foobar = 2 verify(a.foobar == 2) C.method = lambda self: 42 verify(a.method() == 42) C.__repr__ = lambda self: "C()" verify(repr(a) == "C()") C.__int__ = lambda self: 100 verify(int(a) == 100) verify(a.foobar == 2) verify(not hasattr(a, "spam")) def mygetattr(self, name): if name == "spam": return "spam" raise AttributeError C.__getattr__ = mygetattr verify(a.spam == "spam") a.new = 12 verify(a.new == 12) def mysetattr(self, name, value): if name == "spam": raise AttributeError return object.__setattr__(self, name, value) C.__setattr__ = mysetattr try: a.spam = "not spam" except AttributeError: pass else: verify(0, "expected AttributeError") verify(a.spam == "spam") class D(C): pass d = D() d.foo = 1 verify(d.foo == 1) # Test handling of int*seq and seq*int class I(int): __dynamic__ = 1 verify("a"*I(2) == "aa") verify(I(2)*"a" == "aa") verify(2*I(3) == 6) verify(I(3)*2 == 6) verify(I(3)*I(2) == 6) # Test handling of long*seq and seq*long class L(long): __dynamic__ = 1 verify("a"*L(2L) == "aa") verify(L(2L)*"a" == "aa") verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) # Test comparison of classes with dynamic metaclasses class dynamicmetaclass(type): __dynamic__ = 1 class someclass: __metaclass__ = dynamicmetaclass verify(someclass != object)
def dynamics(): if verbose: print "Testing __dynamic__..." verify(object.__dynamic__ == 0) verify(list.__dynamic__ == 0) class S1: __metaclass__ = type verify(S1.__dynamic__ == 0) class S(object): __dynamic__ = 0 verify(S.__dynamic__ == 0) class D(object): __dynamic__ = 1 verify(D.__dynamic__ == 1) class E(D, S): __dynamic__ = 0 verify(E.__dynamic__ == 1) class F(S, D): __dynamic__ = 0 verify(F.__dynamic__ == 1) try: S.foo = 1 except (AttributeError, TypeError): __dynamic__ = 0 else: verify(0, "assignment to a static class attribute should be illegal") D.foo = 1 verify(D.foo == 1) # Test that dynamic attributes are inherited verify(E.foo == 1) verify(F.foo == 1) class SS(D): __dynamic__ = 0 verify(SS.__dynamic__ == 0) verify(SS.foo == 1) try: SS.foo = 1 except (AttributeError, TypeError): __dynamic__ = 0 else: verify(0, "assignment to SS.foo should be illegal") # Test dynamic instances class C(object): __dynamic__ = 1 a = C() verify(not hasattr(a, "foobar")) C.foobar = 2 verify(a.foobar == 2) C.method = lambda self: 42 verify(a.method() == 42) C.__repr__ = lambda self: "C()" verify(repr(a) == "C()") C.__int__ = lambda self: 100 verify(int(a) == 100) verify(a.foobar == 2) verify(not hasattr(a, "spam")) def mygetattr(self, name): if name == "spam": return "spam" raise AttributeError C.__getattr__ = mygetattr verify(a.spam == "spam") a.new = 12 verify(a.new == 12) def mysetattr(self, name, value): if name == "spam": raise AttributeError return object.__setattr__(self, name, value) C.__setattr__ = mysetattr try: a.spam = "not spam" except AttributeError: __dynamic__ = 0 else: verify(0, "expected AttributeError") verify(a.spam == "spam") class D(C): __dynamic__ = 0 d = D() d.foo = 1 verify(d.foo == 1) # Test handling of int*seq and seq*int class I(int): __dynamic__ = 1 verify("a"*I(2) == "aa") verify(I(2)*"a" == "aa") verify(2*I(3) == 6) verify(I(3)*2 == 6) verify(I(3)*I(2) == 6) # Test handling of long*seq and seq*long class L(long): __dynamic__ = 1 verify("a"*L(2L) == "aa") verify(L(2L)*"a" == "aa") verify(2*L(3) == 6) verify(L(3)*2 == 6) verify(L(3)*L(2) == 6) # Test comparison of classes with dynamic metaclasses class dynamicmetaclass(type): __dynamic__ = 1 class someclass: __metaclass__ = dynamicmetaclass verify(someclass != object)
17,196
def rich_comparisons(): if verbose: print "Testing rich comparisons..." class Z(complex): pass z = Z(1) verify(z == 1+0j) verify(1+0j == z) class ZZ(complex): def __eq__(self, other): try: return abs(self - other) <= 1e-6 except: return NotImplemented zz = ZZ(1.0000003) verify(zz == 1+0j) verify(1+0j == zz) class classic: pass for base in (classic, int, object, list): if verbose: print " (base = %s)" % base class C(base): def __init__(self, value): self.value = int(value) def __cmp__(self, other): raise TestFailed, "shouldn't call __cmp__" def __eq__(self, other): if isinstance(other, C): return self.value == other.value if isinstance(other, int) or isinstance(other, long): return self.value == other return NotImplemented def __ne__(self, other): if isinstance(other, C): return self.value != other.value if isinstance(other, int) or isinstance(other, long): return self.value != other return NotImplemented def __lt__(self, other): if isinstance(other, C): return self.value < other.value if isinstance(other, int) or isinstance(other, long): return self.value < other return NotImplemented def __le__(self, other): if isinstance(other, C): return self.value <= other.value if isinstance(other, int) or isinstance(other, long): return self.value <= other return NotImplemented def __gt__(self, other): if isinstance(other, C): return self.value > other.value if isinstance(other, int) or isinstance(other, long): return self.value > other return NotImplemented def __ge__(self, other): if isinstance(other, C): return self.value >= other.value if isinstance(other, int) or isinstance(other, long): return self.value >= other return NotImplemented c1 = C(1) c2 = C(2) c3 = C(3) verify(c1 == 1) c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: for op in "<", "<=", "==", "!=", ">", ">=": verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("c[x] %s y" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y))
def rich_comparisons(): if verbose: print "Testing rich comparisons..." class Z(complex): __dynamic__ = 0 z = Z(1) verify(z == 1+0j) verify(1+0j == z) class ZZ(complex): def __eq__(self, other): try: return abs(self - other) <= 1e-6 except: return NotImplemented zz = ZZ(1.0000003) verify(zz == 1+0j) verify(1+0j == zz) class classic: __dynamic__ = 0 for base in (classic, int, object, list): if verbose: print " (base = %s)" % base class C(base): def __init__(self, value): self.value = int(value) def __cmp__(self, other): raise TestFailed, "shouldn't call __cmp__" def __eq__(self, other): if isinstance(other, C): return self.value == other.value if isinstance(other, int) or isinstance(other, long): return self.value == other return NotImplemented def __ne__(self, other): if isinstance(other, C): return self.value != other.value if isinstance(other, int) or isinstance(other, long): return self.value != other return NotImplemented def __lt__(self, other): if isinstance(other, C): return self.value < other.value if isinstance(other, int) or isinstance(other, long): return self.value < other return NotImplemented def __le__(self, other): if isinstance(other, C): return self.value <= other.value if isinstance(other, int) or isinstance(other, long): return self.value <= other return NotImplemented def __gt__(self, other): if isinstance(other, C): return self.value > other.value if isinstance(other, int) or isinstance(other, long): return self.value > other return NotImplemented def __ge__(self, other): if isinstance(other, C): return self.value >= other.value if isinstance(other, int) or isinstance(other, long): return self.value >= other return NotImplemented c1 = C(1) c2 = C(2) c3 = C(3) verify(c1 == 1) c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: for op in "<", "<=", "==", "!=", ">", ">=": verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("c[x] %s y" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) verify(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y))
17,197
def coercions(): if verbose: print "Testing coercions..." class I(int): pass coerce(I(0), 0) coerce(0, I(0)) class L(long): pass coerce(L(0), 0) coerce(L(0), 0L) coerce(0, L(0)) coerce(0L, L(0)) class F(float): pass coerce(F(0), 0) coerce(F(0), 0L) coerce(F(0), 0.) coerce(0, F(0)) coerce(0L, F(0)) coerce(0., F(0)) class C(complex): pass coerce(C(0), 0) coerce(C(0), 0L) coerce(C(0), 0.) coerce(C(0), 0j) coerce(0, C(0)) coerce(0L, C(0)) coerce(0., C(0)) coerce(0j, C(0))
def coercions(): if verbose: print "Testing coercions..." class I(int): pass coerce(I(0), 0) coerce(0, I(0)) class L(long): pass coerce(L(0), 0) coerce(L(0), 0L) coerce(0, L(0)) coerce(0L, L(0)) class F(float): pass coerce(F(0), 0) coerce(F(0), 0L) coerce(F(0), 0.) coerce(0, F(0)) coerce(0L, F(0)) coerce(0., F(0)) class C(complex): __dynamic__ = 0 coerce(C(0), 0) coerce(C(0), 0L) coerce(C(0), 0.) coerce(C(0), 0j) coerce(0, C(0)) coerce(0L, C(0)) coerce(0., C(0)) coerce(0j, C(0))
17,198
def feed(self, data, isFinal = 0): if not self._parsing: self._parsing = 1 self.reset() self._cont_handler.startDocument()
def feed(self, data, isFinal = 0): if not self._parsing: self._parsing = 1 self._cont_handler.startDocument()
17,199