Search is not available for this dataset
text
stringlengths
75
104k
def patch_transport_fake_push_producer(transport): """ Patch the three methods belonging to IPushProducer onto the transport if it doesn't already have them. (`Agent` assumes its transport has these.) """ patch_if_missing(transport, 'pauseProducing', lambda: None) patch_if_missing(transport, 're...
def patch_transport_abortConnection(transport, protocol): """ Patch abortConnection() onto the transport if it doesn't already have it. (`Agent` assumes its transport has this.) """ def abortConnection(): protocol._fake_connection_aborted = True transport.loseConnection() patch_i...
def accept_connection(self): """ Accept a pending connection. """ assert self.pending, "Connection is not pending." self.server_protocol = self.server.server_factory.buildProtocol(None) self._accept_d.callback( FakeServerProtocolWrapper(self, self.server_proto...
def reject_connection(self, reason=None): """ Reject a pending connection. """ assert self.pending, "Connection is not pending." if reason is None: reason = ConnectionRefusedError() self._accept_d.errback(reason)
def get_agent(self, reactor=None, contextFactory=None): """ Returns an IAgent that makes requests to this fake server. """ return ProxyAgentWithContext( self.endpoint, reactor=reactor, contextFactory=contextFactory)
def form_valid(self, form): """ Calls pre and post save hooks. """ self.object = form.save(commit=False) # Invoke pre_save hook, and allow it to abort the saving # process and do a redirect. response = self.pre_save(self.object) if response: r...
def delete(self, request, *args, **kwargs): """ Calls pre and post delete hooks for DelteViews. """ self.object = self.get_object() success_url = self.get_success_url() self.pre_delete(self.object) self.object.delete() self.post_delete(self.object) ...
def get_initial(self): """ Supply user object as initial data for the specified user_field(s). """ data = super(UserViewMixin, self).get_initial() for k in self.user_field: data[k] = self.request.user return data
def pre_save(self, instance): super(UserViewMixin, self).pre_save(instance) """ Use SaveHookMixin pre_save to set the user. """ if self.request.user.is_authenticated(): for field in self.user_field: setattr(instance, field, self.request.user)
def report(self, morfs, outfile=None): """Writes a report summarizing coverage statistics per module. `outfile` is a file object to write the summary to. """ self.find_code_units(morfs) # Prepare the formatting strings max_name = max([len(cu.name) for cu in self.code_u...
def _get_compiled_ext(): """Official way to get the extension of compiled files (.pyc or .pyo)""" for ext, mode, typ in imp.get_suffixes(): if typ == imp.PY_COMPILED: return ext
def update_class(old, new): """Replace stuff in the __dict__ of a class, and upgrade method code objects""" for key in old.__dict__.keys(): old_obj = getattr(old, key) try: new_obj = getattr(new, key) except AttributeError: # obsolete attribute: remove it ...
def check(self, check_all=False): """Check whether some modules need to be reloaded.""" if not self.enabled and not check_all: return if check_all or self.check_all: modules = sys.modules.keys() else: modules = self.modules.keys() for modnam...
def editor(self, filename, linenum=None, wait=True): """Open the default editor at the given filename and linenumber. This is IPython's default editor hook, you can use it as an example to write your own modified one. To set your own editor function as the new editor hook, call ip.set_hook('editor',yo...
def fix_error_editor(self,filename,linenum,column,msg): """Open the editor at the given filename, linenumber, column and show an error message. This is used for correcting syntax errors. The current implementation only has special support for the VIM editor, and falls back on the 'editor' hook if VIM is...
def clipboard_get(self): """ Get text from the clipboard. """ from IPython.lib.clipboard import ( osx_clipboard_get, tkinter_clipboard_get, win32_clipboard_get ) if sys.platform == 'win32': chain = [win32_clipboard_get, tkinter_clipboard_get] elif sys.platform == 'darwin'...
def add(self, func, priority=0): """ Add a func to the cmd chain with given priority """ self.chain.append((priority, func)) self.chain.sort(key=lambda x: x[0])
def get_metadata(path_or_module, metadata_version=None): """ Try to create a Distribution 'path_or_module'. o 'path_or_module' may be a module object. o If a string, 'path_or_module' may point to an sdist file, a bdist file, an installed package, or a working checkout (if it contains PKG-I...
def configure(self, options, conf): """Configure which kinds of exceptions trigger plugin. """ self.conf = conf self.enabled = options.debugErrors or options.debugFailures self.enabled_for_errors = options.debugErrors self.enabled_for_failures = options.debugFailures
def obfuscate(email, linktext=None, autoescape=None): """ Given a string representing an email address, returns a mailto link with rot13 JavaScript obfuscation. Accepts an optional argument to use as the link text; otherwise uses the email address itself. """ if autoescape: esc = co...
def roundplus(number): """ given an number, this fuction rounds the number as the following examples: 87 -> 87, 100 -> 100+, 188 -> 100+, 999 -> 900+, 1001 -> 1000+, ...etc """ num = str(number) if not num.isdigit(): return num num = str(number) digits = len(num) rounded = '...
def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original code for this was the following. We've left it # visible for now in case the new implementation shows any problems down # th...
def try_passwordless_ssh(server, keyfile, paramiko=None): """Attempt to make an ssh connection without a password. This is mainly used for requiring password input only once when many tunnels may be connected to the same server. If paramiko is None, the default for the platform is chosen. """ i...
def _try_passwordless_openssh(server, keyfile): """Try passwordless login with shell ssh command.""" if pexpect is None: raise ImportError("pexpect unavailable, use paramiko") cmd = 'ssh -f '+ server if keyfile: cmd += ' -i ' + keyfile cmd += ' exit' p = pexpect.spawn(cmd) wh...
def _try_passwordless_paramiko(server, keyfile): """Try passwordless login with paramiko.""" if paramiko is None: msg = "Paramiko unavaliable, " if sys.platform == 'win32': msg += "Paramiko is required for ssh tunneled connections on Windows." else: msg += "use Op...
def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60): """Connect a socket to an address via an ssh tunnel. This is a wrapper for socket.connect(addr), when addr is not accessible from the local machine. It simply creates an ssh tunnel using the remaining args...
def open_tunnel(addr, server, keyfile=None, password=None, paramiko=None, timeout=60): """Open a tunneled connection from a 0MQ url. For use inside tunnel_connection. Returns ------- (url, tunnel): The 0MQ url that has been forwarded, and the tunnel object """ lport = select_random_ports...
def openssh_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60): """Create an ssh tunnel using command-line ssh that connects port lport on this machine to localhost:rport on server. The tunnel will automatically close when not in use, remaining open for a minimu...
def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60): """launch a tunner with paramiko in a subprocess. This should only be used when shell ssh is unavailable (e.g. Windows). This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`, as ...
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None): """Function for actually starting a paramiko tunnel, to be passed to multiprocessing.Process(target=this), and not called directly. """ username, server, port = _split_server(server) client = paramiko.SSHClient() ...
def spin_first(f, self, *args, **kwargs): """Call spin() to sync state prior to calling the method.""" self.spin() return f(self, *args, **kwargs)
def _update_engines(self, engines): """Update our engines dict and _ids from a dict of the form: {id:uuid}.""" for k,v in engines.iteritems(): eid = int(k) self._engines[eid] = v self._ids.append(eid) self._ids = sorted(self._ids) if sorted(self._engin...
def _stop_scheduling_tasks(self): """Stop scheduling tasks because an engine has been unregistered from a pure ZMQ scheduler. """ self._task_socket.close() self._task_socket = None msg = "An engine has been unregistered, and we are using pure " +\ "ZMQ task ...
def _build_targets(self, targets): """Turn valid target IDs or 'all' into two lists: (int_ids, uuids). """ if not self._ids: # flush notification socket if no engines yet, just in case if not self.ids: raise error.NoEnginesRegistered("Can't build t...
def _connect(self, sshserver, ssh_kwargs, timeout): """setup all our socket connections to the cluster. This is called from __init__.""" # Maybe allow reconnecting? if self._connected: return self._connected=True def connect_socket(s, url): url =...
def _unwrap_exception(self, content): """unwrap exception, and remap engine_id to int.""" e = error.unwrap_exception(content) # print e.traceback if e.engine_info: e_uuid = e.engine_info['engine_uuid'] eid = self._engines[e_uuid] e.engine_info['engine_...
def _register_engine(self, msg): """Register a new engine, and update our connection info.""" content = msg['content'] eid = content['id'] d = {eid : content['queue']} self._update_engines(d)
def _unregister_engine(self, msg): """Unregister an engine that has died.""" content = msg['content'] eid = int(content['id']) if eid in self._ids: self._ids.remove(eid) uuid = self._engines.pop(eid) self._handle_stranded_msgs(eid, uuid) if s...
def _handle_stranded_msgs(self, eid, uuid): """Handle messages known to be on an engine when the engine unregisters. It is possible that this will fire prematurely - that is, an engine will go down after completing a result, and the client will be notified of the unregistration and late...
def _handle_execute_reply(self, msg): """Save the reply to an execute_request into our results. execute messages are never actually used. apply is used instead. """ parent = msg['parent_header'] msg_id = parent['msg_id'] if msg_id not in self.outstanding: if...
def _flush_notifications(self): """Flush notifications of engine registrations waiting in ZMQ queue.""" idents,msg = self.session.recv(self._notification_socket, mode=zmq.NOBLOCK) while msg is not None: if self.debug: pprint(msg) msg_type = msg['he...
def _flush_results(self, sock): """Flush task or queue results waiting in ZMQ queue.""" idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) while msg is not None: if self.debug: pprint(msg) msg_type = msg['header']['msg_type'] handler = self...
def _flush_control(self, sock): """Flush replies from the control channel waiting in the ZMQ queue. Currently: ignore them.""" if self._ignored_control_replies <= 0: return idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) while msg is not None: ...
def _flush_ignored_control(self): """flush ignored control replies""" while self._ignored_control_replies > 0: self.session.recv(self._control_socket) self._ignored_control_replies -= 1
def _flush_iopub(self, sock): """Flush replies from the iopub channel waiting in the ZMQ queue. """ idents,msg = self.session.recv(sock, mode=zmq.NOBLOCK) while msg is not None: if self.debug: pprint(msg) parent = msg['parent_header'] ...
def activate(self, targets='all', suffix=''): """Create a DirectView and register it with IPython magics Defines the magics `%px, %autopx, %pxresult, %%px` Parameters ---------- targets: int, list of ints, or 'all' The engines on which the v...
def _spin_every(self, interval=1): """target func for use in spin_thread""" while True: if self._stop_spinning.is_set(): return time.sleep(interval) self.spin()
def spin_thread(self, interval=1): """call Client.spin() in a background thread on some regular interval This helps ensure that messages don't pile up too much in the zmq queue while you are working on other things, or just leaving an idle terminal. It also helps limit ...
def stop_spin_thread(self): """stop background spin_thread, if any""" if self._spin_thread is not None: self._stop_spinning.set() self._spin_thread.join() self._spin_thread = None
def spin(self): """Flush any registration notifications and execution results waiting in the ZMQ queue. """ if self._notification_socket: self._flush_notifications() if self._iopub_socket: self._flush_iopub(self._iopub_socket) if self._mux_socket: ...
def wait(self, jobs=None, timeout=-1): """waits on one or more `jobs`, for up to `timeout` seconds. Parameters ---------- jobs : int, str, or list of ints and/or strs, or one or more AsyncResult objects ints are indices to self.history strs are msg_ids ...
def clear(self, targets=None, block=None): """Clear the namespace in target(s).""" block = self.block if block is None else block targets = self._build_targets(targets)[0] for t in targets: self.session.send(self._control_socket, 'clear_request', content={}, ident=t) ...
def abort(self, jobs=None, targets=None, block=None): """Abort specific jobs from the execution queues of target(s). This is a mechanism to prevent jobs that have already been submitted from executing. Parameters ---------- jobs : msg_id, list of msg_ids, or AsyncResul...
def shutdown(self, targets='all', restart=False, hub=False, block=None): """Terminates one or more engine processes, optionally including the hub. Parameters ---------- targets: list of ints or 'all' [default: all] Which engines to shutdown. hub: boo...
def send_apply_request(self, socket, f, args=None, kwargs=None, subheader=None, track=False, ident=None): """construct and send an apply message via a socket. This is the principal method with which all engine execution is performed by views. """ if self._cl...
def send_execute_request(self, socket, code, silent=True, subheader=None, ident=None): """construct and send an execute request via a socket. """ if self._closed: raise RuntimeError("Client cannot be used after its sockets have been closed") # defaults: sub...
def load_balanced_view(self, targets=None): """construct a DirectView object. If no arguments are specified, create a LoadBalancedView using all engines. Parameters ---------- targets: list,slice,int,etc. [default: use all engines] The subset of engines acr...
def direct_view(self, targets='all'): """construct a DirectView object. If no targets are specified, create a DirectView using all engines. rc.direct_view('all') is distinguished from rc[:] in that 'all' will evaluate the target engines at each execution, whereas rc[:] will con...
def get_result(self, indices_or_msg_ids=None, block=None): """Retrieve a result by msg_id or history index, wrapped in an AsyncResult object. If the client already has the results, no request to the Hub will be made. This is a convenient way to construct AsyncResult objects, which are wrappers...
def resubmit(self, indices_or_msg_ids=None, subheader=None, block=None): """Resubmit one or more tasks. in-flight tasks may not be resubmitted. Parameters ---------- indices_or_msg_ids : integer history index, str msg_id, or list of either The indices or msg_ids of...
def result_status(self, msg_ids, status_only=True): """Check on the status of the result(s) of the apply request with `msg_ids`. If status_only is False, then the actual results will be retrieved, else only the status of the results will be checked. Parameters ---------- ...
def queue_status(self, targets='all', verbose=False): """Fetch the status of engine queues. Parameters ---------- targets : int/str/list of ints/strs the engines whose states are to be queried. default : all verbose : bool Whether...
def purge_results(self, jobs=[], targets=[]): """Tell the Hub to forget results. Individual results can be purged by msg_id, or the entire history of specific targets can be purged. Use `purge_results('all')` to scrub everything from the Hub's db. Parameters ----------...
def hub_history(self): """Get the Hub's history Just like the Client, the Hub has a history, which is a list of msg_ids. This will contain the history of all clients, and, depending on configuration, may contain history across multiple cluster sessions. Any msg_id returned here...
def db_query(self, query, keys=None): """Query the Hub's TaskRecord database This will return a list of task record dicts that match `query` Parameters ---------- query : mongodb query dict The search dict. See mongodb query docs for details. keys : list of...
def _opcode_set(*names): """Return a set of opcodes by the names in `names`.""" s = set() for name in names: try: s.add(_opcode(name)) except KeyError: pass return s
def _get_byte_parser(self): """Create a ByteParser on demand.""" if not self._byte_parser: self._byte_parser = \ ByteParser(text=self.text, filename=self.filename) return self._byte_parser
def lines_matching(self, *regexes): """Find the lines matching one of a list of regexes. Returns a set of line numbers, the lines that contain a match for one of the regexes in `regexes`. The entire line needn't match, just a part of it. """ regex_c = re.compile(join_r...
def _raw_parse(self): """Parse the source to find the interesting facts about its lines. A handful of member fields are updated. """ # Find lines which match an exclusion pattern. if self.exclude: self.excluded = self.lines_matching(self.exclude) # Tokenize...
def first_line(self, line): """Return the first line number of the statement including `line`.""" rng = self.multiline.get(line) if rng: first_line = rng[0] else: first_line = line return first_line
def first_lines(self, lines, *ignores): """Map the line numbers in `lines` to the correct first line of the statement. Skip any line mentioned in any of the sequences in `ignores`. Returns a set of the first lines. """ ignore = set() for ign in ignores: ...
def parse_source(self): """Parse source text to find executable lines, excluded lines, etc. Return values are 1) a set of executable line numbers, and 2) a set of excluded line numbers. Reported line numbers are normalized to the first line of multi-line statements. ""...
def arcs(self): """Get information about the arcs available in the code. Returns a sorted list of line number pairs. Line numbers have been normalized to the first line of multiline statements. """ all_arcs = [] for l1, l2 in self.byte_parser._all_arcs(): f...
def exit_counts(self): """Get a mapping from line numbers to count of exits from that line. Excluded lines are excluded. """ excluded_lines = self.first_lines(self.excluded) exit_counts = {} for l1, l2 in self.arcs(): if l1 < 0: # Don't ever ...
def child_parsers(self): """Iterate over all the code objects nested within this one. The iteration includes `self` as its first value. """ children = CodeObjects(self.code) return [ByteParser(code=c, text=self.text) for c in children]
def _bytes_lines(self): """Map byte offsets to line numbers in `code`. Uses co_lnotab described in Python/compile.c to map byte offsets to line numbers. Produces a sequence: (b0, l0), (b1, l1), ... Only byte offsets that correspond to line numbers are included in the results. ...
def _find_statements(self): """Find the statements in `self.code`. Produce a sequence of line numbers that start statements. Recurses into all code objects reachable from `self.code`. """ for bp in self.child_parsers(): # Get all of the lineno information from this...
def _block_stack_repr(self, block_stack): """Get a string version of `block_stack`, for debugging.""" blocks = ", ".join( ["(%s, %r)" % (dis.opname[b[0]], b[1]) for b in block_stack] ) return "[" + blocks + "]"
def _split_into_chunks(self): """Split the code object into a list of `Chunk` objects. Each chunk is only entered at its first instruction, though there can be many exits from a chunk. Returns a list of `Chunk` objects. """ # The list of chunks so far, and the one we'r...
def validate_chunks(self, chunks): """Validate the rule that chunks have a single entrance.""" # starts is the entrances to the chunks starts = set([ch.byte for ch in chunks]) for ch in chunks: assert all([(ex in starts or ex < 0) for ex in ch.exits])
def _arcs(self): """Find the executable arcs in the code. Yields pairs: (from,to). From and to are integer line numbers. If from is < 0, then the arc is an entrance into the code object. If to is < 0, the arc is an exit from the code object. """ chunks = self._split_...
def _all_chunks(self): """Returns a list of `Chunk` objects for this code and its children. See `_split_into_chunks` for details. """ chunks = [] for bp in self.child_parsers(): chunks.extend(bp._split_into_chunks()) return chunks
def _all_arcs(self): """Get the set of all arcs in this code object and its children. See `_arcs` for details. """ arcs = set() for bp in self.child_parsers(): arcs.update(bp._arcs()) return arcs
def options(self, parser, env): """ Add options to command line. """ super(Coverage, self).options(parser, env) parser.add_option("--cover-package", action="append", default=env.get('NOSE_COVER_PACKAGE'), metavar="PACKAGE", ...
def configure(self, options, conf): """ Configure plugin. """ try: self.status.pop('active') except KeyError: pass super(Coverage, self).configure(options, conf) if conf.worker: return if self.enabled: try: ...
def begin(self): """ Begin recording coverage information. """ log.debug("Coverage begin") self.skipModules = sys.modules.keys()[:] if self.coverErase: log.debug("Clearing previously collected coverage statistics") self.coverInstance.combine() ...
def report(self, stream): """ Output code coverage report. """ log.debug("Coverage report") self.coverInstance.stop() self.coverInstance.combine() self.coverInstance.save() modules = [module for name, module in sys.modules.items() ...
def wantFile(self, file, package=None): """If inclusive coverage enabled, return true for all source files in wanted packages. """ if self.coverInclusive: if file.endswith(".py"): if package and self.coverPackages: for want in self.coverPac...
def interpret_distro_name(location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to t...
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> _encode_auth('username%3Apassword') u'dXNlcm5hbWU6cGFzc3dvcmQ=' """ auth_s = urllib2.unquote(auth) # convert to bytes auth_bytes = auth_s.encode() ...
def open_with_auth(url): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urlparse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): ...
def fetch_distribution(self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `for...
def jrepr(value): '''customized `repr()`.''' if value is None: return repr(value) t = type(value) if t.__repr__ is not object.__repr__: return repr(value) return 'object ' + t.__name__
def get_parent(obj): ''' get parent from obj. ''' names = obj.__qualname__.split('.')[:-1] if '<locals>' in names: # locals function raise ValueError('cannot get parent from locals object.') module = sys.modules[obj.__module__] parent = module while names: parent = getatt...
def root_topic(self): """this is a property, in case the handler is created before the engine gets registered with an id""" if isinstance(getattr(self.engine, 'id', None), int): return "engine.%i"%self.engine.id else: return "engine"
def init_fakemod_dict(fm,adict=None): """Initialize a FakeModule instance __dict__. Kept as a standalone function and not a method so the FakeModule API can remain basically empty. This should be considered for private IPython use, used in managing namespaces for %run. Parameters --------...
def render_template(content, context): """ renders context aware template """ rendered = Template(content).render(Context(context)) return rendered
def configure(self, options, conf): """Configure plugin. Plugin is enabled by default. """ self.conf = conf if not options.capture: self.enabled = False
def formatError(self, test, err): """Add captured output to error report. """ test.capturedOutput = output = self.buffer self._buf = None if not output: # Don't return None as that will prevent other # formatters from formatting and remove earlier formatte...
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]