INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Split the code object into a list of Chunk objects.
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're working on. chunks = [] chunk = None # A dict mapping byte offsets of line starts to the line numbers. bytes_lines_map = dict(self._bytes_lines()) # The block stack: loops and try blocks get pushed here for the # implicit jumps that can occur. # Each entry is a tuple: (block type, destination) block_stack = [] # Some op codes are followed by branches that should be ignored. This # is a count of how many ignores are left. ignore_branch = 0 # We have to handle the last two bytecodes specially. ult = penult = None # Get a set of all of the jump-to points. jump_to = set() bytecodes = list(ByteCodes(self.code.co_code)) for bc in bytecodes: if bc.jump_to >= 0: jump_to.add(bc.jump_to) chunk_lineno = 0 # Walk the byte codes building chunks. for bc in bytecodes: # Maybe have to start a new chunk start_new_chunk = False first_chunk = False if bc.offset in bytes_lines_map: # Start a new chunk for each source line number. start_new_chunk = True chunk_lineno = bytes_lines_map[bc.offset] first_chunk = True elif bc.offset in jump_to: # To make chunks have a single entrance, we have to make a new # chunk when we get to a place some bytecode jumps to. start_new_chunk = True elif bc.op in OPS_CHUNK_BEGIN: # Jumps deserve their own unnumbered chunk. This fixes # problems with jumps to jumps getting confused. start_new_chunk = True if not chunk or start_new_chunk: if chunk: chunk.exits.add(bc.offset) chunk = Chunk(bc.offset, chunk_lineno, first_chunk) chunks.append(chunk) # Look at the opcode if bc.jump_to >= 0 and bc.op not in OPS_NO_JUMP: if ignore_branch: # Someone earlier wanted us to ignore this branch. ignore_branch -= 1 else: # The opcode has a jump, it's an exit for this chunk. chunk.exits.add(bc.jump_to) if bc.op in OPS_CODE_END: # The opcode can exit the code object. chunk.exits.add(-self.code.co_firstlineno) if bc.op in OPS_PUSH_BLOCK: # The opcode adds a block to the block_stack. block_stack.append((bc.op, bc.jump_to)) if bc.op in OPS_POP_BLOCK: # The opcode pops a block from the block stack. block_stack.pop() if bc.op in OPS_CHUNK_END: # This opcode forces the end of the chunk. if bc.op == OP_BREAK_LOOP: # A break is implicit: jump where the top of the # block_stack points. chunk.exits.add(block_stack[-1][1]) chunk = None if bc.op == OP_END_FINALLY: # For the finally clause we need to find the closest exception # block, and use its jump target as an exit. for block in reversed(block_stack): if block[0] in OPS_EXCEPT_BLOCKS: chunk.exits.add(block[1]) break if bc.op == OP_COMPARE_OP and bc.arg == COMPARE_EXCEPTION: # This is an except clause. We want to overlook the next # branch, so that except's don't count as branches. ignore_branch += 1 penult = ult ult = bc if chunks: # The last two bytecodes could be a dummy "return None" that # shouldn't be counted as real code. Every Python code object seems # to end with a return, and a "return None" is inserted if there # isn't an explicit return in the source. if ult and penult: if penult.op == OP_LOAD_CONST and ult.op == OP_RETURN_VALUE: if self.code.co_consts[penult.arg] is None: # This is "return None", but is it dummy? A real line # would be a last chunk all by itself. if chunks[-1].byte != penult.offset: ex = -self.code.co_firstlineno # Split the last chunk last_chunk = chunks[-1] last_chunk.exits.remove(ex) last_chunk.exits.add(penult.offset) chunk = Chunk( penult.offset, last_chunk.line, False ) chunk.exits.add(ex) chunks.append(chunk) # Give all the chunks a length. chunks[-1].length = bc.next_offset - chunks[-1].byte # pylint: disable=W0631,C0301 for i in range(len(chunks)-1): chunks[i].length = chunks[i+1].byte - chunks[i].byte #self.validate_chunks(chunks) return chunks
Validate the rule that chunks have a single entrance.
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])
Find the executable arcs in the code.
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_into_chunks() # A map from byte offsets to chunks jumped into. byte_chunks = dict([(c.byte, c) for c in chunks]) # There's always an entrance at the first chunk. yield (-1, byte_chunks[0].line) # Traverse from the first chunk in each line, and yield arcs where # the trace function will be invoked. for chunk in chunks: if not chunk.first: continue chunks_considered = set() chunks_to_consider = [chunk] while chunks_to_consider: # Get the chunk we're considering, and make sure we don't # consider it again this_chunk = chunks_to_consider.pop() chunks_considered.add(this_chunk) # For each exit, add the line number if the trace function # would be triggered, or add the chunk to those being # considered if not. for ex in this_chunk.exits: if ex < 0: yield (chunk.line, ex) else: next_chunk = byte_chunks[ex] if next_chunk in chunks_considered: continue # The trace function is invoked if visiting the first # bytecode in a line, or if the transition is a # backward jump. backward_jump = next_chunk.byte < this_chunk.byte if next_chunk.first or backward_jump: if next_chunk.line != chunk.line: yield (chunk.line, next_chunk.line) else: chunks_to_consider.append(next_chunk)
Returns a list of Chunk objects for this code and its children.
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
Get the set of all arcs in this code object and its children.
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
Add options to command line.
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", dest="cover_packages", help="Restrict coverage output to selected packages " "[NOSE_COVER_PACKAGE]") parser.add_option("--cover-erase", action="store_true", default=env.get('NOSE_COVER_ERASE'), dest="cover_erase", help="Erase previously collected coverage " "statistics before run") parser.add_option("--cover-tests", action="store_true", dest="cover_tests", default=env.get('NOSE_COVER_TESTS'), help="Include test modules in coverage report " "[NOSE_COVER_TESTS]") parser.add_option("--cover-min-percentage", action="store", dest="cover_min_percentage", default=env.get('NOSE_COVER_MIN_PERCENTAGE'), help="Minimum percentage of coverage for tests" "to pass [NOSE_COVER_MIN_PERCENTAGE]") parser.add_option("--cover-inclusive", action="store_true", dest="cover_inclusive", default=env.get('NOSE_COVER_INCLUSIVE'), help="Include all python files under working " "directory in coverage report. Useful for " "discovering holes in test coverage if not all " "files are imported by the test suite. " "[NOSE_COVER_INCLUSIVE]") parser.add_option("--cover-html", action="store_true", default=env.get('NOSE_COVER_HTML'), dest='cover_html', help="Produce HTML coverage information") parser.add_option('--cover-html-dir', action='store', default=env.get('NOSE_COVER_HTML_DIR', 'cover'), dest='cover_html_dir', metavar='DIR', help='Produce HTML coverage information in dir') parser.add_option("--cover-branches", action="store_true", default=env.get('NOSE_COVER_BRANCHES'), dest="cover_branches", help="Include branch coverage in coverage report " "[NOSE_COVER_BRANCHES]") parser.add_option("--cover-xml", action="store_true", default=env.get('NOSE_COVER_XML'), dest="cover_xml", help="Produce XML coverage information") parser.add_option("--cover-xml-file", action="store", default=env.get('NOSE_COVER_XML_FILE', 'coverage.xml'), dest="cover_xml_file", metavar="FILE", help="Produce XML coverage information in file")
Configure plugin.
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: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = conf self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = [] if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]: self.coverPackages.extend(pkgs) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) self.coverHtmlDir = None if options.cover_html: self.coverHtmlDir = options.cover_html_dir log.debug('Will put HTML coverage report in %s', self.coverHtmlDir) self.coverBranches = options.cover_branches self.coverXmlFile = None if options.cover_min_percentage: self.coverMinPercentage = int(options.cover_min_percentage.rstrip('%')) if options.cover_xml: self.coverXmlFile = options.cover_xml_file log.debug('Will put XML coverage report in %s', self.coverXmlFile) if self.enabled: self.status['active'] = True self.coverInstance = coverage.coverage(auto_data=False, branch=self.coverBranches, data_suffix=None)
Begin recording coverage information.
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() self.coverInstance.erase() self.coverInstance.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') self.coverInstance.load() self.coverInstance.start()
Output code coverage report.
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() if self.wantModuleCoverage(name, module)] log.debug("Coverage report will cover modules: %s", modules) self.coverInstance.report(modules, file=stream) if self.coverHtmlDir: log.debug("Generating HTML coverage report") self.coverInstance.html_report(modules, self.coverHtmlDir) if self.coverXmlFile: log.debug("Generating XML coverage report") self.coverInstance.xml_report(modules, self.coverXmlFile) # make sure we have minimum required coverage if self.coverMinPercentage: f = StringIO.StringIO() self.coverInstance.report(modules, file=f) m = re.search(r'-------\s\w+\s+\d+\s+\d+\s+(\d+)%\s+\d*\s{0,1}$', f.getvalue()) if m: percentage = int(m.groups()[0]) if percentage < self.coverMinPercentage: log.error('TOTAL Coverage did not reach minimum ' 'required: %d%%' % self.coverMinPercentage) sys.exit(1) else: log.error("No total percentage was found in coverage output, " "something went wrong.")
If inclusive coverage enabled return true for all source files in wanted packages.
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.coverPackages: if package.startswith(want): return True else: return True return None
Generate alternative interpretations of a source distro name
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 this routine! """ # Generate alternative interpretations of a source distro name # Because some packages are ambiguous as to name/versions split # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc. # So, we generate each possible interepretation (e.g. "adns, python-1.1.0" # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice, # the spurious interpretations should be ignored, because in the event # there's also an "adns" package, the spurious "python-1.1.0" version will # compare lower than any numeric version number, and is therefore unlikely # to match a request for it. It's still a potential problem, though, and # in the long run PyPI and the distutils should go for "safe" names and # versions in distribution archive names (sdist and bdist). parts = basename.split('-') if not py_version: for i,p in enumerate(parts[2:]): if len(p)==5 and p.startswith('py2.'): return # It's a bdist_dumb, not an sdist -- bail out for p in range(1,len(parts)+1): yield Distribution( location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), py_version=py_version, precedence = precedence, platform = platform )
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 =
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() # use the legacy interface for Python 2.3 support encoded_bytes = base64.encodestring(auth_bytes) # convert back to a string encoded = encoded_bytes.decode() # strip the trailing carriage return return encoded.rstrip()
Open a urllib2 request handling HTTP authentication
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(':'): raise httplib.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, host = urllib2.splituser(netloc) else: auth = None if auth: auth = "Basic " + _encode_auth(auth) new_url = urlparse.urlunparse((scheme,host,path,params,query,frag)) request = urllib2.Request(new_url) request.add_header("Authorization", auth) else: request = urllib2.Request(url) request.add_header('User-Agent', user_agent) fp = urllib2.urlopen(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urlparse.urlparse(fp.url) if s2==scheme and h2==host: fp.url = urlparse.urlunparse((s2,netloc,path2,param2,query2,frag2)) return fp
Obtain a distribution suitable for fulfilling requirement
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 `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored. """ # process a Requirement self.info("Searching for %s", requirement) skipped = {} dist = None def find(req, env=None): if env is None: env = self # Find a matching distribution; may be called more than once for dist in env[req.key]: if dist.precedence==DEVELOP_DIST and not develop_ok: if dist not in skipped: self.warn("Skipping development or system egg: %s",dist) skipped[dist] = 1 continue if dist in req and (dist.precedence<=SOURCE_DIST or not source): self.info("Best match: %s", dist) return dist.clone( location=self.download(dist.location, tmpdir) ) if force_scan: self.prescan() self.find_packages(requirement) dist = find(requirement) if local_index is not None: dist = dist or find(requirement, local_index) if dist is None and self.to_scan is not None: self.prescan() dist = find(requirement) if dist is None and not force_scan: self.find_packages(requirement) dist = find(requirement) if dist is None: self.warn( "No local packages or download links found for %s%s", (source and "a source distribution of " or ""), requirement, ) return dist
customized repr ().
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__
get parent from obj.
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 = getattr(parent, names.pop(0)) return parent
this is a property in case the handler is created before the engine gets registered with an id
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"
Initialize a FakeModule instance __dict__.
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 ---------- fm : FakeModule instance adict : dict, optional """ dct = {} # It seems pydoc (and perhaps others) needs any module instance to # implement a __nonzero__ method, so we add it if missing: dct.setdefault('__nonzero__',lambda : True) dct.setdefault('__file__',__file__) if adict is not None: dct.update(adict) # Hard assignment of the object's __dict__. This is nasty but deliberate. fm.__dict__.clear() fm.__dict__.update(dct)
renders context aware template
def render_template(content, context): """ renders context aware template """ rendered = Template(content).render(Context(context)) return rendered
Configure plugin. Plugin is enabled by default.
def configure(self, options, conf): """Configure plugin. Plugin is enabled by default. """ self.conf = conf if not options.capture: self.enabled = False
Add captured output to error report.
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 formatters # formats, instead return the err we got return err ec, ev, tb = err return (ec, self.addCaptureToErr(ev, output), tb)
Turn a list to list of list
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]
Convert a notebook to the v3 format.
def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0): """Convert a notebook to the v3 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. orig_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). """ if orig_version == 1: nb = v2.convert_to_this_nbformat(nb) orig_version = 2 if orig_version == 2: # Mark the original nbformat so consumers know it has been converted. nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor nb.orig_nbformat = 2 return nb elif orig_version == 3: if orig_minor != nbformat_minor: nb.orig_nbformat_minor = orig_minor nb.nbformat_minor = nbformat_minor return nb else: raise ValueError('Cannot convert a notebook from v%s to v3' % orig_version)
Convert a hex color to rgb integer tuple.
def hex_to_rgb(color): """Convert a hex color to rgb integer tuple.""" if color.startswith('#'): color = color[1:] if len(color) == 3: color = ''.join([c*2 for c in color]) if len(color) != 6: return False try: r = int(color[:2],16) g = int(color[2:4],16) b = int(color[4:],16) except ValueError: return False else: return r,g,b
Construct the keys to be used building the base stylesheet from a templatee.
def get_colors(stylename): """Construct the keys to be used building the base stylesheet from a templatee.""" style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3,6): # could be 'abcdef' or 'ace' hex, which needs '#' prefix try: int(fgcolor, 16) except TypeError: pass else: fgcolor = "#"+fgcolor return dict( bgcolor = style.background_color, select = style.highlight_color, fgcolor = fgcolor )
Use one of the base templates and set bg/ fg/ select colors.
def sheet_from_template(name, colors='lightbg'): """Use one of the base templates, and set bg/fg/select colors.""" colors = colors.lower() if colors=='lightbg': return default_light_style_template%get_colors(name) elif colors=='linux': return default_dark_style_template%get_colors(name) elif colors=='nocolor': return default_bw_style_sheet else: raise KeyError("No such color scheme: %s"%colors)
Return a font of the requested family using fallback as alternative.
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object """ font = QtGui.QFont(family) # Check whether we got what we wanted using QFontInfo, since exactMatch() # is overly strict and returns false in too many cases. font_info = QtGui.QFontInfo(font) if fallback is not None and font_info.family() != family: font = QtGui.QFont(fallback) return font
Reimplemented to support IPython s improved completion machinery.
def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): matches = rep['content']['matches'] text = rep['content']['matched_text'] offset = len(text) # Clean up matches with period and path separators if the matched # text has not been transformed. This is done by truncating all # but the last component and then suitably decreasing the offset # between the current cursor position and the start of completion. if len(matches) > 1 and matches[0][:offset] == text: parts = re.split(r'[./\\]', text) sep_count = len(parts) - 1 if sep_count: chop_length = sum(map(len, parts[:sep_count])) + sep_count matches = [ match[chop_length:] for match in matches ] offset -= chop_length # Move the cursor to the start of the match and complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches)
Reimplemented to support prompt requests.
def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg)
Implemented to handle history tail replies which are only supported by the IPython kernel.
def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items)
Reimplemented for IPython - style display hook.
def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('text/html'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) html = data['text/html'] self._append_plain_text('\n', True) self._append_html(html + self.output_sep2, True) elif data.has_key('text/plain'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True)
The base handler for the display_data message.
def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if data.has_key('text/html'): html = data['text/html'] self._append_html(html, True) elif data.has_key('text/plain'): text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True)
Reimplemented to make a history request and load %guiref.
def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type='tail', n=1000)
Reimplemented to use the run magic.
def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden)
Reimplemented to support IPython s improved completion machinery.
def _complete(self): """ Reimplemented to support IPython's improved completion machinery. """ # We let the kernel split the input line, so we *always* send an empty # text field. Readline-based frontends do get a real text field which # they can use. text = '' # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( text, # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
Reimplemented for IPython - style traceback formatting.
def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback)
Reimplemented to dispatch payloads to handler methods.
def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True
Reimplemented for IPython - style prompts.
def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_manager.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True)
Reimplemented for IPython - style prompts.
def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1)
Sets the widget style to the class defaults.
def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors)
Opens a Python script for editing.
def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command)
Given a prompt number returns an HTML In prompt.
def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-prompt">%s</span>' % body
Given a plain text version of an In prompt returns an HTML continuation prompt.
def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body
Set the style sheets of the underlying widgets.
def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet)
Set the style for the syntax highlighter.
def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet)
Async co - routine to perform requests to a CloudStackAPI. The parameters needs to include the command string which refers to the API to be called. In principle any available and future CloudStack API can be called. The ** kwargs magic allows us to all add supported parameters to the given API call. A list of all available APIs can found at https:// cloudstack. apache. org/ api/ apidocs - 4. 8/ TOC_User. html
async def request(self, command: str, **kwargs) -> dict: """ Async co-routine to perform requests to a CloudStackAPI. The parameters needs to include the command string, which refers to the API to be called. In principle any available and future CloudStack API can be called. The `**kwargs` magic allows us to all add supported parameters to the given API call. A list of all available APIs can found at https://cloudstack.apache.org/api/apidocs-4.8/TOC_User.html :param command: Command string indicating the CloudStack API to be called. :type command: str :param kwargs: Parameters to be passed to the CloudStack API :return: Dictionary containing the decoded json reply of the CloudStack API :rtype: dict """ kwargs.update(dict(apikey=self.api_key, command=command, response='json')) if 'list' in command.lower(): # list APIs can be paginated, therefore include max_page_size and page parameter kwargs.update(dict(pagesize=self.max_page_size, page=1)) final_data = dict() while True: async with self.client_session.get(self.end_point, params=self._sign(kwargs)) as response: data = await self._handle_response(response=response, await_final_result='queryasyncjobresult' not in command.lower()) try: count = data.pop('count') except KeyError: if not data: # Empty dictionary is returned in case a query does not contain any results. # Can happen also if a listAPI is called with a page that does not exits. Therefore, final_data # has to be returned in order to return all results from preceding pages. return final_data else: # Only list API calls have a 'count' key inside the response, # return data as it is in other cases! return data else: # update final_data using paginated results, dictionaries of the response contain the count key # and one key pointing to the actual data values for key, value in data.items(): final_data.setdefault(key, []).extend(value) final_data['count'] = final_data.setdefault('count', 0) + count kwargs['page'] += 1 if count < self.max_page_size: # no more pages exists return final_data
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has been processed.
async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict: """ Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has been processed. :param response: The response returned by the aiohttp call. :type response: aiohttp.client_reqrep.ClientResponse :param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API until the asynchronous API call has been processed :type await_final_result: bool :return: Dictionary containing the JSON response of the API call :rtype: dict """ try: data = await response.json() except aiohttp.client_exceptions.ContentTypeError: text = await response.text() logging.debug('Content returned by server not of type "application/json"\n Content: {}'.format(text)) raise CloudStackClientException(message="Could not decode content. Server did not return json content!") else: data = self._transform_data(data) if response.status != 200: raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode", response.status), error_text=data.get("errortext"), response=data) while await_final_result and ('jobid' in data): await asyncio.sleep(self.async_poll_latency) data = await self.queryAsyncJobResult(jobid=data['jobid']) if data['jobstatus']: # jobstatus is 0 for pending async CloudStack calls if not data['jobresultcode']: # exit code is zero try: return data['jobresult'] except KeyError: pass logging.debug("Async CloudStack call returned {}".format(str(data))) raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode"), error_text=data.get("errortext"), response=data) return data
According to the CloudStack documentation each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA - 1 hash of the url parameters including the command string. In order to generate a unique identifier the url parameters have to be transformed to lower case and ordered alphabetically.
def _sign(self, url_parameters: dict) -> dict: """ According to the CloudStack documentation, each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA-1 hash of the url parameters including the command string. In order to generate a unique identifier, the url parameters have to be transformed to lower case and ordered alphabetically. :param url_parameters: The url parameters of the API call including the command string :type url_parameters: dict :return: The url parameters including a new key, which contains the signature :rtype: dict """ if url_parameters: url_parameters.pop('signature', None) # remove potential existing signature from url parameters request_string = urlencode(sorted(url_parameters.items()), safe='.-*_', quote_via=quote).lower() digest = hmac.new(self.api_secret.encode('utf-8'), request_string.encode('utf-8'), hashlib.sha1).digest() url_parameters['signature'] = base64.b64encode(digest).decode('utf-8').strip() return url_parameters
Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller.
def _transform_data(data: dict) -> dict: """ Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. :param data: Response of the API call :type data: dict :return: Simplified response without the information about the API that originated the response. :rtype: dict """ for key in data.keys(): return_value = data[key] if isinstance(return_value, dict): return return_value return data
System virtual memory as a namedutple.
def virtual_memory(): """System virtual memory as a namedutple.""" mem = _psutil_bsd.get_virtual_mem() total, free, active, inactive, wired, cached, buffers, shared = mem avail = inactive + cached + free used = active + wired + cached percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free, active, inactive, buffers, cached, shared, wired)
System swap memory as ( total used free sin sout ) namedtuple.
def swap_memory(): """System swap memory as (total, used, free, sin, sout) namedtuple.""" total, used, free, sin, sout = \ [x * _PAGESIZE for x in _psutil_bsd.get_swap_mem()] percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, sin, sout)
Return system per - CPU times as a named tuple
def get_system_cpu_times(): """Return system per-CPU times as a named tuple""" user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle, irq)
Return system CPU times as a named tuple
def get_system_per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in _psutil_bsd.get_system_per_cpu_times(): user, nice, system, idle, irq = cpu_t item = _cputimes_ntuple(user, nice, system, idle, irq) ret.append(item) return ret
Return real effective and saved user ids.
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
Return real effective and saved group ids.
def get_process_gids(self): """Return real, effective and saved group ids.""" real, effective, saved = _psutil_bsd.get_process_gids(self.pid) return nt_gids(real, effective, saved)
return a tuple containing process user/ kernel time.
def get_cpu_times(self): """return a tuple containing process user/kernel time.""" user, system = _psutil_bsd.get_process_cpu_times(self.pid) return nt_cputimes(user, system)
Return a tuple with the process RSS and VMS size.
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
Return the number of threads belonging to the process.
def get_process_threads(self): """Return the number of threads belonging to the process.""" rawlist = _psutil_bsd.get_process_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = nt_thread(thread_id, utime, stime) retlist.append(ntuple) return retlist
Return files opened by process as a list of namedtuples.
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self.pid) return [nt_openfile(path, fd) for path, fd in rawlist] else: lsof = _psposix.LsofParser(self.pid, self._process_name) return lsof.get_process_open_files()
Return the path to the connection file of an app Parameters ---------- app: KernelApp instance [ optional ] If unspecified the currently running app will be used
def get_connection_file(app=None): """Return the path to the connection file of an app Parameters ---------- app : KernelApp instance [optional] If unspecified, the currently running app will be used """ if app is None: from IPython.zmq.ipkernel import IPKernelApp if not IPKernelApp.initialized(): raise RuntimeError("app not specified, and not in a running Kernel") app = IPKernelApp.instance() return filefind(app.connection_file, ['.', app.profile_dir.security_dir])
find a connection file and return its absolute path. The current working directory and the profile s security directory will be searched for the file if it is not given by absolute path. If profile is unspecified then the current running application s profile will be used or default if not run from IPython. If the argument does not match an existing file it will be interpreted as a fileglob and the matching file in the profile s security dir with the latest access time will be used. Parameters ---------- filename: str The connection file or fileglob to search for. profile: str [ optional ] The name of the profile to use when searching for the connection file if different from the current IPython session or default. Returns ------- str: The absolute path of the connection file.
def find_connection_file(filename, profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir try: # first, try explicit name return filefind(filename, ['.', security_dir]) except IOError: pass # not found by full name if '*' in filename: # given as a glob already pat = filename else: # accept any substring match pat = '*%s*' % filename matches = glob.glob( os.path.join(security_dir, pat) ) if not matches: raise IOError("Could not find %r in %r" % (filename, security_dir)) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
Return the connection information for the current Kernel. Parameters ---------- connection_file: str [ optional ] The connection file to be used. Can be given by absolute path or IPython will search in the security directory of a given profile. If run from IPython If unspecified the connection file for the currently running IPython Kernel will be used which is only allowed from inside a kernel. unpack: bool [ default: False ] if True return the unpacked dict otherwise just the string contents of the file. profile: str [ optional ] The name of the profile to use when searching for the connection file if different from the current IPython session or default. Returns ------- The connection dictionary of the current kernel as string or dict depending on unpack.
def get_connection_info(connection_file=None, unpack=False, profile=None): """Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`. """ if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: # connection file specified, allow shortnames: cf = find_connection_file(connection_file, profile=profile) with open(cf) as f: info = f.read() if unpack: info = json.loads(info) # ensure key is bytes: info['key'] = str_to_bytes(info.get('key', '')) return info
Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel or to a local notebook. Parameters ---------- connection_file: str [ optional ] The connection file to be used. Can be given by absolute path or IPython will search in the security directory of a given profile. If run from IPython If unspecified the connection file for the currently running IPython Kernel will be used which is only allowed from inside a kernel. argv: list [ optional ] Any extra args to be passed to the console. profile: str [ optional ] The name of the profile to use when searching for the connection file if different from the current IPython session or default. Returns ------- subprocess. Popen instance running the qtconsole frontend
def connect_qtconsole(connection_file=None, argv=None, profile=None): """Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- subprocess.Popen instance running the qtconsole frontend """ argv = [] if argv is None else argv if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: cf = find_connection_file(connection_file, profile=profile) cmd = ';'.join([ "from IPython.frontend.qt.console import qtconsoleapp", "qtconsoleapp.main()" ]) return Popen([sys.executable, '-c', cmd, '--existing', cf] + argv, stdout=PIPE, stderr=PIPE)
tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost - localhost tunnels or if an intermediate server is necessary the kernel must be listening on a public IP. Parameters ---------- connection_info: dict or str ( path ) Either a connection dict or the path to a JSON connection file sshserver: str The ssh sever to use to tunnel to the kernel. Can be a full user
def tunnel_to_kernel(connection_info, sshserver, sshkey=None): """tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb) : ints The four ports on localhost that have been forwarded to the kernel. """ if isinstance(connection_info, basestring): # it's a path, unpack it with open(connection_info) as f: connection_info = json.loads(f.read()) cf = connection_info lports = tunnel.select_random_ports(4) rports = cf['shell_port'], cf['iopub_port'], cf['stdin_port'], cf['hb_port'] remote_ip = cf['ip'] if tunnel.try_passwordless_ssh(sshserver, sshkey): password=False else: password = getpass("SSH Password for %s: "%sshserver) for lp,rp in zip(lports, rports): tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password) return tuple(lports)
strip frontend - specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command - line arguments through to a subprocess where frontend - specific flags and aliases should be removed from the list. Parameters ---------- argv: list ( str ) The starting argv to be filtered aliases: container of aliases ( dict list set etc. ) The frontend - specific aliases to be removed flags: container of flags ( dict list set etc. ) The frontend - specific flags to be removed Returns ------- argv: list ( str ) The argv list excluding flags and aliases that have been stripped
def swallow_argv(argv, aliases=None, flags=None): """strip frontend-specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command-line arguments through to a subprocess, where frontend-specific flags and aliases should be removed from the list. Parameters ---------- argv : list(str) The starting argv, to be filtered aliases : container of aliases (dict, list, set, etc.) The frontend-specific aliases to be removed flags : container of flags (dict, list, set, etc.) The frontend-specific flags to be removed Returns ------- argv : list(str) The argv list, excluding flags and aliases that have been stripped """ if aliases is None: aliases = set() if flags is None: flags = set() stripped = list(argv) # copy swallow_next = False was_flag = False for a in argv: if swallow_next: swallow_next = False # last arg was an alias, remove the next one # *unless* the last alias has a no-arg flag version, in which # case, don't swallow the next arg if it's also a flag: if not (was_flag and a.startswith('-')): stripped.remove(a) continue if a.startswith('-'): split = a.lstrip('-').split('=') alias = split[0] if alias in aliases: stripped.remove(a) if len(split) == 1: # alias passed with arg via space swallow_next = True # could have been a flag that matches an alias, e.g. `existing` # in which case, we might not swallow the next arg was_flag = alias in flags elif alias in flags and len(split) == 1: # strip flag, but don't swallow next, as flags don't take args stripped.remove(a) # return shortened list return stripped
Get short form of commit hash given directory pkg_path
def pkg_commit_hash(pkg_path): """Get short form of commit hash given directory `pkg_path` We get the commit hash from (in order of preference): * IPython.utils._sysinfo.commit * git output, if we are in a git repository If these fail, we return a not-found placeholder tuple Parameters ---------- pkg_path : str directory containing package only used for getting commit from active repo Returns ------- hash_from : str Where we got the hash from - description hash_str : str short form of hash """ # Try and get commit from written commit text file if _sysinfo.commit: return "installation", _sysinfo.commit # maybe we are in a repository proc = subprocess.Popen('git rev-parse --short HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=pkg_path, shell=True) repo_commit, _ = proc.communicate() if repo_commit: return 'repository', repo_commit.strip() return '(none found)', '<not found>'
Return dict describing the context of this package
def pkg_info(pkg_path): """Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) return dict( ipython_version=release.version, ipython_path=pkg_path, commit_source=src, commit_hash=hsh, sys_version=sys.version, sys_executable=sys.executable, sys_platform=sys.platform, platform=platform.platform(), os_name=os.name, default_encoding=encoding.DEFAULT_ENCODING, )
Return useful information about IPython and the system as a string.
def sys_info(): """Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'} """ p = os.path path = p.dirname(p.abspath(p.join(__file__, '..'))) return pprint.pformat(pkg_info(path))
Return the number of active CPUs on a Darwin system.
def _num_cpus_darwin(): """Return the number of active CPUs on a Darwin system.""" p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) return p.stdout.read()
Return the effective number of CPUs in the system as an integer.
def num_cpus(): """Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect). """ # Many thanks to the Parallel Python project (http://www.parallelpython.com) # for the names of the keys we needed to look up for this function. This # code was inspired by their equivalent function. ncpufuncs = {'Linux':_num_cpus_unix, 'Darwin':_num_cpus_darwin, 'Windows':_num_cpus_windows, # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' # See http://bugs.python.org/issue1082 for details. 'Microsoft':_num_cpus_windows, } ncpufunc = ncpufuncs.get(platform.system(), # default to unix version (Solaris, AIX, etc) _num_cpus_unix) try: ncpus = max(1,int(ncpufunc())) except: ncpus = 1 return ncpus
[ 1 2 3 4 ] { accumulate: <built - in function max > }
def handle(self, integers, **options): """ [1, 2, 3, 4] {'accumulate': <built-in function max>} """ print integers, options return super(Command, self).handle(integers, **options)
Advance to the next result set.
def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_result() if nr == -1: return None self._do_get_result() self._post_get_result() self._warning_check() return 1
Execute a query. query -- string query to execute on server args -- optional sequence or mapping parameters to use with query.
def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any """ del self.messages[:] db = self._get_db() if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) if args is not None: query = query % db.literal(args) try: r = None r = self._query(query) except TypeError, m: if m.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, m.args[0])) self.errorhandler(self, ProgrammingError, m.args[0]) else: self.messages.append((TypeError, m)) self.errorhandler(self, TypeError, m) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.messages.append((exc, value)) self.errorhandler(self, exc, value) self._executed = query if not self._defer_warnings: self._warning_check() return r
Execute a multi - row query. query -- string query to execute on server
def executemany(self, query, args): """Execute a multi-row query. query -- string, query to execute on server args Sequence of sequences or mappings, parameters to use with query. Returns long integer rows affected, if any. This method improves performance on multiple-row INSERT and REPLACE. Otherwise it is equivalent to looping over args with execute(). """ del self.messages[:] db = self._get_db() if not args: return if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) m = insert_values.search(query) if not m: r = 0 for a in args: r = r + self.execute(query, a) return r p = m.start(1) e = m.end(1) qv = m.group(1) try: q = [ qv % db.literal(a) for a in args ] except TypeError, msg: if msg.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.errorhandler(self, ProgrammingError, msg.args[0]) else: self.errorhandler(self, TypeError, msg) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.errorhandler(self, exc, value) r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]])) if not self._defer_warnings: self._warning_check() return r
Execute stored procedure procname with args procname -- string name of procedure to execute on server
def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected. """ db = self._get_db() for index, arg in enumerate(args): q = "SET @_%s_%d=%s" % (procname, index, db.literal(arg)) if isinstance(q, unicode): q = q.encode(db.unicode_literal.charset) self._query(q) self.nextset() q = "CALL %s(%s)" % (procname, ','.join(['@_%s_%d' % (procname, i) for i in range(len(args))])) if type(q) is UnicodeType: q = q.encode(db.unicode_literal.charset) self._query(q) self._executed = q if not self._defer_warnings: self._warning_check() return args
Fetches a single row from the cursor.
def fetchone(self): """Fetches a single row from the cursor.""" self._check_executed() r = self._fetch_row(1) if not r: self._warning_check() return None self.rownumber = self.rownumber + 1 return r[0]
Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined cursor. arraysize is used.
def fetchmany(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() r = self._fetch_row(size or self.arraysize) self.rownumber = self.rownumber + len(r) if not r: self._warning_check() return r
Fetchs all available rows from the cursor.
def fetchall(self): """Fetchs all available rows from the cursor.""" self._check_executed() r = self._fetch_row(0) self.rownumber = self.rownumber + len(r) self._warning_check() return r
Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany () instead. Will be removed in 1. 3.
def fetchmanyDict(self, size=None): """Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany() instead. Will be removed in 1.3.""" from warnings import warn warn("fetchmanyDict() is non-standard and will be removed in 1.3", DeprecationWarning, 2) return self.fetchmany(size)
this function will be called on the engines
def connect(com, peers, tree, pub_url, root_id): """this function will be called on the engines""" com.connect(peers, tree, pub_url, root_id)
Parse a string into a ( nbformat dict ) tuple.
def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbf = d.get('nbformat', 1) nbm = d.get('nbformat_minor', 0) return nbf, nbm, d
Parse a string into a ( nbformat string ) tuple.
def parse_py(s, **kwargs): """Parse a string into a (nbformat, string) tuple.""" nbf = current_nbformat nbm = current_nbformat_minor pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>' m = re.search(pattern,s) if m is not None: digits = m.group('nbformat').split('.') nbf = int(digits[0]) if len(digits) > 1: nbm = int(digits[1]) return nbf, nbm, s
Read a JSON notebook from a string and return the NotebookNode object.
def reads_json(s, **kwargs): """Read a JSON notebook from a string and return the NotebookNode object.""" nbf, minor, d = parse_json(s, **kwargs) if nbf == 1: nb = v1.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=1) elif nbf == 2: nb = v2.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=2) elif nbf == 3: nb = v3.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=3, orig_minor=minor) else: raise NBFormatError('Unsupported JSON nbformat version: %i' % nbf) return nb
Read a. py notebook from a string and return the NotebookNode object.
def reads_py(s, **kwargs): """Read a .py notebook from a string and return the NotebookNode object.""" nbf, nbm, s = parse_py(s, **kwargs) if nbf == 2: nb = v2.to_notebook_py(s, **kwargs) elif nbf == 3: nb = v3.to_notebook_py(s, **kwargs) else: raise NBFormatError('Unsupported PY nbformat version: %i' % nbf) return nb
Read a notebook from a string and return the NotebookNode object.
def reads(s, format, **kwargs): """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. format : (u'json', u'ipynb', u'py') The format that the string is in. Returns ------- nb : NotebookNode The notebook that was read. """ format = unicode(format) if format == u'json' or format == u'ipynb': return reads_json(s, **kwargs) elif format == u'py': return reads_py(s, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
Write a notebook to a string in a given format in the current nbformat version.
def writes(nb, format, **kwargs): """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ format = unicode(format) if format == u'json' or format == u'ipynb': return writes_json(nb, **kwargs) elif format == u'py': return writes_py(nb, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
Write a notebook to a file in a given format in the current nbformat version.
def write(nb, fp, format, **kwargs): """Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ return fp.write(writes(nb, format, **kwargs))
Convert to a notebook having notebook metadata.
def _convert_to_metadata(): """Convert to a notebook having notebook metadata.""" import glob for fname in glob.glob('*.ipynb'): print('Converting file:',fname) with open(fname,'r') as f: nb = read(f,u'json') md = new_metadata() if u'name' in nb: md.name = nb.name del nb[u'name'] nb.metadata = md with open(fname,'w') as f: write(nb, f, u'json')
try load value from dict. if key is not exists mark as state unset.
def load_from_dict(self, src: dict, key): ''' try load value from dict. if key is not exists, mark as state unset. ''' if key in src: self.value = src[key] else: self.reset()
Run the pyglet event loop by processing pending events only.
def inputhook_pyglet(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: t = clock() while not stdin_ready(): pyglet.clock.tick() for window in pyglet.app.windows: window.switch_to() window.dispatch_events() window.dispatch_event('on_draw') flip(window) # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
Does the name match my requirements?
def matches(self, name): """Does the name match my requirements? To match, a name must match config.testMatch OR config.include and it must not match config.exclude """ return ((self.match.search(name) or (self.include and filter(None, [inc.search(name) for inc in self.include]))) and ((not self.exclude) or not filter(None, [exc.search(name) for exc in self.exclude]) ))
Is the class a wanted test class?
def wantClass(self, cls): """Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. Classes that start with _ are always excluded. """ declared = getattr(cls, '__test__', None) if declared is not None: wanted = declared else: wanted = (not cls.__name__.startswith('_') and (issubclass(cls, unittest.TestCase) or self.matches(cls.__name__))) plug_wants = self.plugins.wantClass(cls) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", cls, plug_wants) wanted = plug_wants log.debug("wantClass %s? %s", cls, wanted) return wanted
Is the directory a wanted test directory?
def wantDirectory(self, dirname): """Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. """ tail = op_basename(dirname) if ispackage(dirname): wanted = (not self.exclude or not filter(None, [exc.search(tail) for exc in self.exclude] )) else: wanted = (self.matches(tail) or (self.config.srcDirs and tail in self.config.srcDirs)) plug_wants = self.plugins.wantDirectory(dirname) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", dirname, plug_wants) wanted = plug_wants log.debug("wantDirectory %s? %s", dirname, wanted) return wanted
Is the file a wanted test file?
def wantFile(self, file): """Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings. """ # never, ever load files that match anything in ignore # (.* _* and *setup*.py by default) base = op_basename(file) ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles if ignore_this.search(base) ] if ignore_matches: log.debug('%s matches ignoreFiles pattern; skipped', base) return False if not self.config.includeExe and os.access(file, os.X_OK): log.info('%s is executable; skipped', file) return False dummy, ext = op_splitext(base) pysrc = ext == '.py' wanted = pysrc and self.matches(base) plug_wants = self.plugins.wantFile(file) if plug_wants is not None: log.debug("plugin setting want %s to %s", file, plug_wants) wanted = plug_wants log.debug("wantFile %s? %s", file, wanted) return wanted
Is the function a test function?
def wantFunction(self, function): """Is the function a test function? """ try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # not a function return False declared = getattr(function, '__test__', None) if declared is not None: wanted = declared else: wanted = not funcname.startswith('_') and self.matches(funcname) plug_wants = self.plugins.wantFunction(function) if plug_wants is not None: wanted = plug_wants log.debug("wantFunction %s? %s", function, wanted) return wanted
Is the method a test method?
def wantMethod(self, method): """Is the method a test method? """ try: method_name = method.__name__ except AttributeError: # not a method return False if method_name.startswith('_'): # never collect 'private' methods return False declared = getattr(method, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(method_name) plug_wants = self.plugins.wantMethod(method) if plug_wants is not None: wanted = plug_wants log.debug("wantMethod %s? %s", method, wanted) return wanted
Is the module a test module?
def wantModule(self, module): """Is the module a test module? The tail of the module name must match test requirements. One exception: we always want __main__. """ declared = getattr(module, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(module.__name__.split('.')[-1]) \ or module.__name__ == '__main__' plug_wants = self.plugins.wantModule(module) if plug_wants is not None: wanted = plug_wants log.debug("wantModule %s? %s", module, wanted) return wanted
Make new_fn have old_fn s doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp. lang. python posting by Duncan Booth.
def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): """Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.""" def wrapper(*args, **kw): return new_fn(*args, **kw) if old_fn.__doc__: wrapper.__doc__ = old_fn.__doc__ + additional_text return wrapper
Return the contents of a named file as a list of lines.
def _file_lines(fname): """Return the contents of a named file as a list of lines. This function never raises an IOError exception: if the file can't be read, it simply returns an empty list.""" try: outfile = open(fname) except IOError: return [] else: out = outfile.readlines() outfile.close() return out
List command to use if we have a newer pydb installed
def list_command_pydb(self, arg): """List command to use if we have a newer pydb installed""" filename, first, last = OldPdb.parse_list_cmd(self, arg) if filename is not None: self.print_list_lines(filename, first, last)