bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data.
def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data.
9,300
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.logRequests = logRequests
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1, allow_none=False): self.logRequests = logRequests
9,301
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.logRequests = logRequests
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=1): self.logRequests = logRequests
9,302
def __init__(self): SimpleXMLRPCDispatcher.__init__(self)
def __init__(self): SimpleXMLRPCDispatcher.__init__(self)
9,303
def setlocale(category, value=None): """ setlocale(integer,string=None) -> string. Activates/queries locale processing. """ if value is not None and value != 'C': raise Error, '_locale emulation only supports "C" locale' return 'C'
def setlocale(category, value=None): """ setlocale(integer,string=None) -> string. Activates/queries locale processing. """ if value not in (None, '', 'C'): raise Error, '_locale emulation only supports "C" locale' return 'C'
9,304
def parse229(resp, peer): '''Parse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] <> '229': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] <> resp[right - 1]: raise error_proto, resp parts = resp[left+1].split(resp[left + 1:right]) if len(parts) <> 5: raise error_proto, resp host = peer[0] port = int(parts[3]) return host, port
def parse229(resp, peer): '''Parse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.''' if resp[:3] <> '229': raise error_reply, resp left = resp.find('(') if left < 0: raise error_proto, resp right = resp.find(')', left + 1) if right < 0: raise error_proto, resp # should contain '(|||port|)' if resp[left + 1] <> resp[right - 1]: raise error_proto, resp parts = resp[left + 1:right].split(resp[left+1]) if len(parts) <> 5: raise error_proto, resp host = peer[0] port = int(parts[3]) return host, port
9,305
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
9,306
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): raise ValueError, "CRC check failed" elif isize != self.size: raise ValueError, "Incorrect length of data produced"
def _read_eof(self): # We've read to the end of the file, so we have to rewind in order # to reread the 8 bytes containing the CRC and the file size. # We check the that the computed CRC and size of the # uncompressed data matches the stored values. self.fileobj.seek(-8, 1) crc32 = read32(self.fileobj) isize = U32(read32(self.fileobj)) # may exceed 2GB if U32(crc32) != U32(self.crc): raise ValueError, "CRC check failed" elif isize != LOWU32(self.size): raise ValueError, "Incorrect length of data produced"
9,307
def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) write32(self.fileobj, self.crc) # self.size may exceed 2GB write32u(self.fileobj, self.size) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None
def close(self): if self.mode == WRITE: self.fileobj.write(self.compress.flush()) write32(self.fileobj, self.crc) # self.size may exceed 2GB write32u(self.fileobj, LOWU32(self.size)) self.fileobj = None elif self.mode == READ: self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None
9,308
def getopt(args, shortopts, longopts = []): """getopt(args, options[, long_options]) -> opts, args Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means "sys.argv[1:]". shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (i.e., the same format that Unix getopt() uses). If specified, longopts is a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Options which require an argument should be followed by an equal sign ('='). The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of the first argument). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen (e.g., '-x'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed. """ opts = [] if type(longopts) == type(""): longopts = [longopts] else: longopts = list(longopts) longopts.sort() while args and args[0][:1] == '-' and args[0] != '-': if args[0] == '--': args = args[1:] break if args[0][:2] == '--': opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) else: opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) return opts, args
def getopt(args, shortopts, longopts = []): """getopt(args, options[, long_options]) -> opts, args Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means "sys.argv[1:]". shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (i.e., the same format that Unix getopt() uses). If specified, longopts is a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Options which require an argument should be followed by an equal sign ('='). The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of the first argument). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen (e.g., '-x'), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed. """ opts = [] if type(longopts) == type(""): longopts = [longopts] else: longopts = list(longopts) longopts.sort() while args and args[0].startswith('-') and args[0] != '-': if args[0] == '--': args = args[1:] break if args[0][:2] == '--': opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) else: opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) return opts, args
9,309
def do_longs(opts, opt, longopts, args): try: i = opt.index('=') opt, optarg = opt[:i], opt[i+1:] except ValueError: optarg = None has_arg, opt = long_has_args(opt, longopts) if has_arg: if optarg is None: if not args: raise GetoptError('option --%s requires argument' % opt, opt) optarg, args = args[0], args[1:] elif optarg: raise GetoptError('option --%s must not have an argument' % opt, opt) opts.append(('--' + opt, optarg or '')) return opts, args
def do_longs(opts, opt, longopts, args): try: i = opt.index('=') except ValueError: optarg = None has_arg, opt = long_has_args(opt, longopts) if has_arg: if optarg is None: if not args: raise GetoptError('option --%s requires argument' % opt, opt) optarg, args = args[0], args[1:] elif optarg: raise GetoptError('option --%s must not have an argument' % opt, opt) opts.append(('--' + opt, optarg or '')) return opts, args
9,310
def long_has_args(opt, longopts): optlen = len(opt) for i in range(len(longopts)): x, y = longopts[i][:optlen], longopts[i][optlen:] if opt != x: continue if y != '' and y != '=' and i+1 < len(longopts): if opt == longopts[i+1][:optlen]: raise GetoptError('option --%s not a unique prefix' % opt, opt) if longopts[i][-1:] in ('=', ): return 1, longopts[i][:-1] return 0, longopts[i] raise GetoptError('option --%s not recognized' % opt, opt)
def long_has_args(opt, longopts): for i in range(len(longopts)): x, y = longopts[i][:optlen], longopts[i][optlen:] if opt != x: continue if y != '' and y != '=' and i+1 < len(longopts): if opt == longopts[i+1][:optlen]: raise GetoptError('option --%s not a unique prefix' % opt, opt) if longopts[i][-1:] in ('=', ): return 1, longopts[i][:-1] return 0, longopts[i] raise GetoptError('option --%s not recognized' % opt, opt)
9,311
def long_has_args(opt, longopts): optlen = len(opt) for i in range(len(longopts)): x, y = longopts[i][:optlen], longopts[i][optlen:] if opt != x: continue if y != '' and y != '=' and i+1 < len(longopts): if opt == longopts[i+1][:optlen]: raise GetoptError('option --%s not a unique prefix' % opt, opt) if longopts[i][-1:] in ('=', ): return 1, longopts[i][:-1] return 0, longopts[i] raise GetoptError('option --%s not recognized' % opt, opt)
def long_has_args(opt, longopts): optlen = len(opt) for i in range(len(longopts)): if longopts[i].startswith(opt): break else: raise GetoptError('option --%s not recognized' % opt, opt) j = i+1 while j < len(longopts) and longopts[j].startswith(opt): j += 1 possibilities = longopts[i:j] if opt in possibilities: return 0, opt elif opt + '=' in possibilities: return 1, opt if len(possibilities) > 1: raise GetoptError('option --%s not a unique prefix' % opt, opt) assert len(possibilities) == 1 unique_match = possibilities[0] has_arg = unique_match.endswith('=') if has_arg: unique_match = unique_match[:-1] return has_arg, unique_match
9,312
def readline(self, size=None, keepends=True):
def readline(self, size=None, keepends=True):
9,313
def readline(self, size=None, keepends=True):
def readline(self, size=None, keepends=True):
9,314
def normalvariate(self, mu, sigma): """Normal distribution.
def normalvariate(self, mu, sigma): """Normal distribution.
9,315
def vonmisesvariate(self, mu, kappa): """Circular data distribution.
def vonmisesvariate(self, mu, kappa): """Circular data distribution.
9,316
def vonmisesvariate(self, mu, kappa): """Circular data distribution.
def vonmisesvariate(self, mu, kappa): """Circular data distribution.
9,317
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
9,318
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
9,319
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
9,320
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
defgammavariate(self,alpha,beta):"""Gammadistribution.Notthegammafunction!
9,321
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
def gammavariate(self, alpha, beta): """Gamma distribution. Not the gamma function!
9,322
def read(self, size): """Read 'size' bytes from remote.""" # sslobj.read() sometimes returns < size bytes data = self.sslobj.read(size) while len(data) < size: data += self.sslobj.read(len(data)-size)
def read(self, size): """Read 'size' bytes from remote.""" # sslobj.read() sometimes returns < size bytes data = self.sslobj.read(size) while len(data) < size: data += self.sslobj.read(len(data)-size)
9,323
def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT) self.assertEquals( compile_command(str, "<input>", symbol), expected)
def assertValid(self, str, symbol='single'): '''succeed iff str is a valid piece of code''' expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT) self.assertEquals( compile_command(str, "<input>", symbol), expected)
9,324
av("def x():\n pass\n")
av("def x():\n pass\n")
9,325
ai("def x():\n")
ai("def x():\n")
9,326
ai("def x():\n")
ai("def x():\n")
9,327
def normcase(s): res, s = splitdrive(s) for c in s: if c in '/\\': res = res + os.sep elif c == '.' and res[-1:] == os.sep: res = res + mapchar + c elif ord(c) < 32 or c in ' "*+,:;<=>?[]|': if res[-1:] != mapchar: res = res + mapchar else: res = res + c return string.lower(res)
def normcase(s): res, s = splitdrive(s) for c in s: if c in '/\\': res = res + os.sep elif c == '.' and res[-1:] == os.sep: res = res + mapchar + c elif ord(c) < 32 or c in ' ",:;<=>': if res[-1:] != mapchar: res = res + mapchar else: res = res + c return string.lower(res)
9,328
def redirect_request(self, req, fp, code, msg, headers): """Return a Request or None in response to a redirect.
def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect.
9,329
def redirect_request(self, req, fp, code, msg, headers): """Return a Request or None in response to a redirect.
def redirect_request(self, req, fp, code, msg, headers): """Return a Request or None in response to a redirect.
9,330
def http_error_302(self, req, fp, code, msg, headers): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
def http_error_302(self, req, fp, code, msg, headers): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
9,331
def test01_join(self): if verbose: print '\n', '-=' * 30 print "Running %s.test01_join..." % \ self.__class__.__name__
def test01_join(self): if verbose: print '\n', '-=' * 30 print "Running %s.test01_join..." % \ self.__class__.__name__
9,332
def test01_join(self): if verbose: print '\n', '-=' * 30 print "Running %s.test01_join..." % \ self.__class__.__name__
def test01_join(self): if verbose: print '\n', '-=' * 30 print "Running %s.test01_join..." % \ self.__class__.__name__
9,333
def reinitialize_command (self, command): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This gives provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real.
def reinitialize_command (self, command): """Reinitializes a command to the state it was in when first returned by 'get_command_obj()': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You'll have to re-finalize the command object (by calling 'finalize_options()' or 'ensure_finalized()') before using it for real.
9,334
def __init__(self, flist=None, filename=None, key=None, root=None): currentTheme=idleConf.CurrentTheme() self.flist = flist root = root or flist.root self.root = root self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) if flist: self.vars = flist.vars #self.top.instanceDict makes flist.inversedict avalable to #configDialog.py so it can access all EditorWindow instaces self.top.instanceDict=flist.inversedict self.recentFilesPath=os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') self.break_set = False self.vbar = vbar = Scrollbar(top, name='vbar') self.text_frame = text_frame = Frame(top) self.text = text = Text(text_frame, name='text', padx=5, wrap=None, foreground=idleConf.GetHighlight(currentTheme, 'normal',fgBg='fg'), background=idleConf.GetHighlight(currentTheme, 'normal',fgBg='bg'), highlightcolor=idleConf.GetHighlight(currentTheme, 'hilite',fgBg='fg'), highlightbackground=idleConf.GetHighlight(currentTheme, 'hilite',fgBg='bg'), insertbackground=idleConf.GetHighlight(currentTheme, 'cursor',fgBg='fg'), width=idleConf.GetOption('main','EditorWindow','width'), height=idleConf.GetOption('main','EditorWindow','height') )
def __init__(self, flist=None, filename=None, key=None, root=None): currentTheme=idleConf.CurrentTheme() self.flist = flist root = root or flist.root self.root = root self.menubar = Menu(root) self.top = top = self.Toplevel(root, menu=self.menubar) if flist: self.vars = flist.vars #self.top.instanceDict makes flist.inversedict avalable to #configDialog.py so it can access all EditorWindow instaces self.top.instanceDict=flist.inversedict self.recentFilesPath=os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') self.break_set = False self.vbar = vbar = Scrollbar(top, name='vbar') self.text_frame = text_frame = Frame(top) self.text = text = Text(text_frame, name='text', padx=5, wrap='none', foreground=idleConf.GetHighlight(currentTheme, 'normal',fgBg='fg'), background=idleConf.GetHighlight(currentTheme, 'normal',fgBg='bg'), highlightcolor=idleConf.GetHighlight(currentTheme, 'hilite',fgBg='fg'), highlightbackground=idleConf.GetHighlight(currentTheme, 'hilite',fgBg='bg'), insertbackground=idleConf.GetHighlight(currentTheme, 'cursor',fgBg='fg'), width=idleConf.GetOption('main','EditorWindow','width'), height=idleConf.GetOption('main','EditorWindow','height') )
9,335
def has_key(self, key): return self.data.has_key(ref(key))
def has_key(self, key): return self.data.has_key(ref(key))
9,336
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 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')
9,337
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 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')
9,338
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 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')
9,339
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 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')
9,340
def grid_location(self, x, y): """Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.""" return self._getints( self.tk.call( 'grid', 'location', self._w, x, y)) or None
def grid_location(self, x, y): """Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.""" return self._getints( self.tk.call( 'grid', 'location', self._w, x, y)) or None
9,341
def initcolormap(self): self.colormapinited = 1 self.color0 = None self.fixcolor0 = 0 if self.format in ('rgb', 'jpeg', 'compress'): self.set_rgbmode() gl.RGBcolor(200, 200, 200) # XXX rather light grey gl.clear() return # This only works on an Entry-level Indigo from IRIX 4.0.5 if self.format == 'rgb8' and is_entry_indigo() and \ gl.gversion() == 'GL4DLG-4.0.': # Note trailing '.'! gl.RGBmode() gl.gconfig() gl.RGBcolor(200, 200, 200) # XXX rather light grey gl.clear() gl.pixmode(GL.PM_SIZE, 8) return self.set_cmode() self.skipchrom = 0 if self.offset == 0: self.mask = 0x7ff else: self.mask = 0xfff if not self.quiet: sys.stderr.write('Initializing color map...') self._initcmap() gl.clear() if not self.quiet: sys.stderr.write(' Done.\n')
def initcolormap(self): self.colormapinited = 1 self.color0 = None self.fixcolor0 = 0 if self.format in ('rgb', 'jpeg', 'compress'): self.set_rgbmode() gl.RGBcolor(200, 200, 200) # XXX rather light grey gl.clear() return # This only works on an Entry-level Indigo from IRIX 4.0.5 if self.format == 'rgb8' and is_entry_indigo() and \ gl.gversion() == 'GL4DLG-4.0.': # Note trailing '.'! self.set_rgbmode() gl.RGBcolor(200, 200, 200) # XXX rather light grey gl.clear() gl.pixmode(GL.PM_SIZE, 8) return self.set_cmode() self.skipchrom = 0 if self.offset == 0: self.mask = 0x7ff else: self.mask = 0xfff if not self.quiet: sys.stderr.write('Initializing color map...') self._initcmap() gl.clear() if not self.quiet: sys.stderr.write(' Done.\n')
9,342
def _initcmap(self): if self.format in ('mono', 'grey4') and self.mustunpack: convcolor = conv_grey else: convcolor = choose_conversion(self.format) maxbits = gl.getgdesc(GL.GD_BITS_NORM_SNG_CMODE) if maxbits > 11: maxbits = 11 c0bits = self.c0bits c1bits = self.c1bits c2bits = self.c2bits if c0bits+c1bits+c2bits > maxbits: if self.fallback and c0bits < maxbits: # Cannot display frames in this mode, use grey self.skipchrom = 1 c1bits = c2bits = 0 convcolor = choose_conversion('grey') else: raise Error, 'Sorry, '+`maxbits`+ \ ' bits max on this machine' maxc0 = 1 << c0bits maxc1 = 1 << c1bits maxc2 = 1 << c2bits if self.offset == 0 and maxbits == 11: offset = 2048 else: offset = self.offset if maxbits <> 11: offset = offset & ((1<<maxbits)-1) self.color0 = None self.fixcolor0 = 0 for c0 in range(maxc0): c0v = c0/float(maxc0-1) for c1 in range(maxc1): if maxc1 == 1: c1v = 0 else: c1v = c1/float(maxc1-1) for c2 in range(maxc2): if maxc2 == 1: c2v = 0 else: c2v = c2/float(maxc2-1) index = offset + c0 + (c1<<c0bits) + \ (c2 << (c0bits+c1bits)) if index < MAXMAP: rv, gv, bv = \ convcolor(c0v, c1v, c2v) r, g, b = int(rv*255.0), \ int(gv*255.0), \ int(bv*255.0) gl.mapcolor(index, r, g, b) if self.color0 == None: self.color0 = \ index, r, g, b # Permanently make the first color index current gl.color(self.color0[0]) gl.gflush() # send the colormap changes to the X server
def _initcmap(self): if self.format in ('mono', 'grey4') and self.mustunpack: convcolor = conv_grey else: convcolor = choose_conversion(self.format) maxbits = gl.getgdesc(GL.GD_BITS_NORM_SNG_CMODE) if maxbits > 11: maxbits = 11 c0bits = self.c0bits c1bits = self.c1bits c2bits = self.c2bits if c0bits+c1bits+c2bits > maxbits: if self.fallback and c0bits < maxbits: # Cannot display frames in this mode, use grey self.skipchrom = 1 c1bits = c2bits = 0 convcolor = choose_conversion('grey') else: raise Error, 'Sorry, '+`maxbits`+ \ ' bits max on this machine' maxc0 = 1 << c0bits maxc1 = 1 << c1bits maxc2 = 1 << c2bits if self.offset == 0 and maxbits == 11: offset = 2048 else: offset = self.offset if maxbits <> 11: offset = offset & ((1<<maxbits)-1) self.color0 = None self.fixcolor0 = 0 for c0 in range(maxc0): c0v = c0/float(maxc0-1) for c1 in range(maxc1): if maxc1 == 1: c1v = 0 else: c1v = c1/float(maxc1-1) for c2 in range(maxc2): if maxc2 == 1: c2v = 0 else: c2v = c2/float(maxc2-1) index = offset + c0 + (c1<<c0bits) + \ (c2 << (c0bits+c1bits)) if index < MAXMAP: rv, gv, bv = \ convcolor(c0v, c1v, c2v) r, g, b = int(rv*255.0), \ int(gv*255.0), \ int(bv*255.0) map.append(index, r, g, b) if self.color0 == None: self.color0 = \ index, r, g, b # Permanently make the first color index current gl.color(self.color0[0]) gl.gflush() # send the colormap changes to the X server
9,343
def add_handler(self, handler): added = False for meth in dir(handler): i = meth.find("_") protocol = meth[:i] condition = meth[i+1:]
def add_handler(self, handler): added = False for meth in dir(handler): i = meth.find("_") protocol = meth[:i] condition = meth[i+1:]
9,344
def add_handler(self, handler): added = False for meth in dir(handler): i = meth.find("_") protocol = meth[:i] condition = meth[i+1:]
def add_handler(self, handler): added = False for meth in dir(handler): i = meth.find("_") protocol = meth[:i] condition = meth[i+1:]
9,345
def test(name, input, output): f = getattr(strop, name) try: value = f(input) except: value = sys.exc_type print sys.exc_value if value != output: print f, `input`, `output`, `value`
def test(name, input, output): f = getattr(strop, name) try: value = f(input) except: value = sys.exc_type if value != output: print f, `input`, `output`, `value`
9,346
def getresponse(self): "Get the response from the server."
def getresponse(self): "Get the response from the server."
9,347
def __init__(self): self.data = {}
def __init__(self): self.data = {}
9,348
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
9,349
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
9,350
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
defself.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) detect_tkinter(self,self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) inc_dirs,self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) lib_dirs):self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) #self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) Theself.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) _tkinterself.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2) module.
9,351
def end_blockquote(self): self.formatter.end_paragraph(0) self.formatter.pop_margin()
def end_blockquote(self): self.formatter.end_paragraph(1) self.formatter.pop_margin()
9,352
def start_dl(self, attrs): self.formatter.end_paragraph(0) self.list_stack.append(['dl', '', 0])
def start_dl(self, attrs): self.formatter.end_paragraph(1) self.list_stack.append(['dl', '', 0])
9,353
def end_dl(self): self.ddpop() if self.list_stack: del self.list_stack[-1]
def end_dl(self): self.ddpop(1) if self.list_stack: del self.list_stack[-1]
9,354
def ddpop(self): self.formatter.end_paragraph(0) if self.list_stack: if self.list_stack[-1][0] == 'dd':
def ddpop(self, bl=0): self.formatter.end_paragraph(bl) if self.list_stack: if self.list_stack[-1][0] == 'dd':
9,355
def start_string(self, attrs): self.start_b(attrs)
def start_string(self, attrs): self.start_b(attrs)
9,356
def end_var(self): self.end_var()
def end_var(self): self.end_var()
9,357
def _update(self, value): tp, h, bar_rect = self.d.GetDialogItem(3) Qd.SetPort(self.d) Qd.FrameRect(bar_rect) # Draw outline inner_rect = Qd.InsetRect(bar_rect, 1, 1) Qd.ForeColor(QuickDraw.whiteColor) Qd.BackColor(QuickDraw.whiteColor) Qd.PaintRect(inner_rect) # Clear internal l, t, r, b = inner_rect r = int(l + (r-l)*value/self.maxval) inner_rect = l, t, r, b Qd.ForeColor(QuickDraw.blackColor) Qd.BackColor(QuickDraw.blackColor) Qd.PaintRect(inner_rect) # Draw bar # Restore settings Qd.ForeColor(QuickDraw.blackColor) Qd.BackColor(QuickDraw.whiteColor) # Test for cancel button if ModalDialog(self._filterfunc) == 1: raise KeyboardInterrupt
def _update(self, value): tp, h, bar_rect = self.d.GetDialogItem(3) Qd.SetPort(self.d) Qd.FrameRect(bar_rect) # Draw outline inner_rect = Qd.InsetRect(bar_rect, 1, 1) Qd.ForeColor(QuickDraw.whiteColor) Qd.BackColor(QuickDraw.whiteColor) Qd.PaintRect(inner_rect) # Clear internal l, t, r, b = inner_rect r = int(l + (r-l)*value/self.maxval) inner_rect = l, t, r, b Qd.ForeColor(QuickDraw.blackColor) Qd.BackColor(QuickDraw.blackColor) Qd.PaintRect(inner_rect) # Draw bar # Restore settings Qd.ForeColor(QuickDraw.blackColor) Qd.BackColor(QuickDraw.whiteColor) # Test for cancel button if ModalDialog(_ProgressBar_filterfunc) == 1: raise KeyboardInterrupt
9,358
def _filterfunc(self, d, e, *more): return 2 # XXXX For now, this disables the cancel button
def _filterfunc(self, d, e, *more): return 2 # XXXX For now, this disables the cancel button
9,359
def set(self, value): if value < 0: value = 0 if value > self.maxval: value = self.maxval self._update(value)
def set(self, value): if value < 0: value = 0 if value > self.maxval: value = self.maxval self._update(value)
9,360
def test_codecs(self): # Encoding self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello')
def test_codecs(self): # Encoding self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello')
9,361
def test_codecs(self): # Encoding self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello')
def test_codecs(self): # Encoding self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello')
9,362
def test_codecs(self): # Encoding self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello')
def test_codecs(self): # Encoding self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello')
9,363
def __getitem__(self, item): if isinstance(item, int): if item < 0: item += self.len if not 0 <= item < self.len: raise IndexError, "out of range" return strftime(self.format, (item,)*8+(0,)).capitalize() elif isinstance(item, type(slice(0))): return [self[e] for e in range(self.len)].__getslice__(item.start, item.stop)
def __getitem__(self, item): if isinstance(item, int): if item < 0: item += self.len if not 0 <= item < self.len: raise IndexError, "out of range" t = (2001, 1, item+1, 12, 0, 0, item, item+1, 0) return strftime(self.format, t).capitalize() elif isinstance(item, type(slice(0))): return [self[e] for e in range(self.len)].__getslice__(item.start, item.stop)
9,364
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'de:hmo:p:P:qs:w') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + binlib] # sanity check of directories and files for dir in [prefix, exec_prefix, binlib, incldir] + extensions: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) if modargs: break # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) if odir: frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug) for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) mf.run_script(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules backup = frozen_c + '~' try: os.rename(frozen_c, backup) except os.error: backup = None outfp = open(frozen_c, 'w') try: makefreeze.makefreeze(outfp, dict, debug) if win and subsystem == 'windows': import winmakemakefile outfp.write(winmakemakefile.WINMAINTEMPLATE) finally: outfp.close() if backup: if cmp.cmp(backup, frozen_c): sys.stderr.write('%s not changed, not written\n' % frozen_c) os.unlink(frozen_c) os.rename(backup, frozen_c) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), [frozenmain_c, frozen_c], target) finally: outfp.close() return # generate config.c and Makefile builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) addfiles = [] if unknown: addfiles, addmods = \ checkextensions.checkextensions(unknown, extensions) for mod in addmods: unknown.remove(mod) builtins = builtins + addmods if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) builtins.sort() infp = open(config_c_in) backup = config_c + '~' try: os.rename(config_c, backup) except os.error: backup = None outfp = open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() if backup: if cmp.cmp(backup, config_c): sys.stderr.write('%s not changed, not written\n' % config_c) os.unlink(config_c) os.rename(backup, config_c) cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] backup = makefile + '~' if os.path.exists(makefile): try: os.unlink(backup) except os.error: pass try: os.rename(makefile, backup) except os.error: backup = None outfp = open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() if backup: if not cmp.cmp(backup, makefile): print 'previous Makefile saved as', backup else: sys.stderr.write('%s not changed, not written\n' % makefile) os.unlink(makefile) os.rename(backup, makefile) # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
def main(): # overridable context prefix = None # settable with -p option exec_prefix = None # settable with -P option extensions = [] path = sys.path[:] modargs = 0 debug = 1 odir = '' win = sys.platform[:3] == 'win' # modules that are imported by the Python runtime implicits = ["site", "exceptions"] # output files frozen_c = 'frozen.c' config_c = 'config.c' target = 'a.out' # normally derived from script name makefile = 'Makefile' subsystem = 'console' # parse command line try: opts, args = getopt.getopt(sys.argv[1:], 'de:hmo:p:P:qs:w') except getopt.error, msg: usage('getopt error: ' + str(msg)) # proces option arguments for o, a in opts: if o == '-h': print __doc__ return if o == '-d': debug = debug + 1 if o == '-e': extensions.append(a) if o == '-m': modargs = 1 if o == '-o': odir = a if o == '-p': prefix = a if o == '-P': exec_prefix = a if o == '-q': debug = 0 if o == '-w': win = not win if o == '-s': if not win: usage("-s subsystem option only on Windows") subsystem = a # default prefix and exec_prefix if not exec_prefix: if prefix: exec_prefix = prefix else: exec_prefix = sys.exec_prefix if not prefix: prefix = sys.prefix # determine whether -p points to the Python source tree ishome = os.path.exists(os.path.join(prefix, 'Python', 'ceval.c')) # locations derived from options version = sys.version[:3] if ishome: print "(Using Python source directory)" binlib = exec_prefix incldir = os.path.join(prefix, 'Include') config_c_in = os.path.join(prefix, 'Modules', 'config.c.in') frozenmain_c = os.path.join(prefix, 'Python', 'frozenmain.c') makefile_in = os.path.join(exec_prefix, 'Modules', 'Makefile') else: binlib = os.path.join(exec_prefix, 'lib', 'python%s' % version, 'config') incldir = os.path.join(prefix, 'include', 'python%s' % version) config_c_in = os.path.join(binlib, 'config.c.in') frozenmain_c = os.path.join(binlib, 'frozenmain.c') makefile_in = os.path.join(binlib, 'Makefile') supp_sources = [] defines = [] includes = ['-I' + incldir, '-I' + binlib] # sanity check of directories and files for dir in [prefix, exec_prefix, binlib, incldir] + extensions: if not os.path.exists(dir): usage('needed directory %s not found' % dir) if not os.path.isdir(dir): usage('%s: not a directory' % dir) if win: files = supp_sources else: files = [config_c_in, makefile_in] + supp_sources for file in supp_sources: if not os.path.exists(file): usage('needed file %s not found' % file) if not os.path.isfile(file): usage('%s: not a plain file' % file) if not win: for dir in extensions: setup = os.path.join(dir, 'Setup') if not os.path.exists(setup): usage('needed file %s not found' % setup) if not os.path.isfile(setup): usage('%s: not a plain file' % setup) # check that enough arguments are passed if not args: usage('at least one filename argument required') # check that file arguments exist for arg in args: if arg == '-m': break if not os.path.exists(arg): usage('argument %s not found' % arg) if not os.path.isfile(arg): usage('%s: not a plain file' % arg) if modargs: break # process non-option arguments scriptfile = args[0] modules = args[1:] # derive target name from script name base = os.path.basename(scriptfile) base, ext = os.path.splitext(base) if base: if base != scriptfile: target = base else: target = base + '.bin' # handle -o option base_frozen_c = frozen_c base_config_c = config_c base_target = target if odir and not os.path.isdir(odir): try: os.mkdir(odir) print "Created output directory", odir except os.error, msg: usage('%s: mkdir failed (%s)' % (odir, str(msg))) if odir: frozen_c = os.path.join(odir, frozen_c) config_c = os.path.join(odir, config_c) target = os.path.join(odir, target) makefile = os.path.join(odir, makefile) # Actual work starts here... # collect all modules of the program dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug) for mod in implicits: mf.import_hook(mod) for mod in modules: if mod == '-m': modargs = 1 continue if modargs: if mod[-2:] == '.*': mf.import_hook(mod[:-2], None, ["*"]) else: mf.import_hook(mod) else: mf.load_file(mod) mf.run_script(scriptfile) if debug > 0: mf.report() print dict = mf.modules # generate output for frozen modules backup = frozen_c + '~' try: os.rename(frozen_c, backup) except os.error: backup = None outfp = open(frozen_c, 'w') try: makefreeze.makefreeze(outfp, dict, debug) if win and subsystem == 'windows': import winmakemakefile outfp.write(winmakemakefile.WINMAINTEMPLATE) finally: outfp.close() if backup: if cmp.cmp(backup, frozen_c): sys.stderr.write('%s not changed, not written\n' % frozen_c) os.unlink(frozen_c) os.rename(backup, frozen_c) # windows gets different treatment if win: # Taking a shortcut here... import winmakemakefile outfp = open(makefile, 'w') try: winmakemakefile.makemakefile(outfp, locals(), [frozenmain_c, os.path.basename(frozen_c)], os.path.basename(target)) finally: outfp.close() return # generate config.c and Makefile builtins = [] unknown = [] mods = dict.keys() mods.sort() for mod in mods: if dict[mod].__code__: continue if not dict[mod].__file__: builtins.append(mod) else: unknown.append(mod) addfiles = [] if unknown: addfiles, addmods = \ checkextensions.checkextensions(unknown, extensions) for mod in addmods: unknown.remove(mod) builtins = builtins + addmods if unknown: sys.stderr.write('Warning: unknown modules remain: %s\n' % string.join(unknown)) builtins.sort() infp = open(config_c_in) backup = config_c + '~' try: os.rename(config_c, backup) except os.error: backup = None outfp = open(config_c, 'w') try: makeconfig.makeconfig(infp, outfp, builtins) finally: outfp.close() infp.close() if backup: if cmp.cmp(backup, config_c): sys.stderr.write('%s not changed, not written\n' % config_c) os.unlink(config_c) os.rename(backup, config_c) cflags = defines + includes + ['$(OPT)'] libs = [os.path.join(binlib, 'libpython$(VERSION).a')] somevars = {} if os.path.exists(makefile_in): makevars = parsesetup.getmakevars(makefile_in) for key in makevars.keys(): somevars[key] = makevars[key] somevars['CFLAGS'] = string.join(cflags) # override files = ['$(OPT)', '$(LDFLAGS)', base_config_c, base_frozen_c] + \ supp_sources + addfiles + libs + \ ['$(MODLIBS)', '$(LIBS)', '$(SYSLIBS)'] backup = makefile + '~' if os.path.exists(makefile): try: os.unlink(backup) except os.error: pass try: os.rename(makefile, backup) except os.error: backup = None outfp = open(makefile, 'w') try: makemakefile.makemakefile(outfp, somevars, files, base_target) finally: outfp.close() if backup: if not cmp.cmp(backup, makefile): print 'previous Makefile saved as', backup else: sys.stderr.write('%s not changed, not written\n' % makefile) os.unlink(makefile) os.rename(backup, makefile) # Done! if odir: print 'Now run "make" in', odir, print 'to build the target:', base_target else: print 'Now run "make" to build the target:', base_target
9,365
def needsquoting(c, quotetabs): """Decide whether a particular character needs to be quoted. The 'quotetabs' flag indicates whether tabs should be quoted.""" if c == '\t': return not quotetabs return c == ESCAPE or not(' ' <= c <= '~')
def needsquoting(c, quotetabs): """Decide whether a particular character needs to be quoted. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. """ if c in ' \t': return quotetabs return c == ESCAPE or not (' ' <= c <= '~')
9,366
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether embedded tabs and spaces should be quoted. Note that line-ending tabs and spaces are always encoded, as per RFC 1521. """ def write(s, output=output, lineEnd='\n'): if s and s[-1:] in ' \t': output.write(s[:-1] + quote(s[-1]) + lineEnd) else: output.write(s + lineEnd) prevline = None linelen = 0 while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
9,367
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break outline = [] stripped = '' if line[-1:] == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
9,368
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] stripped = '\n' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
9,369
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
def encode(input, output, quotetabs): """Read 'input', apply quoted-printable encoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. The 'quotetabs' flag indicates whether tabs should be quoted. """ while 1: line = input.readline() if not line: break new = '' last = line[-1:] if last == '\n': line = line[:-1] else: last = '' prev = '' for c in line: if needsquoting(c, quotetabs): c = quote(c) if len(new) + len(c) >= MAXLINESIZE: output.write(new + ESCAPE + '\n') new = '' new = new + c prev = c if prev in (' ', '\t'): output.write(new + ESCAPE + '\n\n') else: output.write(new + '\n')
9,370
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)
9,371
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)
9,372
def open_new(self, url): self.open(url)
def open_new(self, url): self.open(url)
9,373
def begin(self): if self.msg is not None: # we've already started reading the response return
def begin(self): if self.msg is not None: # we've already started reading the response return
9,374
def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect.
def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect.
9,375
def handle_read (self):
def handle_read (self):
9,376
def get_header(self): 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) if self.aesop_type: meta = '\n <meta name="aesop" content="%s">' # Insert this in the middle of the head that's been # generated so far, keeping <meta> and <link> elements in # neat groups: s = s.replace("<link ", meta + "<link ", 1) return s
def get_header(self): 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) if self.aesop_type: meta = '<meta name="aesop" content="%s">\n ' % self.aesop_type # Insert this in the middle of the head that's been # generated so far, keeping <meta> and <link> elements in # neat groups: s = s.replace("<link ", meta + "<link ", 1) return s
9,377
def makepath(*paths): dir = os.path.abspath(os.path.join(*paths)) return dir, os.path.normcase(dir)
def makepath(*paths): dir = os.path.abspath(os.path.join(*paths)) return dir, os.path.normcase(dir)
9,378
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name) or name == '': return if PATH_CREATED.get (name): return (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1
defcreated_dirs = [] mkpathcreated_dirs = [] (name,created_dirs = [] mode=0777,created_dirs = [] verbose=0,created_dirs = [] dry_run=0):created_dirs = [] """Createcreated_dirs = [] acreated_dirs = [] directorycreated_dirs = [] andcreated_dirs = [] anycreated_dirs = [] missingcreated_dirs = [] ancestorcreated_dirs = [] directories.created_dirs = [] created_dirs = [] Ifcreated_dirs = [] thecreated_dirs = [] directorycreated_dirs = [] alreadycreated_dirs = [] exists,created_dirs = [] returncreated_dirs = [] silently.created_dirs = [] created_dirs = [] Raisecreated_dirs = [] DistutilsFileErrorcreated_dirs = [] ifcreated_dirs = [] unablecreated_dirs = [] tocreated_dirs = [] createcreated_dirs = [] somecreated_dirs = [] directorycreated_dirs = [] alongcreated_dirs = [] thecreated_dirs = [] waycreated_dirs = [] (eg.created_dirs = [] somecreated_dirs = [] sub-pathcreated_dirs = [] exists,created_dirs = [] butcreated_dirs = [] iscreated_dirs = [] acreated_dirs = [] filecreated_dirs = [] rathercreated_dirs = [] thancreated_dirs = [] acreated_dirs = [] directory).created_dirs = [] created_dirs = [] Ifcreated_dirs = [] 'verbose'created_dirs = [] iscreated_dirs = [] true,created_dirs = [] printcreated_dirs = [] acreated_dirs = [] one-linecreated_dirs = [] summarycreated_dirs = [] ofcreated_dirs = [] eachcreated_dirs = [] mkdircreated_dirs = [] tocreated_dirs = [] stdout."""created_dirs = [] created_dirs = [] globalcreated_dirs = [] PATH_CREATEDcreated_dirs = [] created_dirs = [] #created_dirs = [] XXXcreated_dirs = [] what'screated_dirs = [] thecreated_dirs = [] bettercreated_dirs = [] waycreated_dirs = [] tocreated_dirs = [] handlecreated_dirs = [] verbosity?created_dirs = [] printcreated_dirs = [] ascreated_dirs = [] wecreated_dirs = [] createcreated_dirs = [] #created_dirs = [] eachcreated_dirs = [] directorycreated_dirs = [] increated_dirs = [] thecreated_dirs = [] pathcreated_dirs = [] (thecreated_dirs = [] currentcreated_dirs = [] behaviour),created_dirs = [] orcreated_dirs = [] onlycreated_dirs = [] announcecreated_dirs = [] #created_dirs = [] thecreated_dirs = [] creationcreated_dirs = [] ofcreated_dirs = [] thecreated_dirs = [] wholecreated_dirs = [] path?created_dirs = [] (quitecreated_dirs = [] easycreated_dirs = [] tocreated_dirs = [] docreated_dirs = [] thecreated_dirs = [] lattercreated_dirs = [] sincecreated_dirs = [] #created_dirs = [] we'recreated_dirs = [] notcreated_dirs = [] usingcreated_dirs = [] acreated_dirs = [] recursivecreated_dirs = [] algorithm)created_dirs = [] created_dirs = [] namecreated_dirs = [] =created_dirs = [] os.path.normpathcreated_dirs = [] (name)created_dirs = [] created_dirs = [] ifcreated_dirs = [] os.path.isdircreated_dirs = [] (name)created_dirs = [] orcreated_dirs = [] namecreated_dirs = [] ==created_dirs = [] '':created_dirs = [] returncreated_dirs = [] ifcreated_dirs = [] PATH_CREATED.getcreated_dirs = [] (name):created_dirs = [] returncreated_dirs = [] created_dirs = [] (head,created_dirs = [] tail)created_dirs = [] =created_dirs = [] os.path.splitcreated_dirs = [] (name)created_dirs = [] tailscreated_dirs = [] =created_dirs = [] [tail]created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] #created_dirs = [] stackcreated_dirs = [] ofcreated_dirs = [] lonecreated_dirs = [] dirscreated_dirs = [] tocreated_dirs = [] createcreated_dirs = [] created_dirs = [] whilecreated_dirs = [] headcreated_dirs = [] andcreated_dirs = [] tailcreated_dirs = [] andcreated_dirs = [] notcreated_dirs = [] os.path.isdircreated_dirs = [] (head):created_dirs = [] #printcreated_dirs = [] "splittingcreated_dirs = [] '%s':created_dirs = [] "created_dirs = [] %created_dirs = [] head,created_dirs = [] (head,created_dirs = [] tail)created_dirs = [] =created_dirs = [] os.path.splitcreated_dirs = [] (head)created_dirs = [] #printcreated_dirs = [] "tocreated_dirs = [] ('%s','%s')"created_dirs = [] %created_dirs = [] (head,created_dirs = [] tail)created_dirs = [] tails.insertcreated_dirs = [] (0,created_dirs = [] tail)created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] created_dirs = [] #created_dirs = [] pushcreated_dirs = [] nextcreated_dirs = [] highercreated_dirs = [] dircreated_dirs = [] ontocreated_dirs = [] stackcreated_dirs = [] created_dirs = [] #printcreated_dirs = [] "stackcreated_dirs = [] ofcreated_dirs = [] tails:",created_dirs = [] tailscreated_dirs = [] created_dirs = [] #created_dirs = [] nowcreated_dirs = [] 'head'created_dirs = [] containscreated_dirs = [] thecreated_dirs = [] deepestcreated_dirs = [] directorycreated_dirs = [] thatcreated_dirs = [] alreadycreated_dirs = [] existscreated_dirs = [] #created_dirs = [] (thatcreated_dirs = [] is,created_dirs = [] thecreated_dirs = [] childcreated_dirs = [] ofcreated_dirs = [] 'head'created_dirs = [] increated_dirs = [] 'name'created_dirs = [] iscreated_dirs = [] thecreated_dirs = [] highestcreated_dirs = [] directorycreated_dirs = [] #created_dirs = [] thatcreated_dirs = [] doescreated_dirs = [] *not*created_dirs = [] exist)created_dirs = [] forcreated_dirs = [] dcreated_dirs = [] increated_dirs = [] tails:created_dirs = [] #printcreated_dirs = [] "headcreated_dirs = [] =created_dirs = [] %s,created_dirs = [] dcreated_dirs = [] =created_dirs = [] %s:created_dirs = [] "created_dirs = [] %created_dirs = [] (head,created_dirs = [] d),created_dirs = [] headcreated_dirs = [] =created_dirs = [] os.path.joincreated_dirs = [] (head,created_dirs = [] d)created_dirs = [] ifcreated_dirs = [] PATH_CREATED.getcreated_dirs = [] (head):created_dirs = [] continuecreated_dirs = [] created_dirs = [] ifcreated_dirs = [] verbose:created_dirs = [] printcreated_dirs = [] "creating",created_dirs = [] headcreated_dirs = [] created_dirs = [] ifcreated_dirs = [] notcreated_dirs = [] dry_run:created_dirs = [] try:created_dirs = [] os.mkdircreated_dirs = [] (head)created_dirs = [] exceptcreated_dirs = [] os.error,created_dirs = [] (errno,created_dirs = [] errstr):created_dirs = [] raisecreated_dirs = [] DistutilsFileError,created_dirs = [] \created_dirs = [] "couldcreated_dirs = [] notcreated_dirs = [] createcreated_dirs = [] '%s':created_dirs = [] %s"created_dirs = [] %created_dirs = [] (head,created_dirs = [] errstr)created_dirs = [] created_dirs = [] PATH_CREATED[head]created_dirs = [] =created_dirs = [] 1created_dirs = []
9,379
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name) or name == '': return if PATH_CREATED.get (name): return (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return created_dirs silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name) or name == '': return created_dirs if PATH_CREATED.get (name): return created_dirs (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1
9,380
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name) or name == '': return if PATH_CREATED.get (name): return (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1
def mkpath (name, mode=0777, verbose=0, dry_run=0): """Create a directory and any missing ancestor directories. If the directory already exists, return created_dirs silently. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each mkdir to stdout.""" global PATH_CREATED # XXX what's the better way to handle verbosity? print as we create # each directory in the path (the current behaviour), or only announce # the creation of the whole path? (quite easy to do the latter since # we're not using a recursive algorithm) name = os.path.normpath (name) if os.path.isdir (name) or name == '': return created_dirs if PATH_CREATED.get (name): return created_dirs (head, tail) = os.path.split (name) tails = [tail] # stack of lone dirs to create while head and tail and not os.path.isdir (head): #print "splitting '%s': " % head, (head, tail) = os.path.split (head) #print "to ('%s','%s')" % (head, tail) tails.insert (0, tail) # push next higher dir onto stack #print "stack of tails:", tails # now 'head' contains the deepest directory that already exists # (that is, the child of 'head' in 'name' is the highest directory # that does *not* exist) for d in tails: #print "head = %s, d = %s: " % (head, d), head = os.path.join (head, d) if PATH_CREATED.get (head): continue if verbose: print "creating", head if not dry_run: try: os.mkdir (head) except os.error, (errno, errstr): raise DistutilsFileError, \ "could not create '%s': %s" % (head, errstr) PATH_CREATED[head] = 1
9,381
def cwd(self, dirname): '''Change to a directory.''' if dirname == '..': try: return self.voidcmd('CDUP') except error_perm, msg: if msg[:3] != '500': raise error_perm, msg elif dirname == '': dirname = '.' # does nothing, but could return error cmd = 'CWD ' + dirname return self.voidcmd(cmd)
def cwd(self, dirname): '''Change to a directory.''' if dirname == '..': try: return self.voidcmd('CDUP') except error_perm, msg: if msg.args[0][:3] != '500': raise elif dirname == '': dirname = '.' # does nothing, but could return error cmd = 'CWD ' + dirname return self.voidcmd(cmd)
9,382
# File extensions, associated with the REGISTRY.def component
# File extensions, associated with the REGISTRY.def component
9,383
# File extensions, associated with the REGISTRY.def component
# File extensions, associated with the REGISTRY.def component
9,384
def AskYesNoCancel(question, default = 0):
def screenbounds = Qd.qd.screenBits.bounds screenbounds = screenbounds[0]+4, screenbounds[1]+4, \ screenbounds[2]-4, screenbounds[3]-4 AskYesNoCancel(question, screenbounds = Qd.qd.screenBits.bounds screenbounds = screenbounds[0]+4, screenbounds[1]+4, \ screenbounds[2]-4, screenbounds[3]-4 default screenbounds = Qd.qd.screenBits.bounds screenbounds = screenbounds[0]+4, screenbounds[1]+4, \ screenbounds[2]-4, screenbounds[3]-4 = screenbounds = Qd.qd.screenBits.bounds screenbounds = screenbounds[0]+4, screenbounds[1]+4, \ screenbounds[2]-4, screenbounds[3]-4 0):
9,385
def __init__(self, label="Working...", maxval=100): self.label = label self.maxval = maxval self.curval = -1 self.d = GetNewDialog(259, -1) tp, text_h, rect = self.d.GetDialogItem(2) SetDialogItemText(text_h, label) self._update(0)
def __init__(self, title="Working...", maxval=100, label=""): self.maxval = maxval self.curval = -1 self.d = GetNewDialog(259, -1) tp, text_h, rect = self.d.GetDialogItem(2) SetDialogItemText(text_h, label) self._update(0)
9,386
def __init__(self, label="Working...", maxval=100): self.label = label self.maxval = maxval self.curval = -1 self.d = GetNewDialog(259, -1) tp, text_h, rect = self.d.GetDialogItem(2) SetDialogItemText(text_h, label) self._update(0)
def __init__(self, label="Working...", maxval=100): self.label = label self.maxval = maxval self.curval = -1 self.d = GetNewDialog(259, -1) tp, text_h, rect = self.d.GetDialogItem(2) SetDialogItemText(text_h, label) self._update(0)
9,387
def _update(self, value): tp, h, bar_rect = self.d.GetDialogItem(3) Qd.SetPort(self.d) Qd.FrameRect(bar_rect) # Draw outline inner_rect = Qd.InsetRect(bar_rect, 1, 1) l, t, r, b = inner_rect
def _update(self, value): tp, h, bar_rect = self.d.GetDialogItem(3) Qd.SetPort(self.d) Qd.FrameRect(bar_rect) # Draw outline inner_rect = Qd.InsetRect(bar_rect, 1, 1) l, t, r, b = inner_rect
9,388
def set(self, value): if value < 0: value = 0 if value > self.maxval: value = self.maxval self._update(value)
def set(self, value): if value < 0: value = 0 if value > self.maxval: value = self.maxval self._update(value)
9,389
def test(): Message("Testing EasyDialogs.") ok = AskYesNoCancel("Do you want to proceed?") if ok > 0: s = AskString("Enter your first name") Message("Thank you,\015%s" % `s`) bar = ProgressBar("Counting...", 100) for i in range(100): bar.set(i) del bar
def test(): Message("Testing EasyDialogs.") ok = AskYesNoCancel("Do you want to proceed?") if ok > 0: s = AskString("Enter your first name") Message("Thank you,\015%s" % `s`) bar = ProgressBar("Counting...", 100) for i in range(100): bar.set(i) del bar
9,390
def test(): Message("Testing EasyDialogs.") ok = AskYesNoCancel("Do you want to proceed?") if ok > 0: s = AskString("Enter your first name") Message("Thank you,\015%s" % `s`) bar = ProgressBar("Counting...", 100) for i in range(100): bar.set(i) del bar
def test(): Message("Testing EasyDialogs.") ok = AskYesNoCancel("Do you want to proceed?") if ok > 0: s = AskString("Enter your first name") Message("Thank you,\015%s" % `s`) bar = ProgressBar("Counting...", 100) for i in range(100): bar.set(i) del bar
9,391
def test_basic_pty(): try: debug("Calling master_open()") master_fd, slave_name = pty.master_open() debug("Got master_fd '%d', slave_name '%s'"%(master_fd, slave_name)) debug("Calling slave_open(%r)"%(slave_name,)) slave_fd = pty.slave_open(slave_name) debug("Got slave_fd '%d'"%slave_fd) except OSError: # " An optional feature could not be imported " ... ? raise TestSkipped, "Pseudo-terminals (seemingly) not functional." if not os.isatty(slave_fd) and sys.platform not in fickle_isatty: raise TestFailed, "slave_fd is not a tty" debug("Writing to slave_fd") os.write(slave_fd, TEST_STRING_1) s1 = os.read(master_fd, 1024) sys.stdout.write(normalize_output(s1)) debug("Writing chunked output") os.write(slave_fd, TEST_STRING_2[:5]) os.write(slave_fd, TEST_STRING_2[5:]) s2 = os.read(master_fd, 1024) sys.stdout.write(normalize_output(s2)) os.close(slave_fd) os.close(master_fd)
def test_basic_pty(): try: debug("Calling master_open()") master_fd, slave_name = pty.master_open() debug("Got master_fd '%d', slave_name '%s'"%(master_fd, slave_name)) debug("Calling slave_open(%r)"%(slave_name,)) slave_fd = pty.slave_open(slave_name) debug("Got slave_fd '%d'"%slave_fd) except OSError: # " An optional feature could not be imported " ... ? raise TestSkipped, "Pseudo-terminals (seemingly) not functional." if not os.isatty(slave_fd): raise TestFailed, "slave_fd is not a tty" debug("Writing to slave_fd") os.write(slave_fd, TEST_STRING_1) s1 = os.read(master_fd, 1024) sys.stdout.write(normalize_output(s1)) debug("Writing chunked output") os.write(slave_fd, TEST_STRING_2[:5]) os.write(slave_fd, TEST_STRING_2[5:]) s2 = os.read(master_fd, 1024) sys.stdout.write(normalize_output(s2)) os.close(slave_fd) os.close(master_fd)
9,392
def try_stmt(self, nodelist): # 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] # | 'try' ':' suite 'finally' ':' suite if nodelist[3][0] != symbol.except_clause: return self.com_try_finally(nodelist)
def try_stmt(self, nodelist): # 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] # | 'try' ':' suite 'finally' ':' suite if nodelist[3][0] != symbol.except_clause: return self.com_try_finally(nodelist)
9,393
def com_try_finally(self, nodelist): # try_fin_stmt: "try" ":" suite "finally" ":" suite return TryFinally(self.com_node(nodelist[2]), self.com_node(nodelist[5]), lineno=nodelist[0][2])
def com_try_finally(self, nodelist): # try_fin_stmt: "try" ":" suite "finally" ":" suite return TryFinally(self.com_node(nodelist[2]), self.com_node(nodelist[5]), lineno=nodelist[0][2])
9,394
def com_try_except(self, nodelist): # try_except: 'try' ':' suite (except_clause ':' suite)* ['else' suite] #tryexcept: [TryNode, [except_clauses], elseNode)] stmt = self.com_node(nodelist[2]) clauses = [] elseNode = None for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: # except_clause: 'except' [expr [',' expr]] */ if len(node) > 2: expr1 = self.com_node(node[2]) if len(node) > 4: expr2 = self.com_assign(node[4], OP_ASSIGN) else: expr2 = None else: expr1 = expr2 = None clauses.append((expr1, expr2, self.com_node(nodelist[i+2])))
def com_try_except(self, nodelist): # try_except: 'try' ':' suite (except_clause ':' suite)* ['else' suite] #tryexcept: [TryNode, [except_clauses], elseNode)] clauses = [] elseNode = None for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: # except_clause: 'except' [expr [',' expr]] */ if len(node) > 2: expr1 = self.com_node(node[2]) if len(node) > 4: expr2 = self.com_assign(node[4], OP_ASSIGN) else: expr2 = None else: expr1 = expr2 = None clauses.append((expr1, expr2, self.com_node(nodelist[i+2])))
9,395
def com_try_except(self, nodelist): # try_except: 'try' ':' suite (except_clause ':' suite)* ['else' suite] #tryexcept: [TryNode, [except_clauses], elseNode)] stmt = self.com_node(nodelist[2]) clauses = [] elseNode = None for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: # except_clause: 'except' [expr [',' expr]] */ if len(node) > 2: expr1 = self.com_node(node[2]) if len(node) > 4: expr2 = self.com_assign(node[4], OP_ASSIGN) else: expr2 = None else: expr1 = expr2 = None clauses.append((expr1, expr2, self.com_node(nodelist[i+2])))
def com_try_except(self, nodelist): # try_except: 'try' ':' suite (except_clause ':' suite)* ['else' suite] #tryexcept: [TryNode, [except_clauses], elseNode)] stmt = self.com_node(nodelist[2]) clauses = [] elseNode = None for i in range(3, len(nodelist), 3): node = nodelist[i] if node[0] == symbol.except_clause: # except_clause: 'except' [expr [',' expr]] */ if len(node) > 2: expr1 = self.com_node(node[2]) if len(node) > 4: expr2 = self.com_assign(node[4], OP_ASSIGN) else: expr2 = None else: expr1 = expr2 = None clauses.append((expr1, expr2, self.com_node(nodelist[i+2])))
9,396
def finalize_options (self):
def finalize_options (self):
9,397
def unpack(self, archive, output=None): return None
def unpack(self, archive, output=None, package=None): return None
9,398
def unpack(self, archive, output=None): cmd = self.argument % archive if _cmd(output, self._dir, cmd): return "unpack command failed"
def unpack(self, archive, output=None, package=None): cmd = self.argument % archive if _cmd(output, self._dir, cmd): return "unpack command failed"
9,399