bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(gself.lobaltrace) try: exec cmd in dict, dict finally: if not self.donothing: sys.settrace(None)
def runctx(self, cmd, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = {} if not self.donothing: sys.settrace(gself.lobaltrace) try: exec cmd in globals, locals finally: if not self.donothing: sys.settrace(None)
8,500
def globaltrace_lt(self, frame, why, arg): """ Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'. """ if why == 'call': (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0) # if DEBUG_MODE and not filename: # print "%s.globaltrace(frame: %s, why: %s, arg: %s): filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) if filename: modulename = inspect.getmodulename(filename) ignore_it = self.ignore.names(filename, modulename) # if DEBUG_MODE and not self.blabbed.has_key((filename, modulename,)): # self.blabbed[(filename, modulename,)] = None # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s\n" % (self, frame, why, arg, filename, modulename, ignore_it,) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) # if DEBUG_MODE: # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s -- about to localtrace\n" % (self, frame, why, arg, filename, modulename, ignore_it,) return self.localtrace else: # XXX why no filename? return None
def globaltrace_lt(self, frame, why, arg): """ Handles `call' events (why == 'call') and if the code block being entered is to be ignored then it returns `None', else it returns `self.localtrace'. """ if why == 'call': (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0) # if DEBUG_MODE and not filename: # print "%s.globaltrace(frame: %s, why: %s, arg: %s): filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) if filename: modulename = inspect.getmodulename(filename) ignore_it = self.ignore.names(filename, modulename) # if DEBUG_MODE and not self.blabbed.has_key((filename, modulename,)): # self.blabbed[(filename, modulename,)] = None # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s\n" % (self, frame, why, arg, filename, modulename, ignore_it,) if not ignore_it: if self.trace: print " --- modulename: %s, funcname: %s" % (modulename, funcname,) # if DEBUG_MODE: # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s -- about to localtrace\n" % (self, frame, why, arg, filename, modulename, ignore_it,) return self.localtrace else: # XXX why no filename? return None
8,501
def localtrace_trace(self, frame, why, arg): if why == 'line': # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14 # record the file name and line number of every trace # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame) # if DEBUG_MODE: # print "%s.localtrace_trace(frame: %s, why: %s, arg: %s); filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: # Using setdefault faster than two separate lines? --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. pass return self.localtrace
def localtrace_trace(self, frame, why, arg): if why == 'line': # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14 # record the file name and line number of every trace # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14 (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame) # if DEBUG_MODE: # print "%s.localtrace_trace(frame: %s, why: %s, arg: %s); filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: # Using setdefault faster than two separate lines? --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) try: print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. pass return self.localtrace
8,502
def _set_hostport(self, host, port): if port is None: i = host.rfind(':') j = host.rfind(']') # ipv6 addresses have [...] if i > j: try: port = int(host[i+1:]) except ValueError: raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) host = host[:i] else: port = self.default_port if host[0] == '[' and host[-1] == ']': host = host[1:-1] self.host = host self.port = port
def _set_hostport(self, host, port): if port is None: i = host.rfind(':') j = host.rfind(']') # ipv6 addresses have [...] if i > j: try: port = int(host[i+1:]) except ValueError: raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) host = host[:i] else: port = self.default_port if host and host[0] == '[' and host[-1] == ']': host = host[1:-1] self.host = host self.port = port
8,503
def test_lambda(self): self.failUnless(repr(lambda x: x).startswith( "<function <lambda> at 0x")) # XXX anonymous functions? see func_repr
def test_lambda(self): self.failUnless(repr(lambda x: x).startswith( "<function <lambda")) # XXX anonymous functions? see func_repr
8,504
def connect(self, host, port = 0): if not port: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: pass if not port: port = HTTP_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.debuglevel > 0: print 'connect:', (host, port) self.sock.connect(host, port)
def connect(self, host, port = 0): if not port: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: raise socket.error, "nonnumeric port" if not port: port = HTTP_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.debuglevel > 0: print 'connect:', (host, port) self.sock.connect(host, port)
8,505
def main(): print 'hello world' # XXXX # skip the toolbox initializations, already done # XXXX Should use gestalt here to check for quicktime version Qt.EnterMovies() # Get the movie file fss, ok = macfs.StandardGetFile(QuickTime.MovieFileType) if not ok: sys.exit(0) # Open the window bounds = (175, 75, 175+160, 75+120) theWindow = Win.NewCWindow(bounds, fss.as_tuple()[2], 0, 0, -1, 1, 0) # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) Qd.SetPort(theWindow) # Get the movie theMovie = loadMovie(fss) # Relocate to (0, 0) bounds = theMovie.GetMovieBox() bounds = 0, 0, bounds[2]-bounds[0], bounds[3]-bounds[1] theMovie.SetMovieBox(bounds) # Create a controller theController = theMovie.NewMovieController(bounds, QuickTime.mcTopLeftMovie) # Get movie size and update window parameters rv, bounds = theController.MCGetControllerBoundsRect() theWindow.SizeWindow(bounds[2], bounds[3], 0) # XXXX or [3] [2]? Qt.AlignWindow(theWindow, 0) theWindow.ShowWindow() # XXXX MCDoAction(theController, mcActionSetGrowBoxBounds, &maxBounds) theController.MCDoAction(QuickTime.mcActionSetKeysEnabled, '1') # XXXX MCSetActionFilterWithRefCon(theController, movieControllerEventFilter, (long)theWindow) done = 0 while not done: gotone, evt = Evt.WaitNextEvent(-1, 0) (what, message, when, where, modifiers) = evt
def main(): print 'hello world' # XXXX # skip the toolbox initializations, already done # XXXX Should use gestalt here to check for quicktime version Qt.EnterMovies() # Get the movie file fss, ok = macfs.StandardGetFile(QuickTime.MovieFileType) if not ok: sys.exit(0) # Open the window bounds = (175, 75, 175+160, 75+120) theWindow = Win.NewCWindow(bounds, fss.as_tuple()[2], 0, 0, -1, 1, 0) # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) Qd.SetPort(theWindow) # Get the movie theMovie = loadMovie(fss) # Relocate to (0, 0) bounds = theMovie.GetMovieBox() bounds = 0, 0, bounds[2]-bounds[0], bounds[3]-bounds[1] theMovie.SetMovieBox(bounds) # Create a controller theController = theMovie.NewMovieController(bounds, QuickTime.mcTopLeftMovie) # Get movie size and update window parameters rv, bounds = theController.MCGetControllerBoundsRect() theWindow.SizeWindow(bounds[2], bounds[3], 0) # XXXX or [3] [2]? Qt.AlignWindow(theWindow, 0) theWindow.ShowWindow() # XXXX MCDoAction(theController, mcActionSetGrowBoxBounds, &maxBounds) theController.MCDoAction(QuickTime.mcActionSetKeysEnabled, '1') # XXXX MCSetActionFilterWithRefCon(theController, movieControllerEventFilter, (long)theWindow) done = 0 while not done: gotone, evt = Evt.WaitNextEvent(0xffff, 0) (what, message, when, where, modifiers) = evt
8,506
def setup (**attrs): """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; find and parse config files; parse the command line; run each Distutils command found there, customized by the options supplied to 'setup()' (as keyword arguments), in config files, and on the command line. The Distribution instance might be an instance of a class supplied via the 'distclass' keyword argument to 'setup'; if no such class is supplied, then the Distribution class (in dist.py) is instantiated. All other arguments to 'setup' (except for 'cmdclass') are used to set attributes of the Distribution instance. The 'cmdclass' argument, if supplied, is a dictionary mapping command names to command classes. Each command encountered on the command line will be turned into a command class, which is in turn instantiated; any class found in 'cmdclass' is used in place of the default, which is (for command 'foo_bar') class 'foo_bar' in module 'distutils.command.foo_bar'. The command class must provide a 'user_options' attribute which is a list of option specifiers for 'distutils.fancy_getopt'. Any command-line options between the current and the next command are used to set attributes of the current command object. When the entire command-line has been successfully parsed, calls the 'run()' method on each command object in turn. This method will be driven entirely by the Distribution object (which each command object has a reference to, thanks to its constructor), and the command-specific options that became attributes of each command object. """ global _setup_stop_after, _setup_distribution # Determine the distribution class -- either caller-supplied or # our Distribution (see below). klass = attrs.get('distclass') if klass: del attrs['distclass'] else: klass = Distribution if not attrs.has_key('script_name'): attrs['script_name'] = os.path.basename(sys.argv[0]) if not attrs.has_key('script_args'): attrs['script_args'] = sys.argv[1:] # Create the Distribution instance, using the remaining arguments # (ie. everything except distclass) to initialize it try: _setup_distribution = dist = klass(attrs) except DistutilsSetupError, msg: if attrs.has_key('name'): raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) else: raise SystemExit, "error in setup command: %s" % msg if _setup_stop_after == "init": return dist # Find and parse the config file(s): they will override options from # the setup script, but be overridden by the command line. dist.parse_config_files() if DEBUG: print "options (after parsing config files):" dist.dump_option_dicts() if _setup_stop_after == "config": return dist # Parse the command line; any command-line errors are the end user's # fault, so turn them into SystemExit to suppress tracebacks. try: ok = dist.parse_command_line() except DistutilsArgError, msg: raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: print "options (after parsing command line):" dist.dump_option_dicts() if _setup_stop_after == "commandline": return dist # And finally, run all the commands found on the command line. if ok: try: dist.run_commands() except KeyboardInterrupt: raise SystemExit, "interrupted" except (IOError, os.error), exc: error = grok_environment_error(exc) if DEBUG: sys.stderr.write(error + "\n") raise else: raise SystemExit, error except (DistutilsExecError, DistutilsFileError, DistutilsOptionError, CCompilerError), msg: if DEBUG: raise else: raise SystemExit, "error: " + str(msg) return dist
def setup (**attrs): """The gateway to the Distutils: do everything your setup script needs to do, in a highly flexible and user-driven way. Briefly: create a Distribution instance; find and parse config files; parse the command line; run each Distutils command found there, customized by the options supplied to 'setup()' (as keyword arguments), in config files, and on the command line. The Distribution instance might be an instance of a class supplied via the 'distclass' keyword argument to 'setup'; if no such class is supplied, then the Distribution class (in dist.py) is instantiated. All other arguments to 'setup' (except for 'cmdclass') are used to set attributes of the Distribution instance. The 'cmdclass' argument, if supplied, is a dictionary mapping command names to command classes. Each command encountered on the command line will be turned into a command class, which is in turn instantiated; any class found in 'cmdclass' is used in place of the default, which is (for command 'foo_bar') class 'foo_bar' in module 'distutils.command.foo_bar'. The command class must provide a 'user_options' attribute which is a list of option specifiers for 'distutils.fancy_getopt'. Any command-line options between the current and the next command are used to set attributes of the current command object. When the entire command-line has been successfully parsed, calls the 'run()' method on each command object in turn. This method will be driven entirely by the Distribution object (which each command object has a reference to, thanks to its constructor), and the command-specific options that became attributes of each command object. """ global _setup_stop_after, _setup_distribution # Determine the distribution class -- either caller-supplied or # our Distribution (see below). klass = attrs.get('distclass') if klass: del attrs['distclass'] else: klass = Distribution if not attrs.has_key('script_name'): attrs['script_name'] = os.path.basename(sys.argv[0]) if not attrs.has_key('script_args'): attrs['script_args'] = sys.argv[1:] # Create the Distribution instance, using the remaining arguments # (ie. everything except distclass) to initialize it try: _setup_distribution = dist = klass(attrs) except DistutilsSetupError, msg: if attrs.has_key('name'): raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) else: raise SystemExit, "error in setup command: %s" % msg if _setup_stop_after == "init": return dist # Find and parse the config file(s): they will override options from # the setup script, but be overridden by the command line. dist.parse_config_files() if DEBUG: print "options (after parsing config files):" dist.dump_option_dicts() if _setup_stop_after == "config": return dist # Parse the command line; any command-line errors are the end user's # fault, so turn them into SystemExit to suppress tracebacks. try: ok = dist.parse_command_line() except DistutilsArgError, msg: raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg if DEBUG: print "options (after parsing command line):" dist.dump_option_dicts() if _setup_stop_after == "commandline": return dist # And finally, run all the commands found on the command line. if ok: try: dist.run_commands() except KeyboardInterrupt: raise SystemExit, "interrupted" except (IOError, os.error), exc: error = grok_environment_error(exc) if DEBUG: sys.stderr.write(error + "\n") raise else: raise SystemExit, error except (DistutilsError, CCompilerError), msg: if DEBUG: raise else: raise SystemExit, "error: " + str(msg) return dist
8,507
def do_mouseDown(self, event): (what, message, when, where, modifiers) = event partcode, window = FindWindow(where) if partname.has_key(partcode): name = "do_" + partname[partcode] else: name = "do_%d" % partcode try: handler = getattr(self, name) except AttrinuteError: handler = self.do_unknownpartcode handler(partcode, window, event)
def do_mouseDown(self, event): (what, message, when, where, modifiers) = event partcode, window = FindWindow(where) if partname.has_key(partcode): name = "do_" + partname[partcode] else: name = "do_%d" % partcode try: handler = getattr(self, name) except AttributeError: handler = self.do_unknownpartcode handler(partcode, window, event)
8,508
def do_close(self, window): print "Should close window:", window
def do_close(self, window): if DEBUG: print "Should close window:", window
8,509
def do_inSysWindow(self, partcode, window, event): print "SystemClick", event, window # SystemClick(event, window) # XXX useless, window is None
def do_inSysWindow(self, partcode, window, event): MacOS.HandleEvent(event) # SystemClick(event, window) # XXX useless, window is None
8,510
def do_inDesk(self, partcode, window, event): print "inDesk" # XXX what to do with it?
def do_inDesk(self, partcode, window, event): # XXX what to do with it?
8,511
def do_inContent(self, partcode, window, event): (what, message, when, where, modifiers) = event local = GlobalToLocal(where) ctltype, control = FindControl(local, window) if ctltype and control: pcode = control.TrackControl(local) if pcode: self.do_controlhit(window, control, pcode, event) else: print "FindControl(%s, %s) -> (%s, %s)" % \ (local, window, ctltype, control)
def do_inContent(self, partcode, window, event): (what, message, when, where, modifiers) = event local = GlobalToLocal(where) ctltype, control = FindControl(local, window) if ctltype and control: pcode = control.TrackControl(local) if pcode: self.do_controlhit(window, control, pcode, event) else: if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \ (local, window, ctltype, control)
8,512
def do_controlhit(self, window, control, pcode, event): print "control hit in", window, "on", control, "; pcode =", pcode
def do_controlhit(self, window, control, pcode, event): if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode
8,513
def do_unknownpartcode(self, partcode, window, event): (what, message, when, where, modifiers) = event print "Mouse down at global:", where print "\tUnknown part code:", partcode
def do_unknownpartcode(self, partcode, window, event): (what, message, when, where, modifiers) = event if DEBUG: print "Mouse down at global:", where if DEBUG: print "\tUnknown part code:", partcode MacOS.HandleEvent(event)
8,514
def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = FrontWindow() if w: self.do_close(w) else: print 'Command-W without front window' else: print "Command-" +`c` else: self.do_char(c, event)
def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = FrontWindow() if w: self.do_close(w) else: if DEBUG: print 'Command-W without front window' else: print "Command-" +`c` else: self.do_char(c, event)
8,515
def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = FrontWindow() if w: self.do_close(w) else: print 'Command-W without front window' else: print "Command-" +`c` else: self.do_char(c, event)
def do_key(self, event): (what, message, when, where, modifiers) = event c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise self else: result = MenuKey(ord(c)) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id: self.do_rawmenu(id, item, None, event) elif c == 'w': w = FrontWindow() if w: self.do_close(w) else: print 'Command-W without front window' else: if DEBUG: print "Command-" +`c` else: self.do_char(c, event)
8,516
def do_char(self, c, event): print "Character", `c`
def do_char(self, c, event): if DEBUG: print "Character", `c`
8,517
def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt"
def do_updateEvt(self, event): if DEBUG: print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt"
8,518
def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: print "no window for do_updateEvt"
def do_updateEvt(self, event): print "do_update", self.printevent(event) window = FrontWindow() # XXX This is wrong! if window: self.do_rawupdate(window, event) else: MacOS.HandleEvent(event)
8,519
def do_rawupdate(self, window, event): print "raw update for", window window.BeginUpdate() self.do_update(window, event) DrawControls(window) window.DrawGrowIcon() window.EndUpdate()
def do_rawupdate(self, window, event): if DEBUG: print "raw update for", window window.BeginUpdate() self.do_update(window, event) DrawControls(window) window.DrawGrowIcon() window.EndUpdate()
8,520
def do_kHighLevelEvent(self, event): (what, message, when, where, modifiers) = event print "High Level Event:", self.printevent(event) try: AEProcessAppleEvent(event) except: print "AEProcessAppleEvent error:" traceback.print_exc()
def do_kHighLevelEvent(self, event): (what, message, when, where, modifiers) = event if DEBUG: print "High Level Event:", self.printevent(event) try: AEProcessAppleEvent(event) except: print "AEProcessAppleEvent error:" traceback.print_exc()
8,521
def dispatch(self, id, item, window, event): if self.menus.has_key(id): self.menus[id].dispatch(id, item, window, event) else: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ (id, item, window, event)
def dispatch(self, id, item, window, event): if self.menus.has_key(id): self.menus[id].dispatch(id, item, window, event) else: if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ (id, item, window, event)
8,522
def set_path_env_var (name, version_number): """Set environment variable 'name' to an MSVC path type value obtained from 'get_msvc_paths()'. This is equivalent to a SET command prior to execution of spawned commands.""" p = get_msvc_paths (name, version_number) if p: os.environ[name] = string.join (p,';')
def set_path_env_var (name, version_number): """Set environment variable 'name' to an MSVC path type value obtained from 'get_msvc_paths()'. This is equivalent to a SET command prior to execution of spawned commands.""" p = get_msvc_paths (name, version_number) if p: os.environ[name] = string.join (p,';')
8,523
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
def compile (self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None):
8,524
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except: ar = 'no self.addr!'
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: if self.addr == types.TupleType: status.append ('%s:%d' % self.addr) else: status.append (self.addr) return '<%s %s at %x>' % (self.__class__.__name__, ' '.join (status), id (self)) except: try: ar = repr(self.addr) except: ar = 'no self.addr!'
8,525
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except: ar = 'no self.addr!'
def __repr__ (self): try: status = [] if self.accepting and self.addr: status.append ('listening') elif self.connected: status.append ('connected') if self.addr: status.append ('%s:%d' % self.addr) return '<%s %s at %x>' % ( self.__class__.__name__, ' '.join (status), id(self) ) except: try: ar = repr(self.addr) except: ar = 'no self.addr!'
8,526
def get_config_h_filename(): """Return full pathname of installed config.h file.""" return os.path.join(sys.exec_prefix, "lib", "python" + sys.version[:3], "config", "config.h")
def get_config_h_filename(): """Return full pathname of installed config.h file.""" return os.path.join(sys.exec_prefix, "include", "python" + sys.version[:3], "config.h")
8,527
def __init__(self): self.quitting = 0 # Initialize menu self.appleid = 1 self.quitid = 2 Menu.ClearMenuBar() self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") applemenu.AppendMenu("All about cgitest...;(-") applemenu.AppendResMenu('DRVR') applemenu.InsertMenu(0) self.quitmenu = Menu.NewMenu(self.quitid, "File") self.quitmenu.AppendMenu("Quit") self.quitmenu.InsertMenu(0) Menu.DrawMenuBar()
def __init__(self): self.quitting = 0 # Initialize menu self.appleid = 1 self.quitid = 2 Menu.ClearMenuBar() self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") applemenu.AppendMenu("About %s...;(-" % self.__class__.__name__) applemenu.AppendResMenu('DRVR') applemenu.InsertMenu(0) self.quitmenu = Menu.NewMenu(self.quitid, "File") self.quitmenu.AppendMenu("Quit") self.quitmenu.InsertMenu(0) Menu.DrawMenuBar()
8,528
def __del__(self): self.close()
def __del__(self): self.close()
8,529
def close(self): pass
def close(self): pass
8,530
def mainloop(self, mask = everyEvent, timeout = 60*60): while not self.quitting: self.dooneevent(mask, timeout)
def mainloop(self, mask = everyEvent, timeout = 60*60): while not self.quitting: self.dooneevent(mask, timeout)
8,531
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if modifiers & cmdKey: if c == '.': raise KeyboardInterrupt, "Command-period" if c == 'q': self.quitting = 1 elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
8,532
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message(self.getabouttext()) elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
8,533
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetMenuItemText(item) Menu.OpenDeskAcc(name) elif id == self.quitid and item == 1: self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
8,534
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: print 'AE error: ', err print 'in', msg traceback.print_exc() return elif what == keyDown: c = chr(message & charCodeMask) if c == '.' and modifiers & cmdKey: raise KeyboardInterrupt, "Command-period" elif what == mouseDown: partcode, window = Win.FindWindow(where) if partcode == inMenuBar: result = Menu.MenuSelect(where) id = (result>>16) & 0xffff # Hi word item = result & 0xffff # Lo word if id == self.appleid: if item == 1: EasyDialogs.Message("cgitest - First cgi test") return elif item > 1: name = self.applemenu.GetItem(item) Qd.OpenDeskAcc(name) return if id == self.quitid and item == 1: print "Menu-requested QUIT" self.quitting = 1 # Anything not handled is passed to Python/SIOUX MacOS.HandleEvent(event)
8,535
def __init__(self): self.ae_handlers = {}
def __init__(self): self.ae_handlers = {}
8,536
def close(self): for classe, type in self.ae_handlers.keys(): AE.AERemoveEventHandler(classe, type)
def close(self): for classe, type in self.ae_handlers.keys(): AE.AERemoveEventHandler(classe, type)
8,537
def callback_wrapper(self, _request, _reply): _parameters, _attributes = aetools.unpackevent(_request) _class = _attributes['evcl'].type _type = _attributes['evid'].type if self.ae_handlers.has_key((_class, _type)): _function = self.ae_handlers[(_class, _type)] elif self.ae_handlers.has_key((_class, '****')): _function = self.ae_handlers[(_class, '****')] elif self.ae_handlers.has_key(('****', '****')): _function = self.ae_handlers[('****', '****')] else: raise 'Cannot happen: AE callback without handler', (_class, _type) # XXXX Do key-to-name mapping here _parameters['_attributes'] = _attributes _parameters['_class'] = _class _parameters['_type'] = _type if _parameters.has_key('----'): _object = _parameters['----'] del _parameters['----'] try: rv = apply(_function, (_object,), _parameters) except TypeError, name: raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name) else: try: rv = apply(_function, (), _parameters) except TypeError, name: raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name) if rv == None: aetools.packevent(_reply, {}) else: aetools.packevent(_reply, {'----':rv})
def callback_wrapper(self, _request, _reply): _parameters, _attributes = aetools.unpackevent(_request) _class = _attributes['evcl'].type _type = _attributes['evid'].type if self.ae_handlers.has_key((_class, _type)): _function = self.ae_handlers[(_class, _type)] elif self.ae_handlers.has_key((_class, '****')): _function = self.ae_handlers[(_class, '****')] elif self.ae_handlers.has_key(('****', '****')): _function = self.ae_handlers[('****', '****')] else: raise 'Cannot happen: AE callback without handler', (_class, _type) # XXXX Do key-to-name mapping here _parameters['_attributes'] = _attributes _parameters['_class'] = _class _parameters['_type'] = _type if _parameters.has_key('----'): _object = _parameters['----'] del _parameters['----'] try: rv = apply(_function, (_object,), _parameters) except TypeError, name: raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name) else: try: rv = apply(_function, (), _parameters) except TypeError, name: raise TypeError, ('AppleEvent handler misses formal keyword argument', _function, name) if rv == None: aetools.packevent(_reply, {}) else: aetools.packevent(_reply, {'----':rv})
8,538
def initfp(self, file): self._version = 0 self._decomp = None self._convert = None self._markers = [] self._soundpos = 0 self._file = Chunk(file) if self._file.getname() != 'FORM': raise Error, 'file does not start with FORM id' formdata = self._file.read(4) if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == 'FVER': self._version = _read_long(chunk) elif chunkname == 'MARK': self._readmark(chunk) elif chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error, 'COMM chunk and/or SSND chunk missing' if self._aifc and self._decomp: import cl params = [cl.ORIGINAL_FORMAT, 0, cl.BITS_PER_COMPONENT, self._sampwidth * 8, cl.FRAME_RATE, self._framerate] if self._nchannels == 1: params[1] = cl.MONO elif self._nchannels == 2: params[1] = cl.STEREO_INTERLEAVED else: raise Error, 'cannot compress more than 2 channels' self._decomp.SetParams(params)
def initfp(self, file): self._version = 0 self._decomp = None self._convert = None self._markers = [] self._soundpos = 0 self._file = Chunk(file) if self._file.getname() != 'FORM': raise Error, 'file does not start with FORM id' formdata = self._file.read(4) if formdata == 'AIFF': self._aifc = 0 elif formdata == 'AIFC': self._aifc = 1 else: raise Error, 'not an AIFF or AIFF-C file' self._comm_chunk_read = 0 while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == 'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == 'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == 'FVER': self._version = _read_ulong(chunk) elif chunkname == 'MARK': self._readmark(chunk) elif chunkname in _skiplist: pass else: raise Error, 'unrecognized chunk type '+chunk.chunkname chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error, 'COMM chunk and/or SSND chunk missing' if self._aifc and self._decomp: import cl params = [cl.ORIGINAL_FORMAT, 0, cl.BITS_PER_COMPONENT, self._sampwidth * 8, cl.FRAME_RATE, self._framerate] if self._nchannels == 1: params[1] = cl.MONO elif self._nchannels == 2: params[1] = cl.STEREO_INTERLEAVED else: raise Error, 'cannot compress more than 2 channels' self._decomp.SetParams(params)
8,539
def reportMissing(self): missing = [name for name in self.missingModules if name not in MAYMISS_MODULES] if self.maybeMissingModules: maybe = self.maybeMissingModules else: maybe = [name for name in missing if "." in name] missing = [name for name in missing if "." not in name] missing.sort() maybe.sort() if maybe: self.message("Warning: couldn't find the following submodules:", 1) self.message(" (Note that these could be false alarms -- " "it's not always", 1) self.message(" possible to distinguish between from \"package import submodule\" ", 1) self.message(" and \"from package import name\")", 1) for name in maybe: self.message(" ? " + name, 1) if missing: self.message("Warning: couldn't find the following modules:", 1) for name in missing: self.message(" ? " + name, 1)
def reportMissing(self): missing = [name for name in self.missingModules if name not in MAYMISS_MODULES] if self.maybeMissingModules: maybe = self.maybeMissingModules else: maybe = [name for name in missing if "." in name] missing = [name for name in missing if "." not in name] missing.sort() maybe.sort() if maybe: self.message("Warning: couldn't find the following submodules:", 1) self.message(" (Note that these could be false alarms -- " "it's not always", 1) self.message(" possible to distinguish between \"from package " "import submodule\" ", 1) self.message(" and \"from package import name\")", 1) for name in maybe: self.message(" ? " + name, 1) if missing: self.message("Warning: couldn't find the following modules:", 1) for name in missing: self.message(" ? " + name, 1)
8,540
def basic_test_inplace_concat(self, size): l = [sys.stdout] * size l += l self.assertEquals(len(l), size * 2) self.failUnless(l[0] is l[-1]) self.failUnless(l[size - 1] is l[size + 1])
def basic_test_inplace_concat(self, size): l = [sys.stdout] * size l += l self.assertEquals(len(l), size * 2) self.failUnless(l[0] is l[-1]) self.failUnless(l[size - 1] is l[size + 1])
8,541
def test_inplace_concat_small(self, size): return self.basic_test_inplace_concat(size)
def test_inplace_concat_small(self, size): return self.basic_test_inplace_concat(size)
8,542
def __init__(self, switchboard, parent=None): self.__sb = switchboard self.__frame = Frame(parent) self.__frame.pack(expand=YES, fill=BOTH) # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) self.__selected = ChipWidget(self.__sframe, text='Selected') # create the chip that will display the nearest real X11 color # database color name self.__nframe = Frame(self.__frame) self.__nframe.grid(row=0, column=1) self.__nearest = ChipWidget(self.__nframe, text='Nearest', presscmd = self.__buttonpress, releasecmd = self.__buttonrelease)
def __init__(self, switchboard, parent=None): self.__sb = switchboard self.__frame = Frame(parent, relief=GROOVE, borderwidth=2) self.__frame.pack() # create the chip that will display the currently selected color # exactly self.__sframe = Frame(self.__frame) self.__sframe.grid(row=0, column=0) self.__selected = ChipWidget(self.__sframe, text='Selected') # create the chip that will display the nearest real X11 color # database color name self.__nframe = Frame(self.__frame) self.__nframe.grid(row=0, column=1) self.__nearest = ChipWidget(self.__nframe, text='Nearest', presscmd = self.__buttonpress, releasecmd = self.__buttonrelease)
8,543
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) if os.name == 'posix': try: fd = os.open(filename, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700) except OSError: pass else: fp = os.fdopen(fd, 'w') fp.write('blat') fp.close() os.unlink(filename) del fp, fd tempdir = dir break else: fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
def gettempdir(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd] if os.name == 'nt': attempdirs.insert(0, 'C:\\TEMP') attempdirs.insert(0, '\\TEMP') elif os.name == 'mac': import macfs, MACFS try: refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, MACFS.kTemporaryFolderType, 1) dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': if os.environ.has_key(envname): attempdirs.insert(0, os.environ[envname]) testfile = gettempprefix() + 'test' for dir in attempdirs: try: filename = os.path.join(dir, testfile) if os.name == 'posix': try: fd = os.open(filename, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700) except OSError: pass else: fp = os.fdopen(fd, 'w') fp.write('blat') fp.close() os.unlink(filename) del fp, fd tempdir = dir break else: fp = open(filename, 'w') fp.write('blat') fp.close() os.unlink(filename) tempdir = dir break except IOError: pass if tempdir is None: msg = "Can't find a usable temporary directory amongst " + `attempdirs` raise IOError, msg return tempdir
8,544
def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError, 'arg is not a code object' code = co.co_code nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. for i in range(nargs): if args[i][:1] in ['', '.']: stack, remain, count = [], [], [] while step < len(code): op = ord(code[step]) step = step + 1 if op >= dis.HAVE_ARGUMENT: opname = dis.opname[op] value = ord(code[step]) + ord(code[step+1])*256 step = step + 2 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: remain.append(value) count.append(value) elif opname == 'STORE_FAST': stack.append(names[value]) remain[-1] = remain[-1] - 1 while remain[-1] == 0: remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] if not remain: break remain[-1] = remain[-1] - 1 if not remain: break args[i] = stack[0] varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, varkw
def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('arg is not a code object') code = co.co_code nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. for i in range(nargs): if args[i][:1] in ['', '.']: stack, remain, count = [], [], [] while step < len(code): op = ord(code[step]) step = step + 1 if op >= dis.HAVE_ARGUMENT: opname = dis.opname[op] value = ord(code[step]) + ord(code[step+1])*256 step = step + 2 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: remain.append(value) count.append(value) elif opname == 'STORE_FAST': stack.append(names[value]) remain[-1] = remain[-1] - 1 while remain[-1] == 0: remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] if not remain: break remain[-1] = remain[-1] - 1 if not remain: break args[i] = stack[0] varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, varkw
8,545
def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments.""" if not isfunction(func): raise TypeError, 'arg is not a Python function' args, varargs, varkw = getargs(func.func_code) return args, varargs, varkw, func.func_defaults
def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.im_func if not isfunction(func): raise TypeError('arg is not a Python function') args, varargs, varkw = getargs(func.func_code) return args, varargs, varkw, func.func_defaults
8,546
def __str__(self): return self.x
def __str__(self): return self.x
8,547
def __init__(self, url, data=None, headers={}): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} self.headers.update(headers)
def __init__(self, url, data=None, headers={}): # unwrap('<URL:type://host/path>') --> 'type://host/path' self.__original = unwrap(url) self.type = None # self.__r_type is what's left after doing the splittype self.host = None self.port = None self.data = data self.headers = {} self.headers.update(headers)
8,548
def add_header(self, key, val): # useful for something like authentication self.headers[key] = val
def add_header(self, key, val): # useful for something like authentication self.headers[key] = val
8,549
def __init__(self, proxies=None): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies for type, url in proxies.items(): setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: \ meth(r, proxy, type))
def __init__(self, proxies=None): if proxies is None: proxies = getproxies() assert hasattr(proxies, 'has_key'), "proxies must be a mapping" self.proxies = proxies for type, url in proxies.iteritems(): setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: \ meth(r, proxy, type))
8,550
def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) authuri = self.reduce_uri(authuri) for uris, authinfo in domains.items(): for uri in uris: if self.is_suburi(uri, authuri): return authinfo return None, None
def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) authuri = self.reduce_uri(authuri) for uris, authinfo in domains.iteritems(): for uri in uris: if self.is_suburi(uri, authuri): return authinfo return None, None
8,551
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
8,552
def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.items(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values())
def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.iteritems(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values())
8,553
def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.items(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values())
def check_cache(self): # first check for old ones t = time.time() if self.soonest <= t: for k, v in self.timeout.iteritems(): if v < t: self.cache[k].close() del self.cache[k] del self.timeout[k] self.soonest = min(self.timeout.values())
8,554
def win32_ver(release='',version='',csd='',ptype=''): """ Get additional version information from the Windows Registry and return a tuple (version,csd,ptype) referring to version number, CSD level and OS type (multi/single processor). As a hint: ptype returns 'Uniprocessor Free' on single processor NT machines and 'Multiprocessor Free' on multi processor machines. The 'Free' refers to the OS version being free of debugging code. It could also state 'Checked' which means the OS version uses debugging code, i.e. code that checks arguments, ranges, etc. (Thomas Heller). Note: this functions only works if Mark Hammond's win32 package is installed and obviously only runs on Win32 compatible platforms. """ # XXX Is there any way to find out the processor type on WinXX ? # XXX Is win32 available on Windows CE ? # Adapted from code posted by Karl Putland to comp.lang.python. # Import the needed APIs try: import win32api except ImportError: return release,version,csd,ptype from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\ VER_PLATFORM_WIN32_WINDOWS # Find out the registry key and some general version infos maj,min,buildno,plat,csd = GetVersionEx() version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) if csd[:13] == 'Service Pack ': csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name if maj == 4: if min == 0: release = '95' else: release = '98' elif maj == 5: release = '2000' elif plat == VER_PLATFORM_WIN32_NT: regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' if maj <= 4: release = 'NT' elif maj == 5: release = '2000' else: if not release: # E.g. Win3.1 with win32s release = '%i.%i' % (maj,min) return release,version,csd,ptype # Open the registry key try: keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey) # Get a value to make sure the key exists... RegQueryValueEx(keyCurVer,'SystemRoot') except: return release,version,csd,ptype # Parse values #subversion = _win32_getvalue(keyCurVer, # 'SubVersionNumber', # ('',1))[0] #if subversion: # release = release + subversion # 95a, 95b, etc. build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('',1))[0] ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype,1))[0] # Normalize version version = _norm_version(version,build) # Close key RegCloseKey(keyCurVer) return release,version,csd,ptype
def win32_ver(release='',version='',csd='',ptype=''): """ Get additional version information from the Windows Registry and return a tuple (version,csd,ptype) referring to version number, CSD level and OS type (multi/single processor). As a hint: ptype returns 'Uniprocessor Free' on single processor NT machines and 'Multiprocessor Free' on multi processor machines. The 'Free' refers to the OS version being free of debugging code. It could also state 'Checked' which means the OS version uses debugging code, i.e. code that checks arguments, ranges, etc. (Thomas Heller). Note: this function only works if Mark Hammond's win32 package is installed and obviously only runs on Win32 compatible platforms. """ # XXX Is there any way to find out the processor type on WinXX ? # XXX Is win32 available on Windows CE ? # Adapted from code posted by Karl Putland to comp.lang.python. # Import the needed APIs try: import win32api except ImportError: return release,version,csd,ptype from win32api import RegQueryValueEx,RegOpenKeyEx,RegCloseKey,GetVersionEx from win32con import HKEY_LOCAL_MACHINE,VER_PLATFORM_WIN32_NT,\ VER_PLATFORM_WIN32_WINDOWS # Find out the registry key and some general version infos maj,min,buildno,plat,csd = GetVersionEx() version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF) if csd[:13] == 'Service Pack ': csd = 'SP' + csd[13:] if plat == VER_PLATFORM_WIN32_WINDOWS: regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion' # Try to guess the release name if maj == 4: if min == 0: release = '95' else: release = '98' elif maj == 5: release = '2000' elif plat == VER_PLATFORM_WIN32_NT: regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' if maj <= 4: release = 'NT' elif maj == 5: release = '2000' else: if not release: # E.g. Win3.1 with win32s release = '%i.%i' % (maj,min) return release,version,csd,ptype # Open the registry key try: keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE,regkey) # Get a value to make sure the key exists... RegQueryValueEx(keyCurVer,'SystemRoot') except: return release,version,csd,ptype # Parse values #subversion = _win32_getvalue(keyCurVer, # 'SubVersionNumber', # ('',1))[0] #if subversion: # release = release + subversion # 95a, 95b, etc. build = _win32_getvalue(keyCurVer, 'CurrentBuildNumber', ('',1))[0] ptype = _win32_getvalue(keyCurVer, 'CurrentType', (ptype,1))[0] # Normalize version version = _norm_version(version,build) # Close key RegCloseKey(keyCurVer) return release,version,csd,ptype
8,555
def __init__(self, switchboard, master=None): # non-gui ivars self.__sb = switchboard optiondb = switchboard.optiondb() self.__hexp = BooleanVar() self.__hexp.set(optiondb.get('HEXTYPE', 0)) self.__uwtyping = BooleanVar() self.__uwtyping.set(optiondb.get('UPWHILETYPE', 0)) # create the gui self.__frame = Frame(master, relief=RAISED, borderwidth=1) self.__frame.grid(row=3, column=1, sticky='NS') # Red self.__xl = Label(self.__frame, text='Red:') self.__xl.grid(row=0, column=0, sticky=E) self.__x = Entry(self.__frame, width=4) self.__x.grid(row=0, column=1) self.__x.bindtags(self.__x.bindtags() + ('Normalize', 'Update')) self.__x.bind_class('Normalize', '<Key>', self.__normalize) self.__x.bind_class('Update' , '<Key>', self.__maybeupdate) # Green self.__yl = Label(self.__frame, text='Green:') self.__yl.grid(row=1, column=0, sticky=E) self.__y = Entry(self.__frame, width=4) self.__y.grid(row=1, column=1) self.__y.bindtags(self.__y.bindtags() + ('Normalize', 'Update')) # Blue self.__zl = Label(self.__frame, text='Blue:') self.__zl.grid(row=2, column=0, sticky=E) self.__z = Entry(self.__frame, width=4) self.__z.grid(row=2, column=1) self.__z.bindtags(self.__z.bindtags() + ('Normalize', 'Update')) # Update while typing? self.__uwt = Checkbutton(self.__frame, text='Update while typing', variable=self.__uwtyping) self.__uwt.grid(row=3, column=0, columnspan=2, sticky=W) # Hex/Dec self.__hex = Checkbutton(self.__frame, text='Hexadecimal', variable=self.__hexp, command=self.__togglehex) self.__hex.grid(row=4, column=0, columnspan=2, sticky=W)
def __init__(self, switchboard, master=None): # non-gui ivars self.__sb = switchboard optiondb = switchboard.optiondb() self.__hexp = BooleanVar() self.__hexp.set(optiondb.get('HEXTYPE', 0)) self.__uwtyping = BooleanVar() self.__uwtyping.set(optiondb.get('UPWHILETYPE', 0)) # create the gui self.__frame = Frame(master, relief=RAISED, borderwidth=1) self.__frame.grid(row=3, column=1, sticky='NSEW') # Red self.__xl = Label(self.__frame, text='Red:') self.__xl.grid(row=0, column=0, sticky=E) self.__x = Entry(self.__frame, width=4) self.__x.grid(row=0, column=1) self.__x.bindtags(self.__x.bindtags() + ('Normalize', 'Update')) self.__x.bind_class('Normalize', '<Key>', self.__normalize) self.__x.bind_class('Update' , '<Key>', self.__maybeupdate) # Green self.__yl = Label(self.__frame, text='Green:') self.__yl.grid(row=1, column=0, sticky=E) self.__y = Entry(self.__frame, width=4) self.__y.grid(row=1, column=1) self.__y.bindtags(self.__y.bindtags() + ('Normalize', 'Update')) # Blue self.__zl = Label(self.__frame, text='Blue:') self.__zl.grid(row=2, column=0, sticky=E) self.__z = Entry(self.__frame, width=4) self.__z.grid(row=2, column=1) self.__z.bindtags(self.__z.bindtags() + ('Normalize', 'Update')) # Update while typing? self.__uwt = Checkbutton(self.__frame, text='Update while typing', variable=self.__uwtyping) self.__uwt.grid(row=3, column=0, columnspan=2, sticky=W) # Hex/Dec self.__hex = Checkbutton(self.__frame, text='Hexadecimal', variable=self.__hexp, command=self.__togglehex) self.__hex.grid(row=4, column=0, columnspan=2, sticky=W)
8,556
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__("".join(L)) return self._rev
8,557
def _connect_unixsocket(self, address): self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) # syslog may require either DGRAM or STREAM sockets try: self.socket.connect(address) except socket.error: self.socket.close() self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.socket.connect(address)
def _connect_unixsocket(self, address): self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) # syslog may require either DGRAM or STREAM sockets try: self.socket.connect(address) except socket.error: self.socket.close() self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.socket.connect(address)
8,558
def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the last character inserted and ring # the bell if v is None or v < 0 or v > 255: i = ew.index(INSERT) contents = contents[:i-1] + contents[i:] ew.bell() icursor = icursor-1 elif self.__hexp.get(): contents = hex(v) else: contents = int(v) ew.delete(0, END) ew.insert(0, contents) ew.icursor(icursor)
def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the last character inserted and ring # the bell if v is None or v < 0 or v > 255: i = ew.index(INSERT) if event.char: contents = contents[:i-1] + contents[i:] icursor = icursor-1 ew.bell() icursor = icursor-1 elif self.__hexp.get(): contents = hex(v) else: contents = int(v) ew.delete(0, END) ew.insert(0, contents) ew.icursor(icursor)
8,559
def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the last character inserted and ring # the bell if v is None or v < 0 or v > 255: i = ew.index(INSERT) contents = contents[:i-1] + contents[i:] ew.bell() icursor = icursor-1 elif self.__hexp.get(): contents = hex(v) else: contents = int(v) ew.delete(0, END) ew.insert(0, contents) ew.icursor(icursor)
def __normalize(self, event=None): ew = event.widget contents = ew.get() icursor = ew.index(INSERT) if contents == '': contents = '0' # figure out what the contents value is in the current base try: if self.__hexp.get(): v = string.atoi(contents, 16) else: v = string.atoi(contents) except ValueError: v = None # if value is not legal, delete the last character inserted and ring # the bell if v is None or v < 0 or v > 255: i = ew.index(INSERT) contents = contents[:i-1] + contents[i:] ew.bell() elif self.__hexp.get(): contents = hex(v) else: contents = int(v) ew.delete(0, END) ew.insert(0, contents) ew.icursor(icursor)
8,560
def update_yourself(self, red, green, blue): if self.__hexp.get(): redstr, greenstr, bluestr = map(hex, (red, green, blue)) else: redstr, greenstr, bluestr = red, green, blue self.__x.delete(0, END) self.__y.delete(0, END) self.__z.delete(0, END) self.__x.insert(0, redstr) self.__y.insert(0, greenstr) self.__z.insert(0, bluestr)
def update_yourself(self, red, green, blue): if self.__hexp.get(): redstr, greenstr, bluestr = map(hex, (red, green, blue)) else: redstr, greenstr, bluestr = red, green, blue self.__x.delete(0, END) self.__y.delete(0, END) self.__z.delete(0, END) self.__x.insert(0, redstr) self.__y.insert(0, greenstr) self.__z.insert(0, bluestr)
8,561
def b(): 'my docstring' pass
def b(): 'my docstring' pass
8,562
def b(): 'my docstring' pass
def b(): 'my docstring' pass
8,563
def cantset(obj, name, value): verify(hasattr(obj, name)) # Otherwise it's probably a typo try: setattr(obj, name, value) except TypeError: pass else: raise TestFailed, "shouldn't be able to set %s to %r" % (name, value) try: delattr(obj, name) except TypeError: pass else: raise TestFailed, "shouldn't be able to del %s" % name
def cantset(obj, name, value): verify(hasattr(obj, name)) # Otherwise it's probably a typo try: setattr(obj, name, value) except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't be able to set %s to %r" % (name, value) try: delattr(obj, name) except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't be able to del %s" % name
8,564
def cantset(obj, name, value): verify(hasattr(obj, name)) # Otherwise it's probably a typo try: setattr(obj, name, value) except TypeError: pass else: raise TestFailed, "shouldn't be able to set %s to %r" % (name, value) try: delattr(obj, name) except TypeError: pass else: raise TestFailed, "shouldn't be able to del %s" % name
def cantset(obj, name, value): verify(hasattr(obj, name)) # Otherwise it's probably a typo try: setattr(obj, name, value) except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't be able to set %s to %r" % (name, value) try: delattr(obj, name) except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't be able to del %s" % name
8,565
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0) table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
8,566
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
8,567
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
8,568
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
8,569
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
def maketable(): decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i unicode = UnicodeData(UNICODE_DATA) decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i DECOMPOSITION = [""] decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i FILE = "unicodedata_db.h" decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i sys.stdout = open(FILE, "w") decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i {%d, %d, %d, %d, %s}," % item print "};" print decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i \"%s\"," % name print " decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i NULL" print "};" decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i \"%s\"," % name print " decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i NULL" print "};" decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i # split index table index1, index2, shift = splitbins(index) decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) decomp_data = [""] decomp_index = [0] * len(unicode.chars) for char in unicode.chars: record = unicode.table[char] if record: if record[5]: try: i = decomp_data.index(record[5]) except ValueError: i = len(decomp_data) decomp_data.append(record[5]) else: i = 0 decomp_index[char] = i sys.stdout = sys.__stdout__
8,570
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d, %s}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
def maketable(): unicode = UnicodeData(UNICODE_DATA) # extract unicode properties dummy = (0, 0, 0, 0, "NULL") table = [dummy] cache = {0: dummy} index = [0] * len(unicode.chars) DECOMPOSITION = [""] for char in unicode.chars: record = unicode.table[char] if record: # extract database properties category = CATEGORY_NAMES.index(record[2]) combining = int(record[3]) bidirectional = BIDIRECTIONAL_NAMES.index(record[4]) mirrored = record[9] == "Y" if record[5]: decomposition = '"%s"' % record[5] else: decomposition = "NULL" item = ( category, combining, bidirectional, mirrored, decomposition ) # add entry to index and item tables i = cache.get(item) if i is None: cache[item] = i = len(table) table.append(item) index[char] = i # FIXME: we really should compress the decomposition stuff # (see the unidb utilities for one way to do this) FILE = "unicodedata_db.h" sys.stdout = open(FILE, "w") print "/* this file was generated by %s %s */" % (SCRIPT, VERSION) print print "/* a list of unique database records */" print "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {" for item in table: print " {%d, %d, %d, %d}," % item print "};" print print "/* string literals */" print "const char *_PyUnicode_CategoryNames[] = {" for name in CATEGORY_NAMES: print " \"%s\"," % name print " NULL" print "};" print "const char *_PyUnicode_BidirectionalNames[] = {" for name in BIDIRECTIONAL_NAMES: print " \"%s\"," % name print " NULL" print "};" # split index table index1, index2, shift = splitbins(index) print "/* index tables used to find the right database record */" print "#define SHIFT", shift Array("index1", index1).dump(sys.stdout) Array("index2", index2).dump(sys.stdout) sys.stdout = sys.__stdout__
8,571
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')
8,572
def finalize_options (self): from distutils import sysconfig
def finalize_options (self): from distutils import sysconfig
8,573
def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)]
def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)]
8,574
def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)]
def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [("x", c_int), ("y", c_char)]
8,575
def quitevent(self, theAppleEvent, theReply): from Carbon import AE AE.AEInteractWithUser(50000000) self._quit()
def quitevent(self, theAppleEvent, theReply): self._quit()
8,576
def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception, exc: if str(exc) == excmsg: if verbose: print "yes" else: if verbose: print 'no' print 'Unexpected ', exception, ':', repr(str(exc)) except: if verbose: print 'no' print 'Unexpected exception' raise else: raise TestFailed, 'did not get expected exception: %s' % excmsg
def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception, exc: if str(exc) == excmsg: if verbose: print "yes" else: if verbose: print 'no' print 'Unexpected ', exception, ':', repr(str(exc)) except: if verbose: print 'no' print 'Unexpected exception' raise else: raise TestFailed, 'did not get expected exception: %s' % excmsg
8,577
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)
8,578
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)
8,579
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)
8,580
def addsitedir(sitedir): sitedir, sitedircase = makepath(sitedir) if not dirs_in_sys_path.has_key(sitedircase): sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return names.sort() for name in names: if name[-4:] == endsep + "pth": addpackage(sitedir, name)
def addsitedir(sitedir): sitedir, sitedircase = makepath(sitedir) if not _dirs_in_sys_path.has_key(sitedircase): sys.path.append(sitedir) # Add path component try: names = os.listdir(sitedir) except os.error: return names.sort() for name in names: if name[-4:] == endsep + "pth": addpackage(sitedir, name)
8,581
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not _dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
8,582
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) dirs_in_sys_path[dircase] = 1
def addpackage(sitedir, name): fullname = os.path.join(sitedir, name) try: f = open(fullname) except IOError: return while 1: dir = f.readline() if not dir: break if dir[0] == '#': continue if dir.startswith("import"): exec dir continue if dir[-1] == '\n': dir = dir[:-1] dir, dircase = makepath(sitedir, dir) if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir): sys.path.append(dir) _dirs_in_sys_path[dircase] = 1 if reset: _dirs_in_sys_path = None
8,583
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer is None: try: importer = ImpImporter(path_item) except ImportError: pass return importer
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer in (None, True, False): try: importer = ImpImporter(path_item) except ImportError: pass return importer
8,584
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer is None: try: importer = ImpImporter(path_item) except ImportError: pass return importer
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: importer = None else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer is None: try: importer = ImpImporter(path_item) except ImportError: importer = None return importer
8,585
def cmp(f1, f2): # Compare two files, use the cache if possible. # Return 1 for identical files, 0 for different. # Raise exceptions if either file could not be statted, read, etc. s1, s2 = sig(os.stat(f1)), sig(os.stat(f2)) if s1[0] <> 8 or s2[0] <> 8: # Either is a not a plain file -- always report as different return 0 if s1 == s2: # type, size & mtime match -- report same return 1 if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother # types or sizes differ -- report different return 0 # same type and size -- look in the cache key = (f1, f2) try: cs1, cs2, outcome = cache[key] # cache hit if s1 == cs1 and s2 == cs2: # cached signatures match return outcome # stale cached signature(s) except KeyError: # cache miss pass # really compare outcome = do_cmp(f1, f2) cache[key] = s1, s2, outcome return outcome
def cmp(f1, f2, shallow=1): # Compare two files, use the cache if possible. # Return 1 for identical files, 0 for different. # Raise exceptions if either file could not be statted, read, etc. s1, s2 = sig(os.stat(f1)), sig(os.stat(f2)) if s1[0] <> 8 or s2[0] <> 8: # Either is a not a plain file -- always report as different return 0 if s1 == s2: # type, size & mtime match -- report same return 1 if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother # types or sizes differ -- report different return 0 # same type and size -- look in the cache key = (f1, f2) try: cs1, cs2, outcome = cache[key] # cache hit if s1 == cs1 and s2 == cs2: # cached signatures match return outcome # stale cached signature(s) except KeyError: # cache miss pass # really compare outcome = do_cmp(f1, f2) cache[key] = s1, s2, outcome return outcome
8,586
def cmp(f1, f2): # Compare two files, use the cache if possible. # Return 1 for identical files, 0 for different. # Raise exceptions if either file could not be statted, read, etc. s1, s2 = sig(os.stat(f1)), sig(os.stat(f2)) if s1[0] <> 8 or s2[0] <> 8: # Either is a not a plain file -- always report as different return 0 if s1 == s2: # type, size & mtime match -- report same return 1 if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother # types or sizes differ -- report different return 0 # same type and size -- look in the cache key = (f1, f2) try: cs1, cs2, outcome = cache[key] # cache hit if s1 == cs1 and s2 == cs2: # cached signatures match return outcome # stale cached signature(s) except KeyError: # cache miss pass # really compare outcome = do_cmp(f1, f2) cache[key] = s1, s2, outcome return outcome
def cmp(f1, f2): # Compare two files, use the cache if possible. # Return 1 for identical files, 0 for different. # Raise exceptions if either file could not be statted, read, etc. s1, s2 = sig(os.stat(f1)), sig(os.stat(f2)) if s1[0] <> 8 or s2[0] <> 8: # Either is a not a plain file -- always report as different return 0 if shallow and s1 == s2: # type, size & mtime match -- report same return 1 if s1[:2] <> s2[:2]: # Types or sizes differ, don't bother # types or sizes differ -- report different return 0 # same type and size -- look in the cache key = (f1, f2) try: cs1, cs2, outcome = cache[key] # cache hit if s1 == cs1 and s2 == cs2: # cached signatures match return outcome # stale cached signature(s) except KeyError: # cache miss pass # really compare outcome = do_cmp(f1, f2) cache[key] = s1, s2, outcome return outcome
8,587
_s = "def %s(self, *args): return self._sock.%s(*args)\n\n"
_s = "def %s(self, *args): return self._sock.%s(*args)\n\n"
8,588
def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self._mode = mode if bufsize <= 0: if bufsize == 0: bufsize = 1 # Unbuffered mode else: bufsize = 8192 self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = [ ] self._wbuf = [ ]
def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self._mode = mode if bufsize <= 0: if bufsize == 0: bufsize = 1 # Unbuffered mode else: bufsize = 8192 self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = [ ] self._wbuf = [ ]
8,589
def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self._mode = mode if bufsize <= 0: if bufsize == 0: bufsize = 1 # Unbuffered mode else: bufsize = 8192 self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = [ ] self._wbuf = [ ]
def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self._mode = mode if bufsize <= 0: if bufsize == 0: bufsize = 1 # Unbuffered mode else: bufsize = 8192 self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = [ ] self._wbuf = [ ]
8,590
def flush(self): if self._wbuf: buffer = ''.join(self._wbuf) self._sock.sendall(buffer) self._wbuf = [ ]
def flush(self): if self._wbuf: buffer = "".join(self._wbuf) self._wbuf = [] self._sock.sendall(buffer) self._wbuf = [ ]
8,591
def flush(self): if self._wbuf: buffer = ''.join(self._wbuf) self._sock.sendall(buffer) self._wbuf = [ ]
def flush(self): if self._wbuf: buffer = ''.join(self._wbuf) self._sock.sendall(buffer) self._wbuf = [ ]
8,592
def write(self, data): self._wbuf.append (data) # A _wbufsize of 1 means we're doing unbuffered IO. # Flush accordingly. if self._wbufsize == 1: if '\n' in data: self.flush () elif self.__get_wbuf_len() >= self._wbufsize: self.flush()
def write(self, data): self._wbuf.append (data) # A _wbufsize of 1 means we're doing unbuffered IO. # Flush accordingly. if self._wbufsize == 1: if '\n' in data: self.flush () elif self.__get_wbuf_len() >= self._wbufsize: self.flush()
8,593
def writelines(self, list): filter(self._sock.sendall, list) self.flush()
def writelines(self, list): filter(self._sock.sendall, list) self.flush()
8,594
def __get_wbuf_len (self): buf_len = 0 for i in [len(x) for x in self._wbuf]: buf_len += i return buf_len
def __get_wbuf_len (self): buf_len = 0 for x in self._wbuf: buf_len += len(x) return buf_len
8,595
def __get_rbuf_len(self): buf_len = 0 for i in [len(x) for x in self._rbuf]: buf_len += i return buf_len
def _get_rbuf_len(self): buf_len = 0 for i in [len(x) for x in self._rbuf]: buf_len += i return buf_len
8,596
def __get_rbuf_len(self): buf_len = 0 for i in [len(x) for x in self._rbuf]: buf_len += i return buf_len
def __get_rbuf_len(self): buf_len = 0 for x in self._rbuf: buf_len += len(x) return buf_len
8,597
def read(self, size=-1): buf_len = self.__get_rbuf_len() while size < 0 or buf_len < size: recv_size = max(self._rbufsize, size - buf_len) data = self._sock.recv(recv_size) if not data: break buf_len += len(data) self._rbuf.append(data) # Clear the rbuf at the end so we're not affected by # an exception during a recv data = ''.join(self._rbuf) self._rbuf = [ ] if buf_len > size and size >= 0: self._rbuf.append(data[size:]) data = data[:size] return data
def read(self, size=-1): buf_len = self.__get_rbuf_len() while size < 0 or buf_len < size: recv_size = max(self._rbufsize, size - buf_len) data = self._sock.recv(recv_size) if not data: break buf_len += len(data) self._rbuf.append(data) # Clear the rbuf at the end so we're not affected by # an exception during a recv data = ''.join(self._rbuf) self._rbuf = [ ] if buf_len > size and size >= 0: self._rbuf.append(data[size:]) data = data[:size] return data
8,598
def readline(self, size=-1): index = -1 buf_len = self.__get_rbuf_len() if self._rbuf: index = min([x.find('\n') for x in self._rbuf]) while index < 0 and (size < 0 or buf_len < size): recv_size = max(self._rbufsize, size - buf_len) data = self._sock.recv(recv_size) if not data: break buf_len += len(data) self._rbuf.append(data) index = data.find('\n') data = ''.join(self._rbuf) self._rbuf = [ ] index = data.find('\n') if index >= 0: index += 1 elif buf_len > size: index = size else: index = buf_len self._rbuf.append(data[index:]) data = data[:index] return data
def readline(self, size=-1): data_len = 0 for index, x in enumerate(self._rbuf): data_len += len(x) if '\n' in x or 0 <= size <= data_len: index += 1 data = "".join(self._rbuf[:index]) end = data.find('\n') if end < 0: end = len(data) else: end += 1 if 0 <= size < end: end = size data, rest = data[:end], data[end:] if rest: self._rbuf[:index] = [rest] else: del self._rbuf[:index] return data recv_size = self._rbufsize while 1: if size >= 0: recv_size = min(self._rbufsize, size - data_len) x = self._sock.recv(recv_size) if not x: break data_len += len(x) self._rbuf.append(x) if '\n' in x or 0 <= size <= data_len: break data = "".join(self._rbuf) end = data.find('\n') if end < 0: end = len(data) else: end += 1 if 0 <= size < end: end = size data, rest = data[:end], data[end:] if rest: self._rbuf = [rest] else: self._rbuf = [] return data
8,599