Search is not available for this dataset
text stringlengths 75 104k |
|---|
def update_tab_bar_visibility(self):
""" update visibility of the tabBar depending of the number of tab
0 or 1 tab, tabBar hidden
2+ tabs, tabBar visible
send a self.close if number of tab ==0
need to be called explicitly, or be connected to tabInserted/tabRemoved
"""
... |
def create_tab_with_current_kernel(self):
"""create a new frontend attached to the same kernel as the current tab"""
current_widget = self.tab_widget.currentWidget()
current_widget_index = self.tab_widget.indexOf(current_widget)
current_widget_name = self.tab_widget.tabText(current_widge... |
def close_tab(self,current_tab):
""" Called when you need to try to close a tab.
It takes the number of the tab to be closed as argument, or a reference
to the widget inside this tab
"""
# let's be sure "tab" and "closing widget" are respectively the index
# of the tab ... |
def add_tab_with_frontend(self,frontend,name=None):
""" insert a tab with a given frontend in the tab bar, and give it a name
"""
if not name:
name = 'kernel %i' % self.next_kernel_id
self.tab_widget.addTab(frontend,name)
self.update_tab_bar_visibility()
self... |
def find_master_tab(self,tab,as_list=False):
"""
Try to return the frontend that owns the kernel attached to the given widget/tab.
Only finds frontend owned by the current application. Selection
based on port of the kernel might be inaccurate if several kernel
on dif... |
def find_slave_widgets(self,tab):
"""return all the frontends that do not own the kernel attached to the given widget/tab.
Only find frontends owned by the current application. Selection
based on connection file of the kernel.
This function does the conversion tabNumber/wid... |
def add_menu_action(self, menu, action, defer_shortcut=False):
"""Add action to menu as well as self
So that when the menu bar is invisible, its actions are still available.
If defer_shortcut is True, set the shortcut context to widget-only,
where it will avoid conflict... |
def _make_dynamic_magic(self,magic):
"""Return a function `fun` that will execute `magic` on active frontend.
Parameters
----------
magic : string
string that will be executed as is when the returned function is called
Returns
-------
fun : function
... |
def populate_all_magic_menu(self, listofmagic=None):
"""Clean "All Magics..." menu and repopulate it with `listofmagic`
Parameters
----------
listofmagic : string,
repr() of a list of strings, send back by the kernel
Notes
-----
`listofmagic`is a rep... |
def _get_magic_menu(self,menuidentifier, menulabel=None):
"""return a submagic menu by name, and create it if needed
parameters:
-----------
menulabel : str
Label for the menu
Will infere the menu name from the identifier at creation if menulabel not given.
... |
def closeEvent(self, event):
""" Forward the close event to every tabs contained by the windows
"""
if self.tab_widget.count() == 0:
# no tabs, just close
event.accept()
return
# Do Not loop on the widget count as it change while closing
title ... |
def passwd(passphrase=None, algorithm='sha1'):
"""Generate hashed password and salt for use in notebook configuration.
In the notebook configuration, set `c.NotebookApp.password` to
the generated string.
Parameters
----------
passphrase : str
Password to hash. If unspecified, the user... |
def passwd_check(hashed_passphrase, passphrase):
"""Verify that a given passphrase matches its hashed version.
Parameters
----------
hashed_passphrase : str
Hashed password, in the format returned by `passwd`.
passphrase : str
Passphrase to validate.
Returns
-------
val... |
def django_boolean_icon(field_val, alt_text=None, title=None):
"""
Return HTML code for a nice representation of true/false.
"""
# Origin: contrib/admin/templatetags/admin_list.py
BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'}
alt_text = alt_text or BOOLEAN_MAPPING[field_val]
... |
def _build_tree_structure(cls):
"""
Build an in-memory representation of the item tree, trying to keep
database accesses down to a minimum. The returned dictionary looks like
this (as json dump):
{"6": [7, 8, 10]
"7": [12],
"8": [],
...
}
"""
all_node... |
def ajax_editable_boolean_cell(item, attr, text='', override=None):
"""
Generate a html snippet for showing a boolean value on the admin page.
Item is an object, attr is the attribute name we should display. Text
is an optional explanatory text to be included in the output.
This function will emit ... |
def ajax_editable_boolean(attr, short_description):
"""
Convenience function: Assign the return value of this method to a variable
of your ModelAdmin class and put the variable name into list_display.
Example::
class MyTreeEditor(TreeEditor):
list_display = ('__unicode__', 'active_... |
def indented_short_title(self, item):
r = ""
"""
Generate a short title for an object, indent it depending on
the object's depth in the hierarchy.
"""
if hasattr(item, 'get_absolute_url'):
r = '<input type="hidden" class="medialibrary_file_path" value="%s" />'... |
def _collect_editable_booleans(self):
"""
Collect all fields marked as editable booleans. We do not
want the user to be able to edit arbitrary fields by crafting
an AJAX request by hand.
"""
if hasattr(self, '_ajax_editable_booleans'):
return
self._aj... |
def _toggle_boolean(self, request):
"""
Handle an AJAX toggle_boolean request
"""
try:
item_id = int(request.POST.get('item_id', None))
attr = str(request.POST.get('attr', None))
except:
return HttpResponseBadRequest("Malformed request")
... |
def changelist_view(self, request, extra_context=None, *args, **kwargs):
"""
Handle the changelist view, the django view for the model instances
change list/actions page.
"""
if 'actions_column' not in self.list_display:
self.list_display.append('actions_column')
... |
def has_change_permission(self, request, obj=None):
"""
Implement a lookup for object level permissions. Basically the same as
ModelAdmin.has_change_permission, but also passes the obj parameter in.
"""
if settings.TREE_EDITOR_OBJECT_PERMISSIONS:
opts = self.opts
... |
def has_delete_permission(self, request, obj=None):
"""
Implement a lookup for object level permissions. Basically the same as
ModelAdmin.has_delete_permission, but also passes the obj parameter in.
"""
if settings.TREE_EDITOR_OBJECT_PERMISSIONS:
opts = self.opts
... |
def random_dag(nodes, edges):
"""Generate a random Directed Acyclic Graph (DAG) with a given number of nodes and edges."""
G = nx.DiGraph()
for i in range(nodes):
G.add_node(i)
while edges > 0:
a = randint(0,nodes-1)
b=a
while b==a:
b = randint(0,nodes-1)
... |
def add_children(G, parent, level, n=2):
"""Add children recursively to a binary tree."""
if level == 0:
return
for i in range(n):
child = parent+str(i)
G.add_node(child)
G.add_edge(parent,child)
add_children(G, child, level-1, n) |
def make_bintree(levels):
"""Make a symmetrical binary tree with @levels"""
G = nx.DiGraph()
root = '0'
G.add_node(root)
add_children(G, root, levels, 2)
return G |
def submit_jobs(view, G, jobs):
"""Submit jobs via client where G describes the time dependencies."""
results = {}
for node in nx.topological_sort(G):
with view.temp_flags(after=[ results[n] for n in G.predecessors(node) ]):
results[node] = view.apply(jobs[node])
return results |
def validate_tree(G, results):
"""Validate that jobs executed after their dependencies."""
for node in G:
started = results[node].metadata.started
for parent in G.predecessors(node):
finished = results[parent].metadata.completed
assert started > finished, "%s should have ... |
def main(nodes, edges):
"""Generate a random graph, submit jobs, then validate that the
dependency order was enforced.
Finally, plot the graph, with time on the x-axis, and
in-degree on the y (just for spread). All arrows must
point at least slightly to the right if the graph is valid.
"""
... |
def make_color_table(in_class):
"""Build a set of color attributes in a class.
Helper function for building the *TermColors classes."""
for name,value in color_templates:
setattr(in_class,name,in_class._base % value) |
def copy(self,name=None):
"""Return a full copy of the object, optionally renaming it."""
if name is None:
name = self.name
return ColorScheme(name, self.colors.dict()) |
def add_scheme(self,new_scheme):
"""Add a new color scheme to the table."""
if not isinstance(new_scheme,ColorScheme):
raise ValueError,'ColorSchemeTable only accepts ColorScheme instances'
self[new_scheme.name] = new_scheme |
def set_active_scheme(self,scheme,case_sensitive=0):
"""Set the currently active scheme.
Names are by default compared in a case-insensitive way, but this can
be changed by setting the parameter case_sensitive to true."""
scheme_names = self.keys()
if case_sensitive:
... |
def home_lib(home):
"""Return the lib dir under the 'home' installation scheme"""
if hasattr(sys, 'pypy_version_info'):
lib = 'site-packages'
else:
lib = os.path.join('lib', 'python')
return os.path.join(home, lib) |
def cache(descriptor=None, *, store: IStore = None):
'''
usage:
``` py
@cache
@property
def name(self): pass
```
'''
if descriptor is None:
return functools.partial(cache, store=store)
hasattrs = {
'get': hasattr(descriptor, '__get__'),
'set': hasattr(d... |
def init_completer(self):
"""Initialize the completion machinery.
This creates completion machinery that can be used by client code,
either interactively in-process (typically triggered by the readline
library), programatically (such as in test suites) or out-of-prcess
(typicall... |
def run_cell(self, cell, store_history=True):
"""Run a complete IPython cell.
Parameters
----------
cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored ... |
def handle_iopub(self):
""" Method to procces subscribe channel's messages
This method reads a message and processes the content in different
outputs like stdout, stderr, pyout and status
Arguments:
sub_msg: message receive from kernel in the sub socket channel
... |
def handle_stdin_request(self, timeout=0.1):
""" Method to capture raw_input
"""
msg_rep = self.km.stdin_channel.get_msg(timeout=timeout)
# in case any iopub came while we were waiting:
self.handle_iopub()
if self.session_id == msg_rep["parent_header"].get("session"):
... |
def wait_for_kernel(self, timeout=None):
"""method to wait for a kernel to be ready"""
tic = time.time()
self.km.hb_channel.unpause()
while True:
self.run_cell('1', False)
if self.km.hb_channel.is_beating():
# heart failure was not the reason this ... |
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, ... |
def get_tokens_unprocessed(self, text, stack=('root',)):
""" Split ``text`` into (tokentype, text) pairs.
Monkeypatched to store the final stack on the object itself.
"""
pos = 0
tokendefs = self._tokens
if hasattr(self, '_saved_state_stack'):
statestack = list(self._saved_state_sta... |
def set_style(self, style):
""" Sets the style to the specified Pygments style.
"""
if isinstance(style, basestring):
style = get_style_by_name(style)
self._style = style
self._clear_caches() |
def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token in self._formats:
return self._formats[token]
if self._style is None:
result = self._get_format_from_document(token, self._document)
else:
result = sel... |
def _get_format_from_document(self, token, document):
""" Returns a QTextCharFormat for token by
"""
code, html = self._formatter._format_lines([(token, u'dummy')]).next()
self._document.setHtml(html)
return QtGui.QTextCursor(self._document).charFormat() |
def _get_format_from_style(self, token, style):
""" Returns a QTextCharFormat for token by reading a Pygments style.
"""
result = QtGui.QTextCharFormat()
for key, value in style.style_for_token(token).items():
if value:
if key == 'color':
r... |
def find_command(cmd, paths=None, pathext=None):
"""Searches the PATH for the given command and returns its path"""
if paths is None:
paths = os.environ.get('PATH', '').split(os.pathsep)
if isinstance(paths, six.string_types):
paths = [paths]
# check if there are funny path extensions fo... |
def normalize_path(path):
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
return os.path.normcase(os.path.realpath(os.path.expanduser(path))) |
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
assert_string_list(dist,attr,value)
for nsp in value:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"name... |
def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
for k,v in value.items():
list(pkg_resources.parse_requirements(v))
except (TypeError,ValueError,AttributeError):
raise DistutilsSetupError(
"'extras_require' must be a diction... |
def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
pkg_resources.EntryPoint.parse_map(value)
except ValueError, e:
raise DistutilsSetupError(e) |
def handle_display_options(self, option_order):
"""If there were any non-global "display-only" options
(--help-commands or the metadata display options) on the command
line, display the requested info and return true; else return
false.
"""
import sys
if sys.vers... |
def last_blank(src):
"""Determine if the input source ends in a blank.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string.
"""
if not src: return False
ll = src.splitlines()[-1]
return (ll == '') or... |
def last_two_blanks(src):
"""Determine if the input source ends in two blanks.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string.
"""
if not src: return False
# The logic here is tricky: I couldn't get ... |
def has_comment(src):
"""Indicate whether an input line has (i.e. ends in, or is) a comment.
This uses tokenize, so it can distinguish comments from # inside strings.
Parameters
----------
src : string
A single line input string.
Returns
-------
Boolean: True if sour... |
def transform_assign_system(line):
"""Handle the `files = !ls` syntax."""
m = _assign_system_re.match(line)
if m is not None:
cmd = m.group('cmd')
lhs = m.group('lhs')
new_line = '%s = get_ipython().getoutput(%r)' % (lhs, cmd)
return new_line
return line |
def transform_assign_magic(line):
"""Handle the `a = %who` syntax."""
m = _assign_magic_re.match(line)
if m is not None:
cmd = m.group('cmd')
lhs = m.group('lhs')
new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd)
return new_line
return line |
def transform_classic_prompt(line):
"""Handle inputs that start with '>>> ' syntax."""
if not line or line.isspace():
return line
m = _classic_prompt_re.match(line)
if m:
return line[len(m.group(0)):]
else:
return line |
def transform_ipy_prompt(line):
"""Handle inputs that start classic IPython prompt syntax."""
if not line or line.isspace():
return line
#print 'LINE: %r' % line # dbg
m = _ipy_prompt_re.match(line)
if m:
#print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
retur... |
def _make_help_call(target, esc, lspace, next_input=None):
"""Prepares a pinfo(2)/psearch call from a target name and the escape
(i.e. ? or ??)"""
method = 'pinfo2' if esc == '??' \
else 'psearch' if '*' in target \
else 'pinfo'
arg = " ".join([method, target])
if ne... |
def transform_help_end(line):
"""Translate lines with ?/?? at the end"""
m = _help_end_re.search(line)
if m is None or has_comment(line):
return line
target = m.group(1)
esc = m.group(3)
lspace = _initial_space_re.match(line).group(0)
# If we're mid-command, put it back on the n... |
def reset(self):
"""Reset the input buffer and associated state."""
self.indent_spaces = 0
self._buffer[:] = []
self.source = ''
self.code = None
self._is_complete = False
self._full_dedent = False |
def push(self, lines):
"""Push one or more lines of input.
This stores the given lines and returns a status code indicating
whether the code forms a complete Python block or not.
Any exceptions generated in compilation are swallowed, but if an
exception was produced, the method... |
def push_accepts_more(self):
"""Return whether a block of interactive input can accept more input.
This method is meant to be used by line-oriented frontends, who need to
guess whether a block is complete or not based solely on prior and
current input lines. The InputSplitter considers... |
def _find_indent(self, line):
"""Compute the new indentation level for a single line.
Parameters
----------
line : str
A single new line of non-whitespace, non-comment Python input.
Returns
-------
indent_spaces : int
New value for ... |
def _store(self, lines, buffer=None, store='source'):
"""Store one or more lines of input.
If input lines are not newline-terminated, a newline is automatically
appended."""
if buffer is None:
buffer = self._buffer
if lines.endswith('\n'):
... |
def _tr_system(line_info):
"Translate lines escaped with: !"
cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
return '%sget_ipython().system(%r)' % (line_info.pre, cmd) |
def _tr_help(line_info):
"Translate lines escaped with: ?/??"
# A naked help line should just fire the intro help screen
if not line_info.line[1:]:
return 'get_ipython().show_usage()'
return _make_help_call(line_info.ifun, line_info.esc, line_info.pre) |
def _tr_magic(line_info):
"Translate lines escaped with: %"
tpl = '%sget_ipython().magic(%r)'
cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
return tpl % (line_info.pre, cmd) |
def _tr_quote(line_info):
"Translate lines escaped with: ,"
return '%s%s("%s")' % (line_info.pre, line_info.ifun,
'", "'.join(line_info.the_rest.split()) ) |
def _tr_paren(line_info):
"Translate lines escaped with: /"
return '%s%s(%s)' % (line_info.pre, line_info.ifun,
", ".join(line_info.the_rest.split())) |
def reset(self):
"""Reset the input buffer and associated state."""
super(IPythonInputSplitter, self).reset()
self._buffer_raw[:] = []
self.source_raw = ''
self.cell_magic_parts = []
self.processing_cell_magic = False |
def source_raw_reset(self):
"""Return input and raw source and perform a full reset.
"""
out = self.source
out_r = self.source_raw
self.reset()
return out, out_r |
def _handle_cell_magic(self, lines):
"""Process lines when they start with %%, which marks cell magics.
"""
self.processing_cell_magic = True
first, _, body = lines.partition('\n')
magic_name, _, line = first.partition(' ')
magic_name = magic_name.lstrip(ESC_MAGIC)
... |
def _line_mode_cell_append(self, lines):
"""Append new content for a cell magic in line mode.
"""
# Only store the raw input. Lines beyond the first one are only only
# stored for history purposes; for execution the caller will grab the
# magic pieces from cell_magic_parts and w... |
def transform_cell(self, cell):
"""Process and translate a cell of input.
"""
self.reset()
self.push(cell)
return self.source_reset() |
def push(self, lines):
"""Push one or more lines of IPython input.
This stores the given lines and returns a status code indicating
whether the code forms a complete Python block or not, after processing
all input lines for special IPython syntax.
Any exceptions generated in co... |
def _init_observers(self):
"""Initialize observer storage"""
self.registered_types = set() #set of types that are observed
self.registered_senders = set() #set of senders that are observed
self.observers = {} |
def post_notification(self, ntype, sender, *args, **kwargs):
"""Post notification to all registered observers.
The registered callback will be called as::
callback(ntype, sender, *args, **kwargs)
Parameters
----------
ntype : hashable
The notification t... |
def _observers_for_notification(self, ntype, sender):
"""Find all registered observers that should recieve notification"""
keys = (
(ntype,sender),
(ntype, None),
(None, sender),
(None,None)
)
obs = set(... |
def add_observer(self, callback, ntype, sender):
"""Add an observer callback to this notification center.
The given callback will be called upon posting of notifications of
the given type/sender and will receive any additional arguments passed
to post_notification.
Parameters
... |
def new(self, func_or_exp, *args, **kwargs):
"""Add a new background job and start it in a separate thread.
There are two types of jobs which can be created:
1. Jobs based on expressions which can be passed to an eval() call.
The expression must be given as a string. For example:
... |
def _update_status(self):
"""Update the status of the job lists.
This method moves finished jobs to one of two lists:
- self.completed: jobs which completed successfully
- self.dead: jobs which finished but died.
It also copies those jobs to corresponding _report lists. Th... |
def _group_report(self,group,name):
"""Report summary for a given job group.
Return True if the group had any elements."""
if group:
print '%s jobs:' % name
for job in group:
print '%s : %s' % (job.num,job)
print
return True |
def _group_flush(self,group,name):
"""Flush a given job group
Return True if the group had any elements."""
njobs = len(group)
if njobs:
plural = {1:''}.setdefault(njobs,'s')
print 'Flushing %s %s job%s.' % (njobs,name,plural)
group[:] = []
... |
def _status_new(self):
"""Print the status of newly finished jobs.
Return True if any new jobs are reported.
This call resets its own state every time, so it only reports jobs
which have finished since the last time it was called."""
self._update_status()
new_comp = se... |
def status(self,verbose=0):
"""Print a status of all jobs currently being managed."""
self._update_status()
self._group_report(self.running,'Running')
self._group_report(self.completed,'Completed')
self._group_report(self.dead,'Dead')
# Also flush the report queues
... |
def remove(self,num):
"""Remove a finished (completed or dead) job."""
try:
job = self.all[num]
except KeyError:
error('Job #%s not found' % num)
else:
stat_code = job.stat_code
if stat_code == self._s_running:
error('Job #... |
def flush(self):
"""Flush all finished jobs (completed and dead) from lists.
Running jobs are never flushed.
It first calls _status_new(), to update info. If any jobs have
completed since the last _status_new() call, the flush operation
aborts."""
# Remove the finished... |
def result(self,num):
"""result(N) -> return the result of job N."""
try:
return self.all[num].result
except KeyError:
error('Job #%s not found' % num) |
def _init(self):
"""Common initialization for all BackgroundJob objects"""
for attr in ['call','strform']:
assert hasattr(self,attr), "Missing attribute <%s>" % attr
# The num tag can be set by an external job manager
self.num = None
self.stat... |
def insert(self, idx, value):
"""
Inserts a value in the ``ListVariable`` at an appropriate index.
:param idx: The index before which to insert the new value.
:param value: The value to insert.
"""
self._value.insert(idx, value)
self._rebuild() |
def copy(self):
"""
Retrieve a copy of the Environment. Note that this is a shallow
copy.
"""
return self.__class__(self._data.copy(), self._sensitive.copy(),
self._cwd) |
def _declare_special(self, name, sep, klass):
"""
Declare an environment variable as a special variable. This can
be used even if the environment variable is not present.
:param name: The name of the environment variable that should
be considered special.
:... |
def declare_list(self, name, sep=os.pathsep):
"""
Declare an environment variable as a list-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
be considered l... |
def declare_set(self, name, sep=os.pathsep):
"""
Declare an environment variable as a set-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
be considered set... |
def call(self, args, **kwargs):
"""
A thin wrapper around ``subprocess.Popen``. Takes the same
options as ``subprocess.Popen``, with the exception of the
``cwd``, and ``env`` parameters, which come from the
``Environment`` instance. Note that if the sole positional
argu... |
def cwd(self, value):
"""
Change the working directory that processes should be executed in.
:param value: The new path to change to. If relative, will be
interpreted relative to the current working
directory.
"""
self._cwd = utils.c... |
def move(self, state=None):
"""Swaps two cities in the route.
:type state: TSPState
"""
state = self.state if state is None else state
route = state
a = random.randint(self.locked_range, len(route) - 1)
b = random.randint(self.locked_range, len(route) - 1)
... |
def energy(self, state=None):
"""Calculates the length of the route."""
state = self.state if state is None else state
route = state
e = 0
if self.distance_matrix:
for i in range(len(route)):
e += self.distance_matrix["{},{}".format(route[i-1], route[i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.