INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Compare the response code of url param with code param and returns boolean | def compare_response_code(url, code):
'''
Compare the response code of url param with code param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> int e.g. 404, 500, 400 ..etc
'''
try:
response = urllib2.urlopen(url)
except HTTPError as... |
Publish data and metadata to all frontends. | def publish_display_data(source, data, metadata=None):
"""Publish data and metadata to all frontends.
See the ``display_data`` message in the messaging documentation for
more details about this message type.
The following MIME types are currently implemented:
* text/plain
* text/html
* te... |
Validate the display data. | def _validate_data(self, source, data, metadata=None):
"""Validate the display data.
Parameters
----------
source : str
The fully dotted name of the callable that created the data, like
:func:`foo.bar.my_formatter`.
data : dict
The formata dat... |
Publish data and metadata to all frontends. | def publish(self, source, data, metadata=None):
"""Publish data and metadata to all frontends.
See the ``display_data`` message in the messaging documentation for
more details about this message type.
The following MIME types are currently implemented:
* text/plain
* t... |
Clear the output of the cell receiving output. | def clear_output(self, stdout=True, stderr=True, other=True):
"""Clear the output of the cell receiving output."""
if stdout:
print('\033[2K\r', file=io.stdout, end='')
io.stdout.flush()
if stderr:
print('\033[2K\r', file=io.stderr, end='')
io.stde... |
Returns numerical gradient function of given input function Input: f scalar function of one or two variables delta ( optional ) finite difference step Output: gradient function object | def grad(f, delta=DELTA):
"""
Returns numerical gradient function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: gradient function object
"""
def grad_f(*args, **kwargs):
if len(args) == 1:
... |
Returns numerical hessian function of given input function Input: f scalar function of one or two variables delta ( optional ) finite difference step Output: hessian function object | def hessian(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of one or two variables
delta(optional), finite difference step
Output: hessian function object
"""
def hessian_f(*args, **kwargs):
if len(args) == 1:
... |
Returns numerical gradient function of given input function Input: f scalar function of an numpy array object delta ( optional ) finite difference step Output: gradient function object | def ndgrad(f, delta=DELTA):
"""
Returns numerical gradient function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: gradient function object
"""
def grad_f(*args, **kwargs):
x = args[0]
grad_val... |
Returns numerical hessian function of given input function Input: f scalar function of an numpy array object delta ( optional ) finite difference step Output: hessian function object | def ndhess(f, delta=DELTA):
"""
Returns numerical hessian function of given input function
Input: f, scalar function of an numpy array object
delta(optional), finite difference step
Output: hessian function object
"""
def hess_f(*args, **kwargs):
x = args[0]
hess_val =... |
Returns numerical gradient function of given class method with respect to a class attribute Input: obj general object exe ( str ) name of object method arg ( str ) name of object atribute delta ( float optional ) finite difference step Output: gradient function object | def clgrad(obj, exe, arg, delta=DELTA):
"""
Returns numerical gradient function of given class method
with respect to a class attribute
Input: obj, general object
exe (str), name of object method
arg (str), name of object atribute
delta(float, optional), finite differenc... |
Returns numerical mixed Hessian function of given class method with respect to two class attributes Input: obj general object exe ( str ) name of object method arg1 ( str ) name of object attribute arg2 ( str ) name of object attribute delta ( float optional ) finite difference step Output: Hessian function object | def clmixhess(obj, exe, arg1, arg2, delta=DELTA):
"""
Returns numerical mixed Hessian function of given class method
with respect to two class attributes
Input: obj, general object
exe (str), name of object method
arg1(str), name of object attribute
arg2(str), name of ob... |
Find absolute path to executable cmd in a cross platform manner. | def find_cmd(cmd):
"""Find absolute path to executable cmd in a cross platform manner.
This function tries to determine the full path to a command line program
using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
time it will use the version that is first on the users `PATH`. If
... |
r Take the path of a python command and return a list ( argv - style ). | def pycmd2argv(cmd):
r"""Take the path of a python command and return a list (argv-style).
This only works on Python based command line programs and will find the
location of the ``python`` executable using ``sys.executable`` to make
sure the right version is used.
For a given path ``cmd``, this r... |
Return abbreviated version of cwd e. g. d: mydir | def abbrev_cwd():
""" Return abbreviated version of cwd, e.g. d:mydir """
cwd = os.getcwdu().replace('\\','/')
drivepart = ''
tail = cwd
if sys.platform == 'win32':
if len(cwd) < 4:
return cwd
drivepart,tail = os.path.splitdrive(cwd)
parts = tail.split('/')
if l... |
Construct a list of CodeUnits from polymorphic inputs. | def code_unit_factory(morfs, file_locator):
"""Construct a list of CodeUnits from polymorphic inputs.
`morfs` is a module or a filename, or a list of same.
`file_locator` is a FileLocator that can help resolve filenames.
Returns a list of CodeUnit objects.
"""
# Be sure we have a list.
i... |
A base for a flat filename to correspond to this code unit. | def flat_rootname(self):
"""A base for a flat filename to correspond to this code unit.
Useful for writing files about the code where you want all the files in
the same directory, but need to differentiate same-named files from
different directories.
For example, the file a/b/c... |
Return an open file for reading the source of the code unit. | def source_file(self):
"""Return an open file for reading the source of the code unit."""
if os.path.exists(self.filename):
# A regular text file: open it.
return open_source(self.filename)
# Maybe it's in a zip file?
source = self.file_locator.get_zip_data(self.... |
Does it seem like this file should contain Python? | def should_be_python(self):
"""Does it seem like this file should contain Python?
This is used to decide if a file reported as part of the exection of
a program was really likely to have contained Python in the first
place.
"""
# Get the file extension.
_, ext =... |
timedelta. total_seconds was added in 2. 7 | def _total_seconds(td):
"""timedelta.total_seconds was added in 2.7"""
try:
# Python >= 2.7
return td.total_seconds()
except AttributeError:
# Python 2.6
return 1e-6 * (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) |
Call spin () to sync state prior to calling the method. | def check_ready(f, self, *args, **kwargs):
"""Call spin() to sync state prior to calling the method."""
self.wait(0)
if not self._ready:
raise error.TimeoutError("result not ready")
return f(self, *args, **kwargs) |
Return the result when it arrives. | def get(self, timeout=-1):
"""Return the result when it arrives.
If `timeout` is not ``None`` and the result does not arrive within
`timeout` seconds then ``TimeoutError`` is raised. If the
remote call raised an exception then that exception will be reraised
by get() inside a `R... |
Wait until the result is available or until timeout seconds pass. | def wait(self, timeout=-1):
"""Wait until the result is available or until `timeout` seconds pass.
This method always returns None.
"""
if self._ready:
return
self._ready = self._client.wait(self.msg_ids, timeout)
if self._ready:
try:
... |
Get the results as a dict keyed by engine_id. | def get_dict(self, timeout=-1):
"""Get the results as a dict, keyed by engine_id.
timeout behavior is described in `get()`.
"""
results = self.get(timeout)
engine_ids = [ md['engine_id'] for md in self._metadata ]
bycount = sorted(engine_ids, key=lambda k: engine_ids.co... |
abort my tasks. | def abort(self):
"""abort my tasks."""
assert not self.ready(), "Can't abort, I am already done!"
return self._client.abort(self.msg_ids, targets=self._targets, block=True) |
compute the difference between two sets of timestamps The default behavior is to use the earliest of the first and the latest of the second list but this can be changed by passing a different Parameters ---------- start: one or more datetime objects ( e. g. ar. submitted ) end: one or more datetime objects ( e. g. ar. ... | def timedelta(self, start, end, start_key=min, end_key=max):
"""compute the difference between two sets of timestamps
The default behavior is to use the earliest of the first
and the latest of the second list, but this can be changed
by passing a different
Param... |
the number of tasks which have been completed at this point. Fractional progress would be given by 1. 0 * ar. progress/ len ( ar ) | def progress(self):
"""the number of tasks which have been completed at this point.
Fractional progress would be given by 1.0 * ar.progress / len(ar)
"""
self.wait(0)
return len(self) - len(set(self.msg_ids).intersection(self._client.outstanding)) |
elapsed time since initial submission | def elapsed(self):
"""elapsed time since initial submission"""
if self.ready():
return self.wall_time
now = submitted = datetime.now()
for msg_id in self.msg_ids:
if msg_id in self._client.metadata:
stamp = self._client.metadata[msg_id]['s... |
serial computation time of a parallel calculation Computed as the sum of ( completed - started ) of each task | def serial_time(self):
"""serial computation time of a parallel calculation
Computed as the sum of (completed-started) of each task
"""
t = 0
for md in self._metadata:
t += _total_seconds(md['completed'] - md['started'])
return t |
interactive wait printing progress at regular intervals | def wait_interactive(self, interval=1., timeout=None):
"""interactive wait, printing progress at regular intervals"""
N = len(self)
tic = time.time()
while not self.ready() and (timeout is None or time.time() - tic <= timeout):
self.wait(interval)
clear_output()
... |
republish individual displaypub content dicts | def _republish_displaypub(self, content, eid):
"""republish individual displaypub content dicts"""
try:
ip = get_ipython()
except NameError:
# displaypub is meaningless outside IPython
return
md = content['metadata'] or {}
md['engine'] = eid
... |
wait for the status = idle message that indicates we have all outputs | def _wait_for_outputs(self, timeout=-1):
"""wait for the 'status=idle' message that indicates we have all outputs
"""
if not self._success:
# don't wait on errors
return
tic = time.time()
while not all(md['outputs_ready'] for md in self._metadata):
... |
republish the outputs of the computation Parameters ---------- groupby: str [ default: type ] if type: Group outputs by type ( show all stdout then all stderr etc. ): [ stdout: 1 ] foo [ stdout: 2 ] foo [ stderr: 1 ] bar [ stderr: 2 ] bar if engine: Display outputs for each engine before moving on to the next: [ stdout... | def display_outputs(self, groupby="type"):
"""republish the outputs of the computation
Parameters
----------
groupby : str [default: type]
if 'type':
Group outputs by type (show all stdout, then all stderr, etc.):
... |
iterator for results * as they arrive * on FCFS basis ignoring submission order. | def _unordered_iter(self):
"""iterator for results *as they arrive*, on FCFS basis, ignoring submission order."""
try:
rlist = self.get(0)
except error.TimeoutError:
pending = set(self.msg_ids)
while pending:
try:
self._clie... |
wait for result to complete. | def wait(self, timeout=-1):
"""wait for result to complete."""
start = time.time()
if self._ready:
return
local_ids = filter(lambda msg_id: msg_id in self._client.outstanding, self.msg_ids)
local_ready = self._client.wait(local_ids, timeout)
if local_ready:
... |
Return the absolute normalized form of filename. | def abs_file(filename):
"""Return the absolute normalized form of `filename`."""
path = os.path.expandvars(os.path.expanduser(filename))
path = os.path.abspath(os.path.realpath(path))
path = actual_path(path)
return path |
Prepare the file patterns for use in a FnmatchMatcher. | def prep_patterns(patterns):
"""Prepare the file patterns for use in a `FnmatchMatcher`.
If a pattern starts with a wildcard, it is used as a pattern
as-is. If it does not start with a wildcard, then it is made
absolute with the current directory.
If `patterns` is None, an empty list is returned.... |
Find the path separator used in this string or os. sep if none. | def sep(s):
"""Find the path separator used in this string, or os.sep if none."""
sep_match = re.search(r"[\\/]", s)
if sep_match:
the_sep = sep_match.group(0)
else:
the_sep = os.sep
return the_sep |
Yield all of the importable Python files in dirname recursively. | def find_python_files(dirname):
"""Yield all of the importable Python files in `dirname`, recursively.
To be importable, the files have to be in a directory with a __init__.py,
except for `dirname` itself, which isn't required to have one. The
assumption is that `dirname` was specified directly, so th... |
Return the relative form of filename. | def relative_filename(self, filename):
"""Return the relative form of `filename`.
The filename will be relative to the current directory when the
`FileLocator` was constructed.
"""
fnorm = os.path.normcase(filename)
if fnorm.startswith(self.relative_dir):
fi... |
Return a canonical filename for filename. | def canonical_filename(self, filename):
"""Return a canonical filename for `filename`.
An absolute path with no redundant components and normalized case.
"""
if filename not in self.canonical_filename_cache:
if not os.path.isabs(filename):
for path in [os.cu... |
Get data from filename if it is a zip file path. | def get_zip_data(self, filename):
"""Get data from `filename` if it is a zip file path.
Returns the string data read from the zip file, or None if no zip file
could be found or `filename` isn't in it. The data returned will be
an empty string if the file is empty.
"""
... |
Does fpath indicate a file in one of our trees? | def match(self, fpath):
"""Does `fpath` indicate a file in one of our trees?"""
for d in self.dirs:
if fpath.startswith(d):
if fpath == d:
# This is the same file!
return True
if fpath[len(d)] == os.sep:
... |
Does fpath match one of our filename patterns? | def match(self, fpath):
"""Does `fpath` match one of our filename patterns?"""
for pat in self.pats:
if fnmatch.fnmatch(fpath, pat):
return True
return False |
Add the pattern/ result pair to the list of aliases. | def add(self, pattern, result):
"""Add the `pattern`/`result` pair to the list of aliases.
`pattern` is an `fnmatch`-style pattern. `result` is a simple
string. When mapping paths, if a path starts with a match against
`pattern`, then that match is replaced with `result`. This models... |
Map path through the aliases. | def map(self, path):
"""Map `path` through the aliases.
`path` is checked against all of the patterns. The first pattern to
match is used to replace the root of the path with the result root.
Only one pattern is ever used. If no patterns match, `path` is
returned unchanged.
... |
Start a kernel with PyQt4 event loop integration. | def loop_qt4(kernel):
"""Start a kernel with PyQt4 event loop integration."""
from IPython.external.qt_for_kernel import QtCore
from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
kernel.app = get_app_qt4([" "])
kernel.app.setQuitOnLastWindowClosed(False)
kernel.timer = QtCore... |
Start a kernel with wx event loop support. | def loop_wx(kernel):
"""Start a kernel with wx event loop support."""
import wx
from IPython.lib.guisupport import start_event_loop_wx
doi = kernel.do_one_iteration
# Wx uses milliseconds
poll_interval = int(1000*kernel._poll_interval)
# We have to put the wx.Timer in a wx.Frame for it t... |
Start a kernel with the Tk event loop. | def loop_tk(kernel):
"""Start a kernel with the Tk event loop."""
import Tkinter
doi = kernel.do_one_iteration
# Tk uses milliseconds
poll_interval = int(1000*kernel._poll_interval)
# For Tkinter, we create a Tk object and call its withdraw method.
class Timer(object):
def __init__(... |
Start the kernel coordinating with the GTK event loop | def loop_gtk(kernel):
"""Start the kernel, coordinating with the GTK event loop"""
from .gui.gtkembed import GTKEmbed
gtk_kernel = GTKEmbed(kernel)
gtk_kernel.start() |
Start the kernel coordinating with the Cocoa CFRunLoop event loop via the matplotlib MacOSX backend. | def loop_cocoa(kernel):
"""Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend.
"""
import matplotlib
if matplotlib.__version__ < '1.1.0':
kernel.log.warn(
"MacOSX backend in matplotlib %s doesn't have a Timer, "
"falling back ... |
Enable integration with a given GUI | def enable_gui(gui, kernel=None):
"""Enable integration with a given GUI"""
if gui not in loop_map:
raise ValueError("GUI %r not supported" % gui)
if kernel is None:
if Application.initialized():
kernel = getattr(Application.instance(), 'kernel', None)
if kernel is None:
... |
Creates an NxN element of the Gaussian Orthogonal Ensemble | def GOE(N):
"""Creates an NxN element of the Gaussian Orthogonal Ensemble"""
m = ra.standard_normal((N,N))
m += m.T
return m/2 |
Compute the eigvals of mat and then find the center eigval difference. | def center_eigenvalue_diff(mat):
"""Compute the eigvals of mat and then find the center eigval difference."""
N = len(mat)
evals = np.sort(la.eigvals(mat))
diff = np.abs(evals[N/2] - evals[N/2-1])
return diff |
Return num eigenvalue diffs for the NxN GOE ensemble. | def ensemble_diffs(num, N):
"""Return num eigenvalue diffs for the NxN GOE ensemble."""
diffs = np.empty(num)
for i in xrange(num):
mat = GOE(N)
diffs[i] = center_eigenvalue_diff(mat)
return diffs |
Initialize the item. This calls the class constructor with the appropriate arguments and returns the initialized object. | def init(self, ctxt, step_addr):
"""
Initialize the item. This calls the class constructor with the
appropriate arguments and returns the initialized object.
:param ctxt: The context object.
:param step_addr: The address of the step in the test
configu... |
Parse a YAML file containing test steps. | def parse_file(cls, ctxt, fname, key=None, step_addr=None):
"""
Parse a YAML file containing test steps.
:param ctxt: The context object.
:param fname: The name of the file to parse.
:param key: An optional dictionary key. If specified, the
file must be a YA... |
Parse a step dictionary. | def parse_step(cls, ctxt, step_addr, step_conf):
"""
Parse a step dictionary.
:param ctxt: The context object.
:param step_addr: The address of the step in the test
configuration.
:param step_conf: The description of the step. This may be a
... |
Create a crash handler typically setting sys. excepthook to it. | def init_crash_handler(self):
"""Create a crash handler, typically setting sys.excepthook to it."""
self.crash_handler = self.crash_handler_class(self)
sys.excepthook = self.excepthook
def unset_crashhandler():
sys.excepthook = sys.__excepthook__
atexit.register(unset... |
this is sys. excepthook after init_crashhandler set self. verbose_crash = True to use our full crashhandler instead of a regular traceback with a short message ( crash_handler_lite ) | def excepthook(self, etype, evalue, tb):
"""this is sys.excepthook after init_crashhandler
set self.verbose_crash=True to use our full crashhandler, instead of
a regular traceback with a short message (crash_handler_lite)
"""
if self.verbose_crash:
r... |
Load the config file. | def load_config_file(self, suppress_errors=True):
"""Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
"""
self.log.debug("Sear... |
initialize the profile dir | def init_profile_dir(self):
"""initialize the profile dir"""
try:
# location explicitly specified:
location = self.config.ProfileDir.location
except AttributeError:
# location not specified, find by profile name
try:
p = ProfileDir.... |
[ optionally ] copy default config files into profile dir. | def init_config_files(self):
"""[optionally] copy default config files into profile dir."""
# copy config files
path = self.builtin_profile_dir
if self.copy_config_files:
src = self.profile
cfg = self.config_file_name
if path and os.path.exists(os.pat... |
auto generate default config file and stage it into the profile. | def stage_default_config_file(self):
"""auto generate default config file, and stage it into the profile."""
s = self.generate_config_file()
fname = os.path.join(self.profile_dir.location, self.config_file_name)
if self.overwrite or not os.path.exists(fname):
self.log.warn("G... |
Read coverage data from the coverage data file ( if it exists ). | def read(self):
"""Read coverage data from the coverage data file (if it exists)."""
if self.use_file:
self.lines, self.arcs = self._read_file(self.filename)
else:
self.lines, self.arcs = {}, {} |
Write the collected coverage data to a file. | def write(self, suffix=None):
"""Write the collected coverage data to a file.
`suffix` is a suffix to append to the base file name. This can be used
for multiple or parallel execution, so that many coverage data files
can exist simultaneously. A dot will be used to join the base name a... |
Erase the data both in this object and from its file storage. | def erase(self):
"""Erase the data, both in this object, and from its file storage."""
if self.use_file:
if self.filename:
file_be_gone(self.filename)
self.lines = {}
self.arcs = {} |
Return the map from filenames to lists of line numbers executed. | def line_data(self):
"""Return the map from filenames to lists of line numbers executed."""
return dict(
[(f, sorted(lmap.keys())) for f, lmap in iitems(self.lines)]
) |
Return the map from filenames to lists of line number pairs. | def arc_data(self):
"""Return the map from filenames to lists of line number pairs."""
return dict(
[(f, sorted(amap.keys())) for f, amap in iitems(self.arcs)]
) |
Write the coverage data to filename. | def write_file(self, filename):
"""Write the coverage data to `filename`."""
# Create the file data.
data = {}
data['lines'] = self.line_data()
arcs = self.arc_data()
if arcs:
data['arcs'] = arcs
if self.collector:
data['collector'] = se... |
Read the coverage data from filename. | def read_file(self, filename):
"""Read the coverage data from `filename`."""
self.lines, self.arcs = self._read_file(filename) |
Return the raw pickled data from filename. | def raw_data(self, filename):
"""Return the raw pickled data from `filename`."""
if self.debug and self.debug.should('dataio'):
self.debug.write("Reading data from %r" % (filename,))
fdata = open(filename, 'rb')
try:
data = pickle.load(fdata)
finally:
... |
Return the stored coverage data from the given file. | def _read_file(self, filename):
"""Return the stored coverage data from the given file.
Returns two values, suitable for assigning to `self.lines` and
`self.arcs`.
"""
lines = {}
arcs = {}
try:
data = self.raw_data(filename)
if isinstance... |
Combine a number of data files together. | def combine_parallel_data(self, aliases=None):
"""Combine a number of data files together.
Treat `self.filename` as a file prefix, and combine the data from all
of the data files starting with that prefix plus a dot.
If `aliases` is provided, it's a `PathAliases` object that is used to... |
Add executed line data. | def add_line_data(self, line_data):
"""Add executed line data.
`line_data` is { filename: { lineno: None, ... }, ...}
"""
for filename, linenos in iitems(line_data):
self.lines.setdefault(filename, {}).update(linenos) |
Add measured arc data. | def add_arc_data(self, arc_data):
"""Add measured arc data.
`arc_data` is { filename: { (l1,l2): None, ... }, ...}
"""
for filename, arcs in iitems(arc_data):
self.arcs.setdefault(filename, {}).update(arcs) |
Contribute filename s data to the Md5Hash hasher. | def add_to_hash(self, filename, hasher):
"""Contribute `filename`'s data to the Md5Hash `hasher`."""
hasher.update(self.executed_lines(filename))
hasher.update(self.executed_arcs(filename)) |
Return a dict summarizing the coverage data. | def summary(self, fullpath=False):
"""Return a dict summarizing the coverage data.
Keys are based on the filenames, and values are the number of executed
lines. If `fullpath` is true, then the keys are the full pathnames of
the files, otherwise they are the basenames of the files.
... |
Yield pasted lines until the user enters the given sentinel value. | def get_pasted_lines(sentinel, l_input=py3compat.input):
""" Yield pasted lines until the user enters the given sentinel value.
"""
print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
% sentinel
while True:
try:
l = l_input(':')
if l == s... |
Start the mainloop. | def mainloop(self, display_banner=None):
"""Start the mainloop.
If an optional banner argument is given, it will override the
internally created default banner.
"""
with nested(self.builtin_trap, self.display_trap):
while 1:
try:
... |
Store multiple lines as a single entry in history | def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
"""Store multiple lines as a single entry in history"""
# do nothing without readline or disabled multiline
if not self.has_readline or not self.multiline_history:
return hlen_before_cell
# windows rl has no... |
Closely emulate the interactive Python console. | def interact(self, display_banner=None):
"""Closely emulate the interactive Python console."""
# batch run -> do not interact
if self.exit_now:
return
if display_banner is None:
display_banner = self.display_banner
if isinstance(display_banner, basestri... |
Write a prompt and read a line. | def raw_input(self, prompt=''):
"""Write a prompt and read a line.
The returned line does not include the trailing newline.
When the user enters the EOF key sequence, EOFError is raised.
Optional inputs:
- prompt(''): a string to be printed to prompt the user.
- c... |
The bottom half of the syntax error handler called in the main loop. | def edit_syntax_error(self):
"""The bottom half of the syntax error handler called in the main loop.
Loop until syntax error is fixed or user cancels.
"""
while self.SyntaxTB.last_syntax_error:
# copy and clear last_syntax_error
err = self.SyntaxTB.clear_err_sta... |
Utility routine for edit_syntax_error | def _should_recompile(self,e):
"""Utility routine for edit_syntax_error"""
if e.filename in ('<ipython console>','<input>','<string>',
'<console>','<BackgroundJob compilation>',
None):
return False
try:
if (self.autoed... |
Handle interactive exit. | def exit(self):
"""Handle interactive exit.
This method calls the ask_exit callback."""
if self.confirm_exit:
if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
self.ask_exit()
else:
self.ask_exit() |
Returns the correct repository URL and revision by parsing the given repository URL | def get_url_rev(self):
"""
Returns the correct repository URL and revision by parsing the given
repository URL
"""
error_message= (
"Sorry, '%s' is a malformed VCS url. "
"Ihe format is <vcs>+<protocol>://<url>, "
"e.g. svn+http://myrepo/svn/MyApp... |
register exitable. __exit__ () into atexit module. | def dispose_at_exit(exitable):
'''
register `exitable.__exit__()` into `atexit` module.
return the `exitable` itself.
'''
@atexit.register
def callback():
exitable.__exit__(*sys.exc_info())
return exitable |
Create and return new frontend attached to new kernel launched on localhost. | def new_frontend_master(self):
""" Create and return new frontend attached to new kernel, launched on localhost.
"""
ip = self.ip if self.ip in LOCAL_IPS else LOCALHOST
kernel_manager = self.kernel_manager_class(
ip=ip,
conn... |
Create and return a new frontend attached to an existing kernel. Parameters ---------- current_widget: IPythonWidget The IPythonWidget whose kernel this frontend is to share | def new_frontend_slave(self, current_widget):
"""Create and return a new frontend attached to an existing kernel.
Parameters
----------
current_widget : IPythonWidget
The IPythonWidget whose kernel this frontend is to share
"""
kernel_manager = self.k... |
Configure the coloring of the widget | def init_colors(self, widget):
"""Configure the coloring of the widget"""
# Note: This will be dramatically simplified when colors
# are removed from the backend.
# parse the colors arg down to current known labels
try:
colors = self.config.ZMQInteractiveShell.colors... |
return the connection info for this object s sockets. | def info(self):
"""return the connection info for this object's sockets."""
return (self.identity, self.url, self.pub_url, self.location) |
connect to peers. peers will be a dict of 4 - tuples keyed by name. { peer: ( ident addr pub_addr location ) } where peer is the name ident is the XREP identity addr pub_addr are the | def connect(self, peers):
"""connect to peers. `peers` will be a dict of 4-tuples, keyed by name.
{peer : (ident, addr, pub_addr, location)}
where peer is the name, ident is the XREP identity, addr,pub_addr are the
"""
for peer, (ident, url, pub_url, location) in peers.items():
... |
Convert an object in R s namespace to one suitable for ipython s namespace. | def Rconverter(Robj, dataframe=False):
"""
Convert an object in R's namespace to one suitable
for ipython's namespace.
For a data.frame, it tries to return a structured array.
It first checks for colnames, then names.
If all are NULL, it returns np.asarray(Robj), else
it tries to construct ... |
Return the entire source file and starting line number for an object. | def findsource(object):
"""Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. ... |
Try to fix the filenames in each record from inspect. getinnerframes (). | def fix_frame_records_filenames(records):
"""Try to fix the filenames in each record from inspect.getinnerframes().
Particularly, modules loaded from within zip files have useless filenames
attached to their code object, and inspect.getinnerframes() just uses it.
"""
fixed_records = []
for fram... |
Shorthand access to the color table scheme selector method. | def set_colors(self,*args,**kw):
"""Shorthand access to the color table scheme selector method."""
# Set own color table
self.color_scheme_table.set_active_scheme(*args,**kw)
# for convenience, set Colors to the active scheme
self.Colors = self.color_scheme_table.active_colors
... |
Toggle between the currently active color scheme and NoColor. | def color_toggle(self):
"""Toggle between the currently active color scheme and NoColor."""
if self.color_scheme_table.active_scheme_name == 'NoColor':
self.color_scheme_table.set_active_scheme(self.old_scheme)
self.Colors = self.color_scheme_table.active_colors
else:
... |
Return formatted traceback. | def text(self, etype, value, tb, tb_offset=None, context=5):
"""Return formatted traceback.
Subclasses may override this if they add extra arguments.
"""
tb_list = self.structured_traceback(etype, value, tb,
tb_offset, context)
return ... |
Return a color formatted string with the traceback info. | def structured_traceback(self, etype, value, elist, tb_offset=None,
context=5):
"""Return a color formatted string with the traceback info.
Parameters
----------
etype : exception type
Type of the exception raised.
value : object
... |
Format a list of traceback entry tuples for printing. | def _format_list(self, extracted_list):
"""Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.