_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q280500
HasTraits.trait_metadata
test
def trait_metadata(self, traitname, key): """Get metadata values for trait by key.""" try: trait = getattr(self.__class__, traitname) except AttributeError: raise TraitError("Class %s does not have a trait named %s" % (self.__class__.__name...
python
{ "resource": "" }
q280501
Type.validate
test
def validate(self, obj, value): """Validates that the value is a valid object instance.""" try: if issubclass(value, self.klass): return value except: if (value is None) and (self._allow_none): return value self.error(obj, value)
python
{ "resource": "" }
q280502
Instance.get_default_value
test
def get_default_value(self): """Instantiate a default value instance. This is called when the containing HasTraits classes' :meth:`__new__` method is called to ensure that a unique instance is created for each HasTraits instance. """ dv = self.default_value if i...
python
{ "resource": "" }
q280503
Dependency.check
test
def check(self, completed, failed=None): """check whether our dependencies have been met.""" if len(self) == 0: return True against = set() if self.success: against = completed if failed is not None and self.failure: against = against.union(fai...
python
{ "resource": "" }
q280504
Dependency.unreachable
test
def unreachable(self, completed, failed=None): """return whether this dependency has become impossible.""" if len(self) == 0: return False against = set() if not self.success: against = completed if failed is not None and not self.failure: agai...
python
{ "resource": "" }
q280505
Dependency.as_dict
test
def as_dict(self): """Represent this dependency as a dict. For json compatibility.""" return dict( dependencies=list(self), all=self.all, success=self.success, failure=self.failure )
python
{ "resource": "" }
q280506
depth
test
def depth(n, tree): """get depth of an element in the tree""" d = 0 parent = tree[n] while parent is not None: d += 1 parent = tree[parent] return d
python
{ "resource": "" }
q280507
print_bintree
test
def print_bintree(tree, indent=' '): """print a binary tree""" for n in sorted(tree.keys()): print "%s%s" % (indent * depth(n,tree), n)
python
{ "resource": "" }
q280508
disambiguate_dns_url
test
def disambiguate_dns_url(url, location): """accept either IP address or dns name, and return IP""" if not ip_pat.match(location): location = socket.gethostbyname(location) return disambiguate_url(url, location)
python
{ "resource": "" }
q280509
BinaryTreeCommunicator.allreduce
test
def allreduce(self, f, value, flat=True): """parallel reduce followed by broadcast of the result""" return self.reduce(f, value, flat=flat, all=True)
python
{ "resource": "" }
q280510
Hub._validate_targets
test
def _validate_targets(self, targets): """turn any valid targets argument into a list of integer ids""" if targets is None: # default to all return self.ids if isinstance(targets, (int,str,unicode)): # only one target specified targets = [targets] ...
python
{ "resource": "" }
q280511
Hub.dispatch_monitor_traffic
test
def dispatch_monitor_traffic(self, msg): """all ME and Task queue messages come through here, as well as IOPub traffic.""" self.log.debug("monitor traffic: %r", msg[0]) switch = msg[0] try: idents, msg = self.session.feed_identities(msg[1:]) except ValueError:...
python
{ "resource": "" }
q280512
Hub.dispatch_query
test
def dispatch_query(self, msg): """Route registration requests and queries from clients.""" try: idents, msg = self.session.feed_identities(msg) except ValueError: idents = [] if not idents: self.log.error("Bad Query Message: %r", msg) retur...
python
{ "resource": "" }
q280513
Hub.handle_new_heart
test
def handle_new_heart(self, heart): """handler to attach to heartbeater. Called when a new heart starts to beat. Triggers completion of registration.""" self.log.debug("heartbeat::handle_new_heart(%r)", heart) if heart not in self.incoming_registrations: self.log.info(...
python
{ "resource": "" }
q280514
Hub.handle_heart_failure
test
def handle_heart_failure(self, heart): """handler to attach to heartbeater. called when a previously registered heart fails to respond to beat request. triggers unregistration""" self.log.debug("heartbeat::handle_heart_failure(%r)", heart) eid = self.hearts.get(heart, None) ...
python
{ "resource": "" }
q280515
Hub.save_task_request
test
def save_task_request(self, idents, msg): """Save the submission of a task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::client %r sent invalid task message: %r", client_id, msg, exc...
python
{ "resource": "" }
q280516
Hub.save_task_result
test
def save_task_result(self, idents, msg): """save the result of a completed task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::invalid task result message send to %r: %r", client_id, m...
python
{ "resource": "" }
q280517
Hub.save_iopub_message
test
def save_iopub_message(self, topics, msg): """save an iopub message into the db""" # print (topics) try: msg = self.session.unserialize(msg, content=True) except Exception: self.log.error("iopub::invalid IOPub message", exc_info=True) return p...
python
{ "resource": "" }
q280518
Hub.connection_request
test
def connection_request(self, client_id, msg): """Reply with connection addresses for clients.""" self.log.info("client::client %r connected", client_id) content = dict(status='ok') content.update(self.client_info) jsonable = {} for k,v in self.keytable.iteritems(): ...
python
{ "resource": "" }
q280519
Hub.register_engine
test
def register_engine(self, reg, msg): """Register a new engine.""" content = msg['content'] try: queue = cast_bytes(content['queue']) except KeyError: self.log.error("registration::queue not specified", exc_info=True) return heart = content.get(...
python
{ "resource": "" }
q280520
Hub.unregister_engine
test
def unregister_engine(self, ident, msg): """Unregister an engine that explicitly requested to leave.""" try: eid = msg['content']['id'] except: self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True) return self.log.i...
python
{ "resource": "" }
q280521
Hub.finish_registration
test
def finish_registration(self, heart): """Second half of engine registration, called after our HeartMonitor has received a beat from the Engine's Heart.""" try: (eid,queue,reg,purge) = self.incoming_registrations.pop(heart) except KeyError: self.log.error("registra...
python
{ "resource": "" }
q280522
Hub.shutdown_request
test
def shutdown_request(self, client_id, msg): """handle shutdown request.""" self.session.send(self.query, 'shutdown_reply', content={'status': 'ok'}, ident=client_id) # also notify other clients of shutdown self.session.send(self.notifier, 'shutdown_notice', content={'status': 'ok'}) ...
python
{ "resource": "" }
q280523
Hub.purge_results
test
def purge_results(self, client_id, msg): """Purge results from memory. This method is more valuable before we move to a DB based message storage mechanism.""" content = msg['content'] self.log.info("Dropping records with %s", content) msg_ids = content.get('msg_ids', []) ...
python
{ "resource": "" }
q280524
Hub._extract_record
test
def _extract_record(self, rec): """decompose a TaskRecord dict into subsection of reply for get_result""" io_dict = {} for key in ('pyin', 'pyout', 'pyerr', 'stdout', 'stderr'): io_dict[key] = rec[key] content = { 'result_content': rec['result_content'], ...
python
{ "resource": "" }
q280525
Hub.get_results
test
def get_results(self, client_id, msg): """Get the result of 1 or more messages.""" content = msg['content'] msg_ids = sorted(set(content['msg_ids'])) statusonly = content.get('status_only', False) pending = [] completed = [] content = dict(status='ok') con...
python
{ "resource": "" }
q280526
Hub.get_history
test
def get_history(self, client_id, msg): """Get a list of all msg_ids in our DB records""" try: msg_ids = self.db.get_history() except Exception as e: content = error.wrap_exception() else: content = dict(status='ok', history=msg_ids) self.sessi...
python
{ "resource": "" }
q280527
Hub.db_query
test
def db_query(self, client_id, msg): """Perform a raw query on the task record database.""" content = msg['content'] query = content.get('query', {}) keys = content.get('keys', None) buffers = [] empty = list() try: records = self.db.find_records(query,...
python
{ "resource": "" }
q280528
Rscript.cd
test
def cd(self, newdir): """ go to the path """ prevdir = os.getcwd() os.chdir(newdir) try: yield finally: os.chdir(prevdir)
python
{ "resource": "" }
q280529
Rscript.decode_cmd_out
test
def decode_cmd_out(self, completed_cmd): """ return a standard message """ try: stdout = completed_cmd.stdout.encode('utf-8').decode() except AttributeError: try: stdout = str(bytes(completed_cmd.stdout), 'big5').strip() except ...
python
{ "resource": "" }
q280530
Rscript.run_command_under_r_root
test
def run_command_under_r_root(self, cmd, catched=True): """ subprocess run on here """ RPATH = self.path with self.cd(newdir=RPATH): if catched: process = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE) else: process = sp.run(cmd...
python
{ "resource": "" }
q280531
Rscript.execute
test
def execute(self): """ Execute R script """ rprocess = OrderedDict() commands = OrderedDict([ (self.file, ['Rscript', self.file] + self.cmd), ]) for cmd_name, cmd in commands.items(): rprocess[cmd_name] = self.run_command_under_r_root(cmd) ...
python
{ "resource": "" }
q280532
BaseFrontendMixin._dispatch
test
def _dispatch(self, msg): """ Calls the frontend handler associated with the message type of the given message. """ msg_type = msg['header']['msg_type'] handler = getattr(self, '_handle_' + msg_type, None) if handler: handler(msg)
python
{ "resource": "" }
q280533
BaseFrontendMixin._is_from_this_session
test
def _is_from_this_session(self, msg): """ Returns whether a reply from the kernel originated from a request from this frontend. """ session = self._kernel_manager.session.session parent = msg['parent_header'] if not parent: # if the message has no parent, ...
python
{ "resource": "" }
q280534
AnnotateReporter.report
test
def report(self, morfs, directory=None): """Run the report. See `coverage.report()` for arguments. """ self.report_files(self.annotate_file, morfs, directory)
python
{ "resource": "" }
q280535
AnnotateReporter.annotate_file
test
def annotate_file(self, cu, analysis): """Annotate a single file. `cu` is the CodeUnit for the file to annotate. """ if not cu.relative: return filename = cu.filename source = cu.source_file() if self.directory: dest_file = os.path.join(...
python
{ "resource": "" }
q280536
get_installed_version
test
def get_installed_version(name): ''' returns installed package version and None if package is not installed ''' pattern = re.compile(r'''Installed:\s+(?P<version>.*)''') cmd = 'apt-cache policy %s' % name args = shlex.split(cmd) try: output = subprocess.check_output(args) ...
python
{ "resource": "" }
q280537
squash_unicode
test
def squash_unicode(obj): """coerce unicode back to bytestrings.""" if isinstance(obj,dict): for key in obj.keys(): obj[key] = squash_unicode(obj[key]) if isinstance(key, unicode): obj[squash_unicode(key)] = obj.pop(key) elif isinstance(obj, list): for ...
python
{ "resource": "" }
q280538
extract_header
test
def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header['header'] except KeyError: try: # See if msg_or_header is just the heade...
python
{ "resource": "" }
q280539
Session._check_packers
test
def _check_packers(self): """check packers for binary data and datetime support.""" pack = self.pack unpack = self.unpack # check simple serialization msg = dict(a=[1,'hi']) try: packed = pack(msg) except Exception: raise ValueError("packe...
python
{ "resource": "" }
q280540
Session.msg
test
def msg(self, msg_type, content=None, parent=None, subheader=None, header=None): """Return the nested message dict. This format is different from what is sent over the wire. The serialize/unserialize methods converts this nested message dict to the wire format, which is a list of messag...
python
{ "resource": "" }
q280541
Session.sign
test
def sign(self, msg_list): """Sign a message with HMAC digest. If no auth, return b''. Parameters ---------- msg_list : list The [p_header,p_parent,p_content] part of the message list. """ if self.auth is None: return b'' h = self.auth.copy...
python
{ "resource": "" }
q280542
Session.serialize
test
def serialize(self, msg, ident=None): """Serialize the message components to bytes. This is roughly the inverse of unserialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parame...
python
{ "resource": "" }
q280543
Session.send
test
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, subheader=None, track=False, header=None): """Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_...
python
{ "resource": "" }
q280544
Session.send_raw
test
def send_raw(self, stream, msg_list, flags=0, copy=True, ident=None): """Send a raw message via ident path. This method is used to send a already serialized message. Parameters ---------- stream : ZMQStream or Socket The ZMQ stream or socket to use for sending the m...
python
{ "resource": "" }
q280545
Session.recv
test
def recv(self, socket, mode=zmq.NOBLOCK, content=True, copy=True): """Receive and unpack a message. Parameters ---------- socket : ZMQStream or Socket The socket or stream to use in receiving. Returns ------- [idents], msg [idents] is a l...
python
{ "resource": "" }
q280546
Session.feed_identities
test
def feed_identities(self, msg_list, copy=True): """Split the identities from the rest of the message. Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly. Parameters...
python
{ "resource": "" }
q280547
Session.unserialize
test
def unserialize(self, msg_list, content=True, copy=True): """Unserialize a msg_list to a nested message dict. This is roughly the inverse of serialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the messa...
python
{ "resource": "" }
q280548
save_svg
test
def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. Parameters: ----------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns: -------- The name ...
python
{ "resource": "" }
q280549
svg_to_clipboard
test
def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document. """ if isinstance(string, unicode): string = string.encode('utf-8') mime_data = QtCore.QMimeData() mime_data.se...
python
{ "resource": "" }
q280550
svg_to_image
test
def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. Parameters: ----------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default si...
python
{ "resource": "" }
q280551
object_info
test
def object_info(**kw): """Make an object info dict with all fields present.""" infodict = dict(izip_longest(info_fields, [None])) infodict.update(kw) return infodict
python
{ "resource": "" }
q280552
getdoc
test
def getdoc(obj): """Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipy...
python
{ "resource": "" }
q280553
getsource
test
def getsource(obj,is_binary=False): """Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to co...
python
{ "resource": "" }
q280554
getargspec
test
def getargspec(obj): """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. 'def...
python
{ "resource": "" }
q280555
call_tip
test
def call_tip(oinfo, format_call=True): """Extract call tip data from an oinfo dict. Parameters ---------- oinfo : dict format_call : bool, optional If True, the call line is formatted and returned as a string. If not, a tuple of (name, argspec) is returned. Returns ------- ...
python
{ "resource": "" }
q280556
find_file
test
def find_file(obj): """Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absol...
python
{ "resource": "" }
q280557
find_source_lines
test
def find_source_lines(obj): """Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int ...
python
{ "resource": "" }
q280558
Inspector._getdef
test
def _getdef(self,obj,oname=''): """Return the definition header for any callable object. If any exception is generated, None is returned instead and the exception is suppressed.""" try: # We need a plain string here, NOT unicode! hdef = oname + inspect.formatarg...
python
{ "resource": "" }
q280559
Inspector.__head
test
def __head(self,h): """Return a header string with proper colors.""" return '%s%s%s' % (self.color_table.active_colors.header,h, self.color_table.active_colors.normal)
python
{ "resource": "" }
q280560
Inspector.noinfo
test
def noinfo(self, msg, oname): """Generic message when no information is found.""" print 'No %s found' % msg, if oname: print 'for %s' % oname else: print
python
{ "resource": "" }
q280561
Inspector.pdef
test
def pdef(self, obj, oname=''): """Print the definition header for any callable object. If the object is a class, print the constructor information.""" if not callable(obj): print 'Object is not callable.' return header = '' if inspect.isclass(obj): ...
python
{ "resource": "" }
q280562
Inspector.pdoc
test
def pdoc(self,obj,oname='',formatter = None): """Print the docstring for any object. Optional: -formatter: a function to run the docstring through for specially formatted docstrings. Examples -------- In [1]: class NoInit: ...: pass In [...
python
{ "resource": "" }
q280563
Inspector.psource
test
def psource(self,obj,oname=''): """Print the source code for an object.""" # Flush the source cache because inspect can return out-of-date source linecache.checkcache() try: src = getsource(obj) except: self.noinfo('source',oname) else: ...
python
{ "resource": "" }
q280564
Inspector.pfile
test
def pfile(self, obj, oname=''): """Show the whole file where an object was defined.""" lineno = find_source_lines(obj) if lineno is None: self.noinfo('file', oname) return ofile = find_file(obj) # run contents of file through pager starting at li...
python
{ "resource": "" }
q280565
Inspector._format_fields
test
def _format_fields(self, fields, title_width=12): """Formats a list of fields for display. Parameters ---------- fields : list A list of 2-tuples: (field_title, field_content) title_width : int How many characters to pad titles to. Default 12. """ ...
python
{ "resource": "" }
q280566
Inspector.pinfo
test
def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): """Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some...
python
{ "resource": "" }
q280567
Inspector.psearch
test
def psearch(self,pattern,ns_table,ns_search=[], ignore_case=False,show_all=False): """Search namespaces with wildcards for objects. Arguments: - pattern: string containing shell-like wildcards to use in namespace searches and optionally a type specification to narrow th...
python
{ "resource": "" }
q280568
threaded_reactor
test
def threaded_reactor(): """ Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done. """ global _twisted_thread try: from twisted.internet import reactor except ImportError: ...
python
{ "resource": "" }
q280569
deferred
test
def deferred(timeout=None): """ By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration o...
python
{ "resource": "" }
q280570
find_best_string
test
def find_best_string(query, corpus, step=4, flex=3, case_sensitive=False): """Return best matching substring of corpus. Parameters ---------- query : str corpus : str step : int Step size of first match-...
python
{ "resource": "" }
q280571
XMLEncoder.to_string
test
def to_string(self, indent=True, declaration=True): """Encodes the stored ``data`` to XML and returns a ``string``. Setting ``indent`` to ``False`` will forego any pretty-printing and return a condensed value. Setting ``declaration`` to ``False`` will skip inserting the ...
python
{ "resource": "" }
q280572
XMLEncoder.to_xml
test
def to_xml(self): """Encodes the stored ``data`` to XML and returns an ``lxml.etree`` value. """ if self.data: self.document = self._update_document(self.document, self.data) return self.document
python
{ "resource": "" }
q280573
load_all_modules_in_packages
test
def load_all_modules_in_packages(package_or_set_of_packages): """ Recursively loads all modules from a package object, or set of package objects :param package_or_set_of_packages: package object, or iterable of package objects :return: list of all unique modules discovered by the function """ i...
python
{ "resource": "" }
q280574
Struct.__dict_invert
test
def __dict_invert(self, data): """Helper function for merge. Takes a dictionary whose values are lists and returns a dict with the elements of each list as keys and the original keys as values. """ outdict = {} for k,lst in data.items(): if isinstance(lst, st...
python
{ "resource": "" }
q280575
Struct.merge
test
def merge(self, __loc_data__=None, __conflict_solve=None, **kw): """Merge two Structs with customizable conflict resolution. This is similar to :meth:`update`, but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional...
python
{ "resource": "" }
q280576
object_to_primitive
test
def object_to_primitive(obj): ''' convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ''' if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isin...
python
{ "resource": "" }
q280577
Parser.format2
test
def format2(self, raw, out = None, scheme = ''): """ Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string 'str' and the parser will auto...
python
{ "resource": "" }
q280578
getfigs
test
def getfigs(*fig_nums): """Get a list of matplotlib figures by figure numbers. If no arguments are given, all available figures are returned. If the argument list contains references to invalid figures, a warning is printed but the function continues pasting further figures. Parameters ------...
python
{ "resource": "" }
q280579
print_figure
test
def print_figure(fig, fmt='png'): """Convert a figure to svg or png for inline display.""" # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return fc = fig.get_facecolor() ec = fig.get_...
python
{ "resource": "" }
q280580
mpl_runner
test
def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use a...
python
{ "resource": "" }
q280581
select_figure_format
test
def select_figure_format(shell, fmt): """Select figure format for inline backend, either 'png' or 'svg'. Using this method ensures only one figure format is active at a time. """ from matplotlib.figure import Figure from IPython.zmq.pylab import backend_inline svg_formatter = shell.display_for...
python
{ "resource": "" }
q280582
find_gui_and_backend
test
def find_gui_and_backend(gui=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','...
python
{ "resource": "" }
q280583
activate_matplotlib
test
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib if backend.startswith('module://'): # Work around bug in matplotlib: matplotlib.use converts the # backend_id to lowercase even if a module name is specified! matplotlib...
python
{ "resource": "" }
q280584
configure_inline_support
test
def configure_inline_support(shell, backend, user_ns=None): """Configure an IPython shell object for matplotlib use. Parameters ---------- shell : InteractiveShell instance backend : matplotlib backend user_ns : dict A namespace where all configured variables will be placed. If not giv...
python
{ "resource": "" }
q280585
pylab_activate
test
def pylab_activate(user_ns, gui=None, import_all=True, shell=None): """Activate pylab mode in the user's namespace. Loads and initializes numpy, matplotlib and friends for interactive use. Parameters ---------- user_ns : dict Namespace where the imports will occur. gui : optional, strin...
python
{ "resource": "" }
q280586
PyTracer._trace
test
def _trace(self, frame, event, arg_unused): """The trace function passed to sys.settrace.""" if self.stopped: return if 0: sys.stderr.write("trace event: %s %r @%d\n" % ( event, frame.f_code.co_filename, frame.f_lineno )) if self.las...
python
{ "resource": "" }
q280587
PyTracer.start
test
def start(self): """Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.thread = threading.currentThread() sys.settrace(self._trace) return self._trace
python
{ "resource": "" }
q280588
PyTracer.stop
test
def stop(self): """Stop this Tracer.""" self.stopped = True if self.thread != threading.currentThread(): # Called on a different thread than started us: we can't unhook # ourseves, but we've set the flag that we should stop, so we won't # do any more tracing. ...
python
{ "resource": "" }
q280589
Collector._start_tracer
test
def _start_tracer(self): """Start a new Tracer object, and store it in self.tracers.""" tracer = self._trace_class() tracer.data = self.data tracer.arcs = self.branch tracer.should_trace = self.should_trace tracer.should_trace_cache = self.should_trace_cache trace...
python
{ "resource": "" }
q280590
Collector._installation_trace
test
def _installation_trace(self, frame_unused, event_unused, arg_unused): """Called on new threads, installs the real tracer.""" # Remove ourselves as the trace function sys.settrace(None) # Install the real tracer. fn = self._start_tracer() # Invoke the real trace function ...
python
{ "resource": "" }
q280591
Collector.start
test
def start(self): """Start collecting trace information.""" if self._collectors: self._collectors[-1].pause() self._collectors.append(self) #print("Started: %r" % self._collectors, file=sys.stderr) # Check to see whether we had a fullcoverage tracer installed. ...
python
{ "resource": "" }
q280592
Collector.stop
test
def stop(self): """Stop collecting trace information.""" #print >>sys.stderr, "Stopping: %r" % self._collectors assert self._collectors assert self._collectors[-1] is self self.pause() self.tracers = [] # Remove this Collector from the stack, and resume the one ...
python
{ "resource": "" }
q280593
Collector.pause
test
def pause(self): """Pause tracing, but be prepared to `resume`.""" for tracer in self.tracers: tracer.stop() stats = tracer.get_stats() if stats: print("\nCoverage.py tracer stats:") for k in sorted(stats.keys()): pr...
python
{ "resource": "" }
q280594
Collector.resume
test
def resume(self): """Resume tracing after a `pause`.""" for tracer in self.tracers: tracer.start() threading.settrace(self._installation_trace)
python
{ "resource": "" }
q280595
Collector.get_line_data
test
def get_line_data(self): """Return the line data collected. Data is { filename: { lineno: None, ...}, ...} """ if self.branch: # If we were measuring branches, then we have to re-build the dict # to show line data. line_data = {} for f, a...
python
{ "resource": "" }
q280596
collect_exceptions
test
def collect_exceptions(rdict_or_list, method='unspecified'): """check a result dict for errors, and raise CompositeError if any exist. Passthrough otherwise.""" elist = [] if isinstance(rdict_or_list, dict): rlist = rdict_or_list.values() else: rlist = rdict_or_list for r in rlis...
python
{ "resource": "" }
q280597
CompositeError.render_traceback
test
def render_traceback(self, excid=None): """render one or all of my tracebacks to a list of lines""" lines = [] if excid is None: for (en,ev,etb,ei) in self.elist: lines.append(self._get_engine_str(ei)) lines.extend((etb or 'No traceback available').spl...
python
{ "resource": "" }
q280598
process_startup
test
def process_startup(): """Call this at Python startup to perhaps measure coverage. If the environment variable COVERAGE_PROCESS_START is defined, coverage measurement is started. The value of the variable is the config file to use. There are two ways to configure your Python installation to invok...
python
{ "resource": "" }
q280599
coverage._canonical_dir
test
def _canonical_dir(self, morf): """Return the canonical directory of the module or file `morf`.""" return os.path.split(CodeUnit(morf, self.file_locator).filename)[0]
python
{ "resource": "" }