rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size,
|
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
|
def write(self, filename, arcname=None, compress_type=None): """Put the bytes from filename into the archive under the name arcname.""" st = os.stat(filename) mtime = time.localtime(st.st_mtime) date_time = mtime[0:6] # Create ZipInfo instance to store file information if arcname is None: zinfo = ZipInfo(filename, date_time) else: zinfo = ZipInfo(arcname, date_time) zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes if compress_type is None: zinfo.compress_type = self.compression else: zinfo.compress_type = compress_type self._writecheck(zinfo) fp = open(filename, "rb") zinfo.flag_bits = 0x00 zinfo.header_offset = self.fp.tell() # Start of header bytes # Must overwrite CRC and sizes with correct data later zinfo.CRC = CRC = 0 zinfo.compress_size = compress_size = 0 zinfo.file_size = file_size = 0 self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes if zinfo.compress_type == ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None while 1: buf = fp.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = binascii.crc32(buf, CRC) if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) fp.close() if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size # Seek backwards and write CRC and file sizes position = self.fp.tell() # Preserve current position in file self.fp.seek(zinfo.header_offset + 14, 0) self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.fp.seek(position, 0) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
|
self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size,
|
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
|
def writestr(self, zinfo_or_arcname, bytes): """Write a file into the archive. The contents is the string 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or the name of the file in the archive.""" if not isinstance(zinfo_or_arcname, ZipInfo): zinfo = ZipInfo(filename=zinfo_or_arcname, date_time=time.localtime(time.time())) zinfo.compress_type = self.compression else: zinfo = zinfo_or_arcname self._writecheck(zinfo) zinfo.file_size = len(bytes) # Uncompressed size zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum if zinfo.compress_type == ZIP_DEFLATED: co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) bytes = co.compress(bytes) + co.flush() zinfo.compress_size = len(bytes) # Compressed size else: zinfo.compress_size = zinfo.file_size zinfo.header_offset = self.fp.tell() # Start of header bytes self.fp.write(zinfo.FileHeader()) zinfo.file_offset = self.fp.tell() # Start of file bytes self.fp.write(bytes) if zinfo.flag_bits & 0x08: # Write CRC and file sizes after the file data self.fp.write(struct.pack("<lll", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
|
incomment = ''
|
instr = '' brackets = 0
|
def checkline(self, filename, lineno): """Return line number of first line at or after input argument such that if the input points to a 'def', the returned line number is the first non-blank/non-comment line to follow. If the input points to a blank or comment line, return 0. At end of file, also return 0."""
|
if incomment: if len(line) < 3: continue if (line[-3:] == incomment): incomment = '' continue
|
def checkline(self, filename, lineno): """Return line number of first line at or after input argument such that if the input points to a 'def', the returned line number is the first non-blank/non-comment line to follow. If the input points to a blank or comment line, return 0. At end of file, also return 0."""
|
|
if len(line) >= 3: if (line[:3] == '"""' or line[:3] == "'''"): if line[-3:] == line[:3]: continue incomment = line[:3] continue if line[0] != '
|
if brackets <= 0 and line[0] not in (' break
|
def checkline(self, filename, lineno): """Return line number of first line at or after input argument such that if the input points to a 'def', the returned line number is the first non-blank/non-comment line to follow. If the input points to a blank or comment line, return 0. At end of file, also return 0."""
|
f.write("<title>Directory listing for %s</title>\n" % self.path) f.write("<h2>Directory listing for %s</h2>\n" % self.path)
|
displaypath = cgi.escape(urllib.unquote(self.path)) f.write("<title>Directory listing for %s</title>\n" % displaypath) f.write("<h2>Directory listing for %s</h2>\n" % displaypath)
|
def list_directory(self, path): """Helper to produce a directory listing (absent index.html).
|
print msg % args
|
if not args: print msg else: print msg % args
|
def _log(self, level, msg, args): if level >= self.threshold: print msg % args sys.stdout.flush()
|
key = (message, category, lineno)
|
if isinstance(message, Warning): text = str(message) category = message.__class__ else: text = message message = category(message) key = (text, category, lineno)
|
def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} key = (message, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if (msg.match(message) and issubclass(category, cat) and mod.match(module) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise category(message) # Other actions if action == "once": registry[key] = 1 oncekey = (message, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (message, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%s) in warnings.filters:\n %s" % (`action`, str(item))) # Print message and context showwarning(message, category, filename, lineno)
|
if (msg.match(message) and
|
if (msg.match(text) and
|
def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} key = (message, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if (msg.match(message) and issubclass(category, cat) and mod.match(module) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise category(message) # Other actions if action == "once": registry[key] = 1 oncekey = (message, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (message, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%s) in warnings.filters:\n %s" % (`action`, str(item))) # Print message and context showwarning(message, category, filename, lineno)
|
raise category(message)
|
raise message
|
def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} key = (message, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if (msg.match(message) and issubclass(category, cat) and mod.match(module) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise category(message) # Other actions if action == "once": registry[key] = 1 oncekey = (message, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (message, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%s) in warnings.filters:\n %s" % (`action`, str(item))) # Print message and context showwarning(message, category, filename, lineno)
|
oncekey = (message, category)
|
oncekey = (text, category)
|
def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} key = (message, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if (msg.match(message) and issubclass(category, cat) and mod.match(module) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise category(message) # Other actions if action == "once": registry[key] = 1 oncekey = (message, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (message, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%s) in warnings.filters:\n %s" % (`action`, str(item))) # Print message and context showwarning(message, category, filename, lineno)
|
altkey = (message, category, 0)
|
altkey = (text, category, 0)
|
def warn_explicit(message, category, filename, lineno, module=None, registry=None): if module is None: module = filename if module[-3:].lower() == ".py": module = module[:-3] # XXX What about leading pathname? if registry is None: registry = {} key = (message, category, lineno) # Quick test for common case if registry.get(key): return # Search the filters for item in filters: action, msg, cat, mod, ln = item if (msg.match(message) and issubclass(category, cat) and mod.match(module) and (ln == 0 or lineno == ln)): break else: action = defaultaction # Early exit actions if action == "ignore": registry[key] = 1 return if action == "error": raise category(message) # Other actions if action == "once": registry[key] = 1 oncekey = (message, category) if onceregistry.get(oncekey): return onceregistry[oncekey] = 1 elif action == "always": pass elif action == "module": registry[key] = 1 altkey = (message, category, 0) if registry.get(altkey): return registry[altkey] = 1 elif action == "default": registry[key] = 1 else: # Unrecognized actions are errors raise RuntimeError( "Unrecognized action (%s) in warnings.filters:\n %s" % (`action`, str(item))) # Print message and context showwarning(message, category, filename, lineno)
|
exts.append( Extension('cPickle', ['cPickle.c']) )
|
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
|
|
def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2))
|
trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)]) trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])
|
def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2))
|
ipad = "\x36" * blocksize opad = "\x5C" * blocksize
|
def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object.
|
|
self.outer.update(_strxor(key, opad)) self.inner.update(_strxor(key, ipad))
|
self.outer.update(key.translate(trans_5C)) self.inner.update(key.translate(trans_36))
|
def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object.
|
use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency.
|
use_statcache -- obsolete argument.
|
def cmp(f1, f2, shallow=1, use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency. Return value: True if the files are the same, False otherwise. This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale. """ if use_statcache: stat_function = statcache.stat else: stat_function = os.stat s1 = _sig(stat_function(f1)) s2 = _sig(stat_function(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return False if shallow and s1 == s2: return True if s1[1] != s2[1]: return False result = _cache.get((f1, f2)) if result and (s1, s2) == result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome
|
Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale.
|
def cmp(f1, f2, shallow=1, use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency. Return value: True if the files are the same, False otherwise. This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale. """ if use_statcache: stat_function = statcache.stat else: stat_function = os.stat s1 = _sig(stat_function(f1)) s2 = _sig(stat_function(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return False if shallow and s1 == s2: return True if s1[1] != s2[1]: return False result = _cache.get((f1, f2)) if result and (s1, s2) == result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome
|
|
if use_statcache: stat_function = statcache.stat else: stat_function = os.stat s1 = _sig(stat_function(f1)) s2 = _sig(stat_function(f2))
|
s1 = _sig(os.stat(f1)) s2 = _sig(os.stat(f2))
|
def cmp(f1, f2, shallow=1, use_statcache=0): """Compare two files. Arguments: f1 -- First file name f2 -- Second file name shallow -- Just check stat signature (do not read the files). defaults to 1. use_statcache -- Do not stat() each file directly: go through the statcache module for more efficiency. Return value: True if the files are the same, False otherwise. This function uses a cache for past comparisons and the results, with a cache invalidation mechanism relying on stale signatures. Of course, if 'use_statcache' is true, this mechanism is defeated, and the cache will never grow stale. """ if use_statcache: stat_function = statcache.stat else: stat_function = os.stat s1 = _sig(stat_function(f1)) s2 = _sig(stat_function(f2)) if s1[0] != stat.S_IFREG or s2[0] != stat.S_IFREG: return False if shallow and s1 == s2: return True if s1[1] != s2[1]: return False result = _cache.get((f1, f2)) if result and (s1, s2) == result[:2]: return result[2] outcome = _do_cmp(f1, f2) _cache[f1, f2] = s1, s2, outcome return outcome
|
a_stat = statcache.stat(a_path)
|
a_stat = os.stat(a_path)
|
def phase2(self): # Distinguish files, directories, funnies self.common_dirs = [] self.common_files = [] self.common_funny = []
|
b_stat = statcache.stat(b_path)
|
b_stat = os.stat(b_path)
|
def phase2(self): # Distinguish files, directories, funnies self.common_dirs = [] self.common_files = [] self.common_funny = []
|
use_statcache -- if true, use statcache.stat() instead of os.stat()
|
use_statcache -- obsolete argument
|
def cmpfiles(a, b, common, shallow=1, use_statcache=0): """Compare common files in two directories. a, b -- directory names common -- list of file names found in both directories shallow -- if true, do comparison based solely on stat() information use_statcache -- if true, use statcache.stat() instead of os.stat() Returns a tuple of three lists: files that compare equal files that are different filenames that aren't regular files. """ res = ([], [], []) for x in common: ax = os.path.join(a, x) bx = os.path.join(b, x) res[_cmp(ax, bx, shallow, use_statcache)].append(x) return res
|
res[_cmp(ax, bx, shallow, use_statcache)].append(x)
|
res[_cmp(ax, bx, shallow)].append(x)
|
def cmpfiles(a, b, common, shallow=1, use_statcache=0): """Compare common files in two directories. a, b -- directory names common -- list of file names found in both directories shallow -- if true, do comparison based solely on stat() information use_statcache -- if true, use statcache.stat() instead of os.stat() Returns a tuple of three lists: files that compare equal files that are different filenames that aren't regular files. """ res = ([], [], []) for x in common: ax = os.path.join(a, x) bx = os.path.join(b, x) res[_cmp(ax, bx, shallow, use_statcache)].append(x) return res
|
def _cmp(a, b, sh, st):
|
def _cmp(a, b, sh):
|
def _cmp(a, b, sh, st): try: return not abs(cmp(a, b, sh, st)) except os.error: return 2
|
return not abs(cmp(a, b, sh, st))
|
return not abs(cmp(a, b, sh))
|
def _cmp(a, b, sh, st): try: return not abs(cmp(a, b, sh, st)) except os.error: return 2
|
print '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
|
print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
|
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)
|
if (not rframe is frame) and rcur:
|
if (rframe is frame) and rcur:
|
def trace_dispatch_exception(self, frame, t): rt, rtt, rct, rfn, rframe, rcur = self.cur if (not rframe is frame) and rcur: return self.trace_dispatch_return(rframe, t) return 0
|
def newgroups(self, date, time):
|
def newgroups(self, date, time, file=None):
|
def newgroups(self, date, time): """Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names"""
|
return self.longcmd('NEWGROUPS ' + date + ' ' + time) def newnews(self, group, date, time):
|
return self.longcmd('NEWGROUPS ' + date + ' ' + time, file) def newnews(self, group, date, time, file=None):
|
def newgroups(self, date, time): """Process a NEWGROUPS command. Arguments: - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of newsgroup names"""
|
return self.longcmd(cmd) def list(self):
|
return self.longcmd(cmd, file) def list(self, file=None):
|
def newnews(self, group, date, time): """Process a NEWNEWS command. Arguments: - group: group name or '*' - date: string 'yymmdd' indicating the date - time: string 'hhmmss' indicating the time Return: - resp: server response if successful - list: list of article ids"""
|
resp, list = self.longcmd('LIST')
|
resp, list = self.longcmd('LIST', file)
|
def list(self): """Process a LIST command. Return: - resp: server response if successful - list: list of (group, last, first, flag) (strings)"""
|
def help(self):
|
def help(self, file=None):
|
def help(self): """Process a HELP command. Returns: - resp: server response if successful - list: list of strings"""
|
return self.longcmd('HELP')
|
return self.longcmd('HELP',file)
|
def help(self): """Process a HELP command. Returns: - resp: server response if successful - list: list of strings"""
|
def xhdr(self, hdr, str):
|
def xhdr(self, hdr, str, file=None):
|
def xhdr(self, hdr, str): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings"""
|
resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str)
|
resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file)
|
def xhdr(self, hdr, str): """Process an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 Returns: - resp: server response if successful - list: list of (nr, value) strings"""
|
def xover(self,start,end):
|
def xover(self, start, end, file=None):
|
def xover(self,start,end): """Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range Returns: - resp: server response if successful - list: list of (art-nr, subject, poster, date, id, references, size, lines)"""
|
resp, lines = self.longcmd('XOVER ' + start + '-' + end)
|
resp, lines = self.longcmd('XOVER ' + start + '-' + end, file)
|
def xover(self,start,end): """Process an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range Returns: - resp: server response if successful - list: list of (art-nr, subject, poster, date, id, references, size, lines)"""
|
def xgtitle(self, group):
|
def xgtitle(self, group, file=None):
|
def xgtitle(self, group): """Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings"""
|
resp, raw_lines = self.longcmd('XGTITLE ' + group)
|
resp, raw_lines = self.longcmd('XGTITLE ' + group, file)
|
def xgtitle(self, group): """Process an XGTITLE command (optional server extension) Arguments: - group: group name wildcard (i.e. news.*) Returns: - resp: server response if successful - list: list of (name,title) strings"""
|
if isinstance(s, StringType):
|
if isinstance(s, str):
|
def _is8bitstring(s): if isinstance(s, StringType): try: unicode(s, 'us-ascii') except UnicodeError: return True return False
|
self.__maxheaderlen = maxheaderlen
|
self._maxheaderlen = maxheaderlen
|
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): """Create the generator for message flattening.
|
return self.__class__(fp, self._mangle_from_, self.__maxheaderlen)
|
return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
|
def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, self.__maxheaderlen)
|
if self.__maxheaderlen == 0:
|
if self._maxheaderlen == 0:
|
def _write_headers(self, msg): for h, v in msg.items(): print >> self._fp, '%s:' % h, if self.__maxheaderlen == 0: # Explicit no-wrapping print >> self._fp, v elif isinstance(v, Header): # Header instances know what to do print >> self._fp, v.encode() elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. print >> self._fp, v else: # Header's got lots of smarts, so use it. print >> self._fp, Header( v, maxlinelen=self.__maxheaderlen, header_name=h, continuation_ws='\t').encode() # A blank line always separates headers from body print >> self._fp
|
v, maxlinelen=self.__maxheaderlen,
|
v, maxlinelen=self._maxheaderlen,
|
def _write_headers(self, msg): for h, v in msg.items(): print >> self._fp, '%s:' % h, if self.__maxheaderlen == 0: # Explicit no-wrapping print >> self._fp, v elif isinstance(v, Header): # Header instances know what to do print >> self._fp, v.encode() elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. print >> self._fp, v else: # Header's got lots of smarts, so use it. print >> self._fp, Header( v, maxlinelen=self.__maxheaderlen, header_name=h, continuation_ws='\t').encode() # A blank line always separates headers from body print >> self._fp
|
if not _isstring(payload):
|
if not isinstance(payload, basestring):
|
def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return cset = msg.get_charset() if cset is not None: payload = cset.body_encode(payload) if not _isstring(payload): raise TypeError, 'string payload expected: %s' % type(payload) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload)
|
boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts):
|
subparts = [] elif isinstance(subparts, basestring):
|
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
|
elif not isinstance(subparts, ListType):
|
elif not isinstance(subparts, list):
|
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
|
self._fp.write(msg.preamble) plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n')
|
print >> self._fp, msg.preamble
|
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
|
joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--',
|
if msgtexts: self._fp.write(msgtexts.pop(0)) for body_part in msgtexts: print >> self._fp, '\n--' + boundary self._fp.write(body_part) self._fp.write('\n--' + boundary + '--')
|
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
|
if not msg.epilogue.startswith('\n'): print >> self._fp
|
print >> self._fp
|
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
|
SyntaxError: assignment to generator expression not possible (<doctest test.test_genexps.__test__.doctests[38]>, line 1)
|
SyntaxError: assignment to generator expression not possible (<doctest test.test_genexps.__test__.doctests[40]>, line 1)
|
>>> def f(n):
|
SyntaxError: augmented assignment to generator expression not possible (<doctest test.test_genexps.__test__.doctests[39]>, line 1)
|
SyntaxError: augmented assignment to generator expression not possible (<doctest test.test_genexps.__test__.doctests[41]>, line 1)
|
>>> def f(n):
|
self._list.LCellSize((width, cellheight))
|
self._list.LCellSize((width/self._cols, cellheight))
|
def adjust(self, oldbounds): self.SetPort() # Appearance frames are drawn outside the specified bounds, # so we always need to outset the invalidated area. self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3))
|
Qd.MoveTo(left + 4, top + ascent)
|
Qd.MoveTo(int(left + 4), int(top + ascent))
|
def listDefDraw(self, selected, cellRect, theCell, dataOffset, dataLen, theList): savedPort = Qd.GetPort() Qd.SetPort(theList.GetListPort()) savedClip = Qd.NewRgn() Qd.GetClip(savedClip) Qd.ClipRect(cellRect) savedPenState = Qd.GetPenState() Qd.PenNormal() Qd.EraseRect(cellRect) #draw the cell if it contains data ascent, descent, leading, size, hm = Fm.FontMetrics() linefeed = ascent + descent + leading if dataLen: left, top, right, bottom = cellRect data = theList.LGetCell(dataLen, theCell) lines = data.split("\r") line1 = lines[0] if len(lines) > 1: line2 = lines[1] else: line2 = "" Qd.MoveTo(left + 4, top + ascent) Qd.DrawText(line1, 0, len(line1)) if line2: Qd.MoveTo(left + 4, top + ascent + linefeed) Qd.DrawText(line2, 0, len(line2)) Qd.PenPat("\x11\x11\x11\x11\x11\x11\x11\x11") bottom = top + theList.cellSize[1] Qd.MoveTo(left, bottom - 1) Qd.LineTo(right, bottom - 1) if selected: self.listDefHighlight(selected, cellRect, theCell, dataOffset, dataLen, theList) #restore graphics environment Qd.SetPort(savedPort) Qd.SetClip(savedClip) Qd.DisposeRgn(savedClip) Qd.SetPenState(savedPenState)
|
Qd.MoveTo(left + 4, top + ascent + linefeed)
|
Qd.MoveTo(int(left + 4), int(top + ascent + linefeed))
|
def listDefDraw(self, selected, cellRect, theCell, dataOffset, dataLen, theList): savedPort = Qd.GetPort() Qd.SetPort(theList.GetListPort()) savedClip = Qd.NewRgn() Qd.GetClip(savedClip) Qd.ClipRect(cellRect) savedPenState = Qd.GetPenState() Qd.PenNormal() Qd.EraseRect(cellRect) #draw the cell if it contains data ascent, descent, leading, size, hm = Fm.FontMetrics() linefeed = ascent + descent + leading if dataLen: left, top, right, bottom = cellRect data = theList.LGetCell(dataLen, theCell) lines = data.split("\r") line1 = lines[0] if len(lines) > 1: line2 = lines[1] else: line2 = "" Qd.MoveTo(left + 4, top + ascent) Qd.DrawText(line1, 0, len(line1)) if line2: Qd.MoveTo(left + 4, top + ascent + linefeed) Qd.DrawText(line2, 0, len(line2)) Qd.PenPat("\x11\x11\x11\x11\x11\x11\x11\x11") bottom = top + theList.cellSize[1] Qd.MoveTo(left, bottom - 1) Qd.LineTo(right, bottom - 1) if selected: self.listDefHighlight(selected, cellRect, theCell, dataOffset, dataLen, theList) #restore graphics environment Qd.SetPort(savedPort) Qd.SetClip(savedClip) Qd.DisposeRgn(savedClip) Qd.SetPenState(savedPenState)
|
if hasattr(os, 'utime'): past = time.time() - 3 os.utime(testfile, (past, past)) else: time.sleep(3)
|
def test(): raise ValueError""" # if this test runs fast, test_bug737473.py will have same mtime # even if it's rewrited and it'll not reloaded. so adjust mtime # of original to past. if hasattr(os, 'utime'): past = time.time() - 3 os.utime(testfile, (past, past)) else: time.sleep(3) if 'test_bug737473' in sys.modules: del sys.modules['test_bug737473'] import test_bug737473 try: test_bug737473.test() except ValueError: # this loads source code to linecache traceback.extract_tb(sys.exc_traceback) print >> open(testfile, 'w'), """\
|
|
vars = { 'base': self.install_base, 'platbase': self.install_platbase, 'py_version_short': sys.version[0:3], }
|
def select_scheme (self, name):
|
|
val = subst_vars (scheme[key], vars) setattr (self, 'install_' + key, val)
|
setattr (self, 'install_' + key, scheme[key]) def _expand_attrs (self, attrs): for attr in attrs: val = getattr (self, attr) if val is not None: if os.name == 'posix': val = os.path.expanduser (val) val = subst_vars (val, self.config_vars) setattr (self, attr, val) def expand_basedirs (self): self._expand_attrs (['install_base', 'install_platbase'])
|
def select_scheme (self, name):
|
for att in ('base', 'platbase', 'purelib', 'platlib', 'lib', 'scripts', 'data'): fullname = "install_" + att val = getattr (self, fullname) if val is not None: setattr (self, fullname, os.path.expandvars (os.path.expanduser (val)))
|
self._expand_attrs (['install_purelib', 'install_platlib', 'install_lib', 'install_scripts', 'install_data',])
|
def expand_dirs (self):
|
return HEAD % self.variables
|
s = HEAD % self.variables if self.uplink: if self.uptitle: link = ('<link rel="up" href="%s" title="%s">' % (self.uplink, self.uptitle)) else: link = '<link rel="up" href="%s">' % self.uplink repl = " %s\n</head>" % link s = s.replace("</head>", repl, 1) return s
|
def get_header(self): return HEAD % self.variables
|
df.Creator, df.Type, df.Flags = sf.Creator, sf.Type, sf.Flags
|
df.Creator, df.Type = sf.Creator, sf.Type df.Flags = (sf.Flags & (kIsStationary|kNameLocked|kHasBundle|kIsInvisible|kIsAlias))
|
def copy(src, dst, createpath=0): """Copy a file, including finder info, resource fork, etc""" if createpath: mkdirs(os.path.split(dst)[0]) srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) ifp = open(srcfss.as_pathname(), 'rb') ofp = open(dstfss.as_pathname(), 'wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() ifp = open(srcfss.as_pathname(), '*rb') ofp = open(dstfss.as_pathname(), '*wb') d = ifp.read(BUFSIZ) while d: ofp.write(d) d = ifp.read(BUFSIZ) ifp.close() ofp.close() sf = srcfss.GetFInfo() df = dstfss.GetFInfo() df.Creator, df.Type, df.Flags = sf.Creator, sf.Type, sf.Flags dstfss.SetFInfo(df)
|
return PyShellEditorWindow.close(self)
|
return OutputWindow.close(self)
|
def close(self): # Extend base class method if self.executing: # XXX Need to ask a question here if not tkMessageBox.askokcancel( "Kill?", "The program is still running; do you want to kill it?", default="ok", master=self.text): return "cancel" self.canceled = 1 if self.reading: self.top.quit() return "cancel" return PyShellEditorWindow.close(self)
|
self.do_disassembly_test(bug1333982, dis_bug1333982)
|
if __debug__: self.do_disassembly_test(bug1333982, dis_bug1333982)
|
def test_bug_1333982(self): self.do_disassembly_test(bug1333982, dis_bug1333982)
|
def set_get_returns_none(self, *args, **kwargs): return apply(self._cobj.set_get_returns_none, args, kwargs)
|
def set_get_returns_none(self, *args, **kwargs): return apply(self._cobj.set_get_returns_none, args, kwargs)
|
|
except ImportError:
|
termios.tcgetattr, termios.tcsetattr except (ImportError, AttributeError):
|
def getuser(): """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. """ import os for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os.environ.get(name) if user: return user # If this fails, the exception will "explain" why import pwd return pwd.getpwuid(os.getuid())[0]
|
self.top.wm_deiconify() self.top.tkraise()
|
def close(self): self.top.wm_deiconify() self.top.tkraise() reply = self.maybesave() if reply != "cancel": self._close() return reply
|
|
if self.will_close:
|
if self.length is None:
|
def read(self, amt=None): if self.fp is None: return ''
|
self.length -= amt
|
def read(self, amt=None): if self.fp is None: return ''
|
|
def get(self, key, default):
|
def get(self, key, default=None):
|
def get(self, key, default): try: ref = self.data[key] except KeyError: return default else: o = ref() if o is None: # This should only happen return default else: return o
|
L.append(key, ref(o, remove))
|
L.append((key, ref(o, remove)))
|
def remove(o, data=d, key=key): del data[key]
|
def get(self, key, default):
|
def get(self, key, default=None):
|
def get(self, key, default): return self.data.get(ref(key),default)
|
L.append(ref(key, self._remove), value)
|
L.append((ref(key, self._remove), value))
|
def update(self, dict): d = self.data L = [] for key, value in dict.items(): L.append(ref(key, self._remove), value) for key, r in L: d[key] = r
|
fp = open(name, '*rb')
|
fp = openrf(name, '*rb')
|
def getfileinfo(name):
|
def openrsrc(name, *mode): if mode: mode = mode[0]
|
def openrsrc(name, *mode): if not mode: mode = '*rb'
|
def getfileinfo(name):
|
mode = 'rb' mode = '*' + mode return open(name, mode)
|
mode = '*' + mode[0] return openrf(name, mode)
|
def openrsrc(name, *mode):
|
def write(self, data):
|
self.hqxdata = '' self.linelen = LINELEN-1 def write(self, data):
|
def __init__(self, ofp):
|
while len(self.data) > LINELEN: hqxdata = binascii.b2a_hqx(self.data[:LINELEN]) self.ofp.write(hqxdata+'\n') self.data = self.data[LINELEN:] def close(self):
|
datalen = len(self.data) todo = (datalen/3)*3 data = self.data[:todo] self.data = self.data[todo:] self.hqxdata = self.hqxdata + binascii.b2a_hqx(data) while len(self.hqxdata) > self.linelen: self.ofp.write(self.hqxdata[:self.linelen]+'\n') self.hqxdata = self.hqxdata[self.linelen:] self.linelen = LINELEN def close(self):
|
def write(self, data):
|
self.ofp.write(binascii.b2a_hqx(self.data))
|
self.hqxdata = self.hqxdata + binascii.b2a_hqx(self.data) while self.hqxdata: self.ofp.write(self.hqxdata[:self.linelen]) self.hqxdata = self.hqxdata[self.linelen:] self.linelen = LINELEN
|
def close(self):
|
def write(self, data): if DEBUG: testf.write(data)
|
def write(self, data):
|
def write(self, data):
|
def __init__(self, (name, finfo, dlen, rlen), ofp): if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') if os.name == 'mac': fss = macfs.FSSpec(ofname) fss.SetCreatorType('BnHq', 'TEXT') ofp.write('(This file may be decompressed with BinHex 4.0)\n\n:')
|
def __init__(self, (name, finfo, dlen, rlen), ofp): if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') if os.name == 'mac': fss = macfs.FSSpec(ofname) fss.SetCreatorType('BnHq', 'TEXT') ofp.write('(This file must be converted with BinHex 4.0)\n\n:')
|
def __init__(self, (name, finfo, dlen, rlen), ofp): if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') if os.name == 'mac': fss = macfs.FSSpec(ofname) fss.SetCreatorType('BnHq', 'TEXT')
|
def _writeinfo(self, name, finfo): if DEBUG: print 'binhex info:', name, finfo.Type, finfo.Creator, self.dlen, self.rlen
|
def _writeinfo(self, name, finfo):
|
def _writeinfo(self, name, finfo):
|
d = ifp.read() ofp.write(d)
|
while 1: d = ifp.read(128000) if not d: break ofp.write(d)
|
def binhex(inp, out): """(infilename, outfilename) - Create binhex-encoded copy of a file""" finfo = getfileinfo(inp) ofp = BinHex(finfo, out) ifp = open(inp, 'rb') # XXXX Do textfile translation on non-mac systems d = ifp.read() ofp.write(d) ofp.close_data() ifp.close() ifp = openrsrc(inp, 'rb') d = ifp.read() ofp.write_rsrc(d) ofp.close() ifp.close()
|
d = ifp.read() ofp.write_rsrc(d)
|
while 1: d = ifp.read(128000) if not d: break ofp.write_rsrc(d)
|
def binhex(inp, out): """(infilename, outfilename) - Create binhex-encoded copy of a file""" finfo = getfileinfo(inp) ofp = BinHex(finfo, out) ifp = open(inp, 'rb') # XXXX Do textfile translation on non-mac systems d = ifp.read() ofp.write(d) ofp.close_data() ifp.close() ifp = openrsrc(inp, 'rb') d = ifp.read() ofp.write_rsrc(d) ofp.close() ifp.close()
|
print 'WTD', wtd, 'GOT', len(rv)
|
def read(self, wtd):
|
|
if DEBUG: print 'SKIP:', ch+dummy
|
def __init__(self, ifp):
|
|
if DEBUG: print 'DBG CRC %x %x'%(self.crc, filecrc)
|
def _checkcrc(self):
|
|
if DEBUG: print 'DATA, RLEN', self.dlen, self.rlen
|
def _readheader(self):
|
|
d = ifp.read() ofp.write(d)
|
while 1: d = ifp.read(128000) if not d: break ofp.write(d)
|
def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = macfs.FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems d = ifp.read() ofp.write(d) ofp.close() ifp.close_data() d = ifp.read_rsrc() if d: ofp = openrsrc(out, 'wb') ofp.write(d) ofp.close() if os.name == 'mac': nfinfo = ofss.GetFInfo() nfinfo.Creator = finfo.Creator nfinfo.Type = finfo.Type nfinfo.Flags = finfo.Flags ofss.SetFInfo(nfinfo) ifp.close()
|
d = ifp.read_rsrc()
|
d = ifp.read_rsrc(128000)
|
def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = macfs.FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems d = ifp.read() ofp.write(d) ofp.close() ifp.close_data() d = ifp.read_rsrc() if d: ofp = openrsrc(out, 'wb') ofp.write(d) ofp.close() if os.name == 'mac': nfinfo = ofss.GetFInfo() nfinfo.Creator = finfo.Creator nfinfo.Type = finfo.Type nfinfo.Flags = finfo.Flags ofss.SetFInfo(nfinfo) ifp.close()
|
self.name = name
|
self.name = os.path.abspath(name)
|
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ self.name = name
|
self.name = fileobj.name
|
self.name = os.path.abspath(fileobj.name)
|
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ self.name = name
|
pre = os.path.basename(pre)
|
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
|
|
tarname = pre + ext
|
tarname = os.path.basename(pre + ext)
|
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
|
if mode != "r": name = tarname
|
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
|
|
t = cls.taropen(tarname, mode, gzip.GzipFile(name, mode, compresslevel, fileobj)
|
t = cls.taropen(name, mode, gzip.GzipFile(tarname, mode, compresslevel, fileobj)
|
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'"
|
pre, ext = os.path.splitext(name) pre = os.path.basename(pre) if ext == ".tbz2": ext = ".tar" if ext == ".bz2": ext = "" tarname = pre + ext
|
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'."
|
|
t = cls.taropen(tarname, mode, bz2.BZ2File(name, mode, compresslevel=compresslevel))
|
t = cls.taropen(name, mode, bz2.BZ2File(name, mode, compresslevel=compresslevel))
|
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError, "mode must be 'r' or 'w'."
|
if self.name is not None \ and os.path.abspath(name) == os.path.abspath(self.name):
|
if self.name is not None and os.path.samefile(name, self.name):
|
def add(self, name, arcname=None, recursive=True): """Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.). If given, `arcname' specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting `recursive' to False. """ self._check("aw")
|
def tag_add(self, tagName, index1, index2=None):
|
def tag_add(self, tagName, index1, *args):
|
def tag_add(self, tagName, index1, index2=None): self.tk.call( self._w, 'tag', 'add', tagName, index1, index2)
|
self._w, 'tag', 'add', tagName, index1, index2)
|
(self._w, 'tag', 'add', tagName, index1) + args)
|
def tag_add(self, tagName, index1, index2=None): self.tk.call( self._w, 'tag', 'add', tagName, index1, index2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.