_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q279200 | Index.search | test | def search(self, query, verbose=0):
"""Searches files satisfying query
It first decompose the query in ngrams, then score each document containing
at least one ngram with the number. The ten document having the most ngrams
in common with the query are selected.
Args:
... | python | {
"resource": ""
} |
q279201 | partition | test | def partition(condition, collection) -> Tuple[List, List]:
"""Partitions a list into two based on a condition."""
succeed, fail = [], []
for x in collection:
if condition(x):
succeed.append(x)
else:
fail.append(x)
return succeed, fail | python | {
"resource": ""
} |
q279202 | run | test | def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path,
verbose):
"""
Runs the program. Takes a list of postcodes or coordinates and
returns various information about them. If using the cli, make
sure to update the bikes database with t... | python | {
"resource": ""
} |
q279203 | bidi | test | def bidi(request):
"""Adds to the context BiDi related variables
LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl')
LANGUAGE_START -- Start of language layout ('right' for rtl, 'left'
for 'ltr')
LANGUAGE_END -- End of language layout ('left' for rtl, 'right'
... | python | {
"resource": ""
} |
q279204 | _find_link | test | def _find_link(inst1, inst2, rel_id, phrase):
'''
Find links that correspond to the given arguments.
'''
metaclass1 = get_metaclass(inst1)
metaclass2 = get_metaclass(inst2)
if isinstance(rel_id, int):
rel_id = 'R%d' % rel_id
for ass in metaclass1.metamodel.associations:
... | python | {
"resource": ""
} |
q279205 | Association.formalize | test | def formalize(self):
'''
Formalize the association and expose referential attributes
on instances.
'''
source_class = self.source_link.to_metaclass
target_class = self.target_link.to_metaclass
source_class.referential_attributes |= set(self.source_keys)
... | python | {
"resource": ""
} |
q279206 | Link.compute_lookup_key | test | def compute_lookup_key(self, from_instance):
'''
Compute the lookup key for an instance, i.e. a foreign key that
can be used to identify an instance at the end of the link.
'''
kwargs = dict()
for attr, other_attr in self.key_map.items():
if _is_null(from_inst... | python | {
"resource": ""
} |
q279207 | Link.compute_index_key | test | def compute_index_key(self, to_instance):
'''
Compute the index key that can be used to identify an instance
on the link.
'''
kwargs = dict()
for attr in self.key_map.values():
if _is_null(to_instance, attr):
return None
... | python | {
"resource": ""
} |
q279208 | MetaClass.attribute_type | test | def attribute_type(self, attribute_name):
'''
Obtain the type of an attribute.
'''
attribute_name = attribute_name.upper()
for name, ty in self.attributes:
if name.upper() == attribute_name:
return ty | python | {
"resource": ""
} |
q279209 | MetaClass.new | test | def new(self, *args, **kwargs):
'''
Create and return a new instance.
'''
inst = self.clazz()
self.storage.append(inst)
# set all attributes with an initial default value
referential_attributes = dict()
for name, ty in self.attributes:
... | python | {
"resource": ""
} |
q279210 | MetaModel.instances | test | def instances(self):
'''
Obtain a sequence of all instances in the metamodel.
'''
for metaclass in self.metaclasses.values():
for inst in metaclass.storage:
yield inst | python | {
"resource": ""
} |
q279211 | MetaModel.define_class | test | def define_class(self, kind, attributes, doc=''):
'''
Define a new class in the metamodel, and return its metaclass.
'''
ukind = kind.upper()
if ukind in self.metaclasses:
raise MetaModelException('A class with the name %s is already defined' % kind)
metaclas... | python | {
"resource": ""
} |
q279212 | send | test | def send(socket, header, payload, topics=(), flags=0):
"""Sends header, payload, and topics through a ZeroMQ socket.
:param socket: a zmq socket.
:param header: a list of byte strings which represent a message header.
:param payload: the serialized byte string of a payload.
:param topics: a chain o... | python | {
"resource": ""
} |
q279213 | recv | test | def recv(socket, flags=0, capture=(lambda msgs: None)):
"""Receives header, payload, and topics through a ZeroMQ socket.
:param socket: a zmq socket.
:param flags: zmq flags to receive messages.
:param capture: a function to capture received messages.
"""
msgs = eintr_retry_zmq(socket.recv_mul... | python | {
"resource": ""
} |
q279214 | dead_code | test | def dead_code():
"""
This also finds code you are working on today!
"""
with safe_cd(SRC):
if IS_TRAVIS:
command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split()
else:
command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split()
... | python | {
"resource": ""
} |
q279215 | parse_emails | test | def parse_emails(values):
'''
Take a string or list of strings and try to extract all the emails
'''
emails = []
if isinstance(values, str):
values = [values]
# now we know we have a list of strings
for value in values:
matches = re_emails.findall(value)
emails.extend... | python | {
"resource": ""
} |
q279216 | rpc | test | def rpc(f=None, **kwargs):
"""Marks a method as RPC."""
if f is not None:
if isinstance(f, six.string_types):
if 'name' in kwargs:
raise ValueError('name option duplicated')
kwargs['name'] = f
else:
return rpc(**kwargs)(f)
return functools.... | python | {
"resource": ""
} |
q279217 | rpc_spec_table | test | def rpc_spec_table(app):
"""Collects methods which are speced as RPC."""
table = {}
for attr, value in inspect.getmembers(app):
rpc_spec = get_rpc_spec(value, default=None)
if rpc_spec is None:
continue
table[rpc_spec.name] = (value, rpc_spec)
return table | python | {
"resource": ""
} |
q279218 | normalize_postcode_middleware | test | async def normalize_postcode_middleware(request, handler):
"""
If there is a postcode in the url it validates and normalizes it.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
if postcode is None or postcode == "random":
return await handler(request)
elif not is_... | python | {
"resource": ""
} |
q279219 | IdGenerator.next | test | def next(self):
'''
Progress to the next identifier, and return the current one.
'''
val = self._current
self._current = self.readfunc()
return val | python | {
"resource": ""
} |
q279220 | MyWalker.accept_S_SYS | test | def accept_S_SYS(self, inst):
'''
A System Model contains top-level packages
'''
for child in many(inst).EP_PKG[1401]():
self.accept(child) | python | {
"resource": ""
} |
q279221 | MyWalker.accept_C_C | test | def accept_C_C(self, inst):
'''
A Component contains packageable elements
'''
for child in many(inst).PE_PE[8003]():
self.accept(child) | python | {
"resource": ""
} |
q279222 | MyWalker.accept_EP_PKG | test | def accept_EP_PKG(self, inst):
'''
A Package contains packageable elements
'''
for child in many(inst).PE_PE[8000]():
self.accept(child) | python | {
"resource": ""
} |
q279223 | LightSensor.get_brightness | test | def get_brightness(self):
"""
Return the average brightness of the image.
"""
# Only download the image if it has changed
if not self.connection.has_changed():
return self.image_brightness
image_path = self.connection.download_image()
converted_image... | python | {
"resource": ""
} |
q279224 | switch.match | test | def match(self, *args):
"""
Indicate whether or not to enter a case suite.
usage:
``` py
for case in switch(value):
if case('A'):
pass
elif case(1, 3):
pass # for mulit-match.
else:
pass # for d... | python | {
"resource": ""
} |
q279225 | BracketMatcher._find_match | test | def _find_match(self, position):
""" Given a valid position in the text document, try to find the
position of the matching bracket. Returns -1 if unsuccessful.
"""
# Decide what character to search for and what direction to search in.
document = self._text_edit.document()
... | python | {
"resource": ""
} |
q279226 | BracketMatcher._selection_for_character | test | def _selection_for_character(self, position):
""" Convenience method for selecting a character.
"""
selection = QtGui.QTextEdit.ExtraSelection()
cursor = self._text_edit.textCursor()
cursor.setPosition(position)
cursor.movePosition(QtGui.QTextCursor.NextCharacter,
... | python | {
"resource": ""
} |
q279227 | BracketMatcher._cursor_position_changed | test | def _cursor_position_changed(self):
""" Updates the document formatting based on the new cursor position.
"""
# Clear out the old formatting.
self._text_edit.setExtraSelections([])
# Attempt to match a bracket for the new cursor position.
cursor = self._text_edit.textCur... | python | {
"resource": ""
} |
q279228 | ContextSuite._exc_info | test | def _exc_info(self):
"""Bottleneck to fix up IronPython string exceptions
"""
e = self.exc_info()
if sys.platform == 'cli':
if isinstance(e[0], StringException):
# IronPython throws these StringExceptions, but
# traceback checks type(etype) == ... | python | {
"resource": ""
} |
q279229 | create_inputhook_qt4 | test | def create_inputhook_qt4(mgr, app=None):
"""Create an input hook for running the Qt4 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, an... | python | {
"resource": ""
} |
q279230 | Mapper.get | test | def get(cls, name=__name__):
"""Return a Mapper instance with the given name.
If the name already exist return its instance.
Does not work if a Mapper was created via its constructor.
Using `Mapper.get()`_ is the prefered way.
Args:
name (str, optional): N... | python | {
"resource": ""
} |
q279231 | Mapper.url | test | def url(self, pattern, method=None, type_cast=None):
"""Decorator for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits yo... | python | {
"resource": ""
} |
q279232 | Mapper.s_url | test | def s_url(self, path, method=None, type_cast=None):
"""Decorator for registering a simple path.
Args:
path (str): Path to be matched.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
... | python | {
"resource": ""
} |
q279233 | Mapper.add | test | def add(self, pattern, function, method=None, type_cast=None):
"""Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to d... | python | {
"resource": ""
} |
q279234 | Mapper.s_add | test | def s_add(self, path, function, method=None, type_cast=None):
"""Function for registering a simple path.
Args:
path (str): Path to be matched.
function (function): Function to associate with this path.
method (str, optional): Usually used to define one of GET, POST,
... | python | {
"resource": ""
} |
q279235 | Mapper.call | test | def call(self, url, method=None, args=None):
"""Calls the first function matching the urls pattern and method.
Args:
url (str): Url for which to call a matching function.
method (str, optional): The method used while registering a
function.
Defaul... | python | {
"resource": ""
} |
q279236 | HistoryConsoleWidget.execute | test | def execute(self, source=None, hidden=False, interactive=False):
""" Reimplemented to the store history.
"""
if not hidden:
history = self.input_buffer if source is None else source
executed = super(HistoryConsoleWidget, self).execute(
source, hidden, interactive... | python | {
"resource": ""
} |
q279237 | HistoryConsoleWidget._up_pressed | test | def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():
# Bail out if we're lo... | python | {
"resource": ""
} |
q279238 | HistoryConsoleWidget._down_pressed | test | def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
end_cursor = self._get_end_cursor()
if self._get_cursor().blockNumber() == end_cursor.blockNumber():
# Bail out if we're locked.... | python | {
"resource": ""
} |
q279239 | HistoryConsoleWidget.history_previous | test | def history_previous(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a previous history item.
Parameters:
-----------
substring : str, optional
If specified, search for an item with this substring.
as_prefix : bool, optional
... | python | {
"resource": ""
} |
q279240 | HistoryConsoleWidget.history_next | test | def history_next(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a subsequent history item.
Parameters:
-----------
substring : str, optional
If specified, search for an item with this substring.
as_prefix : bool, optional
If... | python | {
"resource": ""
} |
q279241 | HistoryConsoleWidget._handle_execute_reply | test | def _handle_execute_reply(self, msg):
""" Handles replies for code execution, here only session history length
"""
msg_id = msg['parent_header']['msg_id']
info = self._request_info['execute'].pop(msg_id,None)
if info and info.kind == 'save_magic' and not self._hidden:
... | python | {
"resource": ""
} |
q279242 | HistoryConsoleWidget._history_locked | test | def _history_locked(self):
""" Returns whether history movement is locked.
"""
return (self.history_lock and
(self._get_edited_history(self._history_index) !=
self.input_buffer) and
(self._get_prompt_cursor().blockNumber() !=
self... | python | {
"resource": ""
} |
q279243 | HistoryConsoleWidget._get_edited_history | test | def _get_edited_history(self, index):
""" Retrieves a history item, possibly with temporary edits.
"""
if index in self._history_edits:
return self._history_edits[index]
elif index == len(self._history):
return unicode()
return self._history[index] | python | {
"resource": ""
} |
q279244 | HistoryConsoleWidget._set_history | test | def _set_history(self, history):
""" Replace the current history with a sequence of history items.
"""
self._history = list(history)
self._history_edits = {}
self._history_index = len(self._history) | python | {
"resource": ""
} |
q279245 | HistoryConsoleWidget._store_edits | test | def _store_edits(self):
""" If there are edits to the current input buffer, store them.
"""
current = self.input_buffer
if self._history_index == len(self._history) or \
self._history[self._history_index] != current:
self._history_edits[self._history_index] = ... | python | {
"resource": ""
} |
q279246 | MyFrame.OnTimeToClose | test | def OnTimeToClose(self, evt):
"""Event handler for the button click."""
print("See ya later!")
sys.stdout.flush()
self.cleanup_consoles(evt)
self.Close()
# Not sure why, but our IPython kernel seems to prevent normal WX
# shutdown, so an explicit exit() call is ne... | python | {
"resource": ""
} |
q279247 | build_collection | test | def build_collection(df, **kwargs):
'''
Generates a list of Record objects given a DataFrame.
Each Record instance has a series attribute which is a pandas.Series of the same attributes
in the DataFrame.
Optional data can be passed in through kwargs which will be included by the name of each object... | python | {
"resource": ""
} |
q279248 | collection_to_df | test | def collection_to_df(collection):
'''
Converts a collection back into a pandas DataFrame
parameters
----------
collection : list
list of Record objects where each Record represents one row from a dataframe
Returns
-------
df : pandas.DataFrame
DataFrame of length=len(c... | python | {
"resource": ""
} |
q279249 | spin_frame | test | def spin_frame(df, method):
'''
Runs the full turntable process on a pandas DataFrame
parameters
----------
df : pandas.DataFrame
each row represents a record
method : def method(record)
function used to process each row
Returns
-------
df : pandas.DataFrame
... | python | {
"resource": ""
} |
q279250 | RecordSetter.set_attributes | test | def set_attributes(self, kwargs):
'''
Initalizes the given argument structure as properties of the class
to be used by name in specific method execution.
Parameters
----------
kwargs : dictionary
Dictionary of extra attributes,
where keys are attr... | python | {
"resource": ""
} |
q279251 | LogWatcher.subscribe | test | def subscribe(self):
"""Update our SUB socket's subscriptions."""
self.stream.setsockopt(zmq.UNSUBSCRIBE, '')
if '' in self.topics:
self.log.debug("Subscribing to: everything")
self.stream.setsockopt(zmq.SUBSCRIBE, '')
else:
for topic in self.topics:
... | python | {
"resource": ""
} |
q279252 | LogWatcher.log_message | test | def log_message(self, raw):
"""receive and parse a message, then log it."""
if len(raw) != 2 or '.' not in raw[0]:
self.log.error("Invalid log message: %s"%raw)
return
else:
topic, msg = raw
# don't newline, since log messages always newline:
... | python | {
"resource": ""
} |
q279253 | mergesort | test | def mergesort(list_of_lists, key=None):
""" Perform an N-way merge operation on sorted lists.
@param list_of_lists: (really iterable of iterable) of sorted elements
(either by naturally or by C{key})
@param key: specify sort key function (like C{sort()}, C{sorted()})
Yields tuples of the form C{(i... | python | {
"resource": ""
} |
q279254 | remote_iterator | test | def remote_iterator(view,name):
"""Return an iterator on an object living on a remote engine.
"""
view.execute('it%s=iter(%s)'%(name,name), block=True)
while True:
try:
result = view.apply_sync(lambda x: x.next(), Reference('it'+name))
# This causes the StopIteration exceptio... | python | {
"resource": ""
} |
q279255 | convert_to_this_nbformat | test | def convert_to_this_nbformat(nb, orig_version=1):
"""Convert a notebook to the v2 format.
Parameters
----------
nb : NotebookNode
The Python representation of the notebook to convert.
orig_version : int
The original version of the notebook to convert.
"""
if orig_version == ... | python | {
"resource": ""
} |
q279256 | get_supported_platform | test | def get_supported_platform():
"""Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version o... | python | {
"resource": ""
} |
q279257 | get_importer | test | def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[... | python | {
"resource": ""
} |
q279258 | StringIO | test | def StringIO(*args, **kw):
"""Thunk to load the real StringIO on demand"""
global StringIO
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return StringIO(*args,**kw) | python | {
"resource": ""
} |
q279259 | parse_version | test | def parse_version(s):
"""Convert a version string to a chronologically-sortable key
This is a rough cross between distutils' StrictVersion and LooseVersion;
if you give it versions that would work with StrictVersion, then it behaves
the same; otherwise it acts like a slightly-smarter LooseVersion. It i... | python | {
"resource": ""
} |
q279260 | _override_setuptools | test | def _override_setuptools(req):
"""Return True when distribute wants to override a setuptools dependency.
We want to override when the requirement is setuptools and the version is
a variant of 0.6.
"""
if req.project_name == 'setuptools':
if not len(req.specs):
# Just setuptools... | python | {
"resource": ""
} |
q279261 | WorkingSet.add | test | def add(self, dist, entry=None, insert=True, replace=False):
"""Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set's ``.entries`` (if it wasn'... | python | {
"resource": ""
} |
q279262 | WorkingSet.find_plugins | test | def find_plugins(self,
plugin_env, full_env=None, installer=None, fallback=True
):
"""Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
)
map(w... | python | {
"resource": ""
} |
q279263 | ResourceManager.get_cache_path | test | def get_cache_path(self, archive_name, names=()):
"""Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not ... | python | {
"resource": ""
} |
q279264 | EntryPoint.parse | test | def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
""... | python | {
"resource": ""
} |
q279265 | DistInfoDistribution._parsed_pkg_info | test | def _parsed_pkg_info(self):
"""Parse and cache metadata"""
try:
return self._pkg_info
except AttributeError:
from email.parser import Parser
self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))
return self._pkg_info | python | {
"resource": ""
} |
q279266 | DistInfoDistribution._compute_dependencies | test | def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
from _markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') ... | python | {
"resource": ""
} |
q279267 | parse_filename | test | def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, no... | python | {
"resource": ""
} |
q279268 | _collapse_leading_ws | test | def _collapse_leading_ws(header, txt):
"""
``Description`` header must preserve newlines; all others need not
"""
if header.lower() == 'description': # preserve newlines
return '\n'.join([x[8:] if x.startswith(' ' * 8) else x
for x in txt.strip().splitlines()])
els... | python | {
"resource": ""
} |
q279269 | CompletionWidget.hideEvent | test | def hideEvent(self, event):
""" Reimplemented to disconnect signal handlers and event filter.
"""
super(CompletionWidget, self).hideEvent(event)
self._text_edit.cursorPositionChanged.disconnect(self._update_current)
self._text_edit.removeEventFilter(self) | python | {
"resource": ""
} |
q279270 | CompletionWidget.showEvent | test | def showEvent(self, event):
""" Reimplemented to connect signal handlers and event filter.
"""
super(CompletionWidget, self).showEvent(event)
self._text_edit.cursorPositionChanged.connect(self._update_current)
self._text_edit.installEventFilter(self) | python | {
"resource": ""
} |
q279271 | CompletionWidget._current_text_cursor | test | def _current_text_cursor(self):
""" Returns a cursor with text between the start position and the
current position selected.
"""
cursor = self._text_edit.textCursor()
if cursor.position() >= self._start_position:
cursor.setPosition(self._start_position,
... | python | {
"resource": ""
} |
q279272 | CompletionWidget._update_current | test | def _update_current(self):
""" Updates the current item based on the current text.
"""
prefix = self._current_text_cursor().selection().toPlainText()
if prefix:
items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith |
QtCore.Qt.M... | python | {
"resource": ""
} |
q279273 | registerAdminSite | test | def registerAdminSite(appName, excludeModels=[]):
"""Registers the models of the app with the given "appName" for the admin site"""
for model in apps.get_app_config(appName).get_models():
if model not in excludeModels:
admin.site.register(model) | python | {
"resource": ""
} |
q279274 | disk_partitions | test | def disk_partitions(all):
"""Return disk partitions."""
rawlist = _psutil_mswindows.get_disk_partitions(all)
return [nt_partition(*x) for x in rawlist] | python | {
"resource": ""
} |
q279275 | get_system_cpu_times | test | def get_system_cpu_times():
"""Return system CPU times as a named tuple."""
user, system, idle = 0, 0, 0
# computes system global times summing each processor value
for cpu_time in _psutil_mswindows.get_system_cpu_times():
user += cpu_time[0]
system += cpu_time[1]
idle += cpu_tim... | python | {
"resource": ""
} |
q279276 | get_system_per_cpu_times | test | def get_system_per_cpu_times():
"""Return system per-CPU times as a list of named tuples."""
ret = []
for cpu_t in _psutil_mswindows.get_system_cpu_times():
user, system, idle = cpu_t
item = _cputimes_ntuple(user, system, idle)
ret.append(item)
return ret | python | {
"resource": ""
} |
q279277 | Win32ShellCommandController._stdin_raw_nonblock | test | def _stdin_raw_nonblock(self):
"""Use the raw Win32 handle of sys.stdin to do non-blocking reads"""
# WARNING: This is experimental, and produces inconsistent results.
# It's possible for the handle not to be appropriate for use
# with WaitForSingleObject, among other t... | python | {
"resource": ""
} |
q279278 | Win32ShellCommandController._stdin_raw_block | test | def _stdin_raw_block(self):
"""Use a blocking stdin read"""
# The big problem with the blocking read is that it doesn't
# exit when it's supposed to in all contexts. An extra
# key-press may be required to trigger the exit.
try:
data = sys.stdin.read(1)
da... | python | {
"resource": ""
} |
q279279 | MainWindow.update_tab_bar_visibility | test | 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
"""
... | python | {
"resource": ""
} |
q279280 | MainWindow.create_tab_with_current_kernel | test | 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... | python | {
"resource": ""
} |
q279281 | MainWindow.add_tab_with_frontend | test | 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... | python | {
"resource": ""
} |
q279282 | MainWindow.add_menu_action | test | 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... | python | {
"resource": ""
} |
q279283 | MainWindow._make_dynamic_magic | test | 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
... | python | {
"resource": ""
} |
q279284 | MainWindow.populate_all_magic_menu | test | 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... | python | {
"resource": ""
} |
q279285 | MainWindow.closeEvent | test | 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 ... | python | {
"resource": ""
} |
q279286 | passwd | test | 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... | python | {
"resource": ""
} |
q279287 | passwd_check | test | 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... | python | {
"resource": ""
} |
q279288 | ajax_editable_boolean_cell | test | 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 ... | python | {
"resource": ""
} |
q279289 | TreeEditor.indented_short_title | test | 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" />'... | python | {
"resource": ""
} |
q279290 | TreeEditor._collect_editable_booleans | test | 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... | python | {
"resource": ""
} |
q279291 | TreeEditor._toggle_boolean | test | 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")
... | python | {
"resource": ""
} |
q279292 | TreeEditor.has_change_permission | test | 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
... | python | {
"resource": ""
} |
q279293 | TreeEditor.has_delete_permission | test | 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
... | python | {
"resource": ""
} |
q279294 | add_children | test | 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) | python | {
"resource": ""
} |
q279295 | make_bintree | test | 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 | python | {
"resource": ""
} |
q279296 | submit_jobs | test | 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 | python | {
"resource": ""
} |
q279297 | validate_tree | test | 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 ... | python | {
"resource": ""
} |
q279298 | make_color_table | test | 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) | python | {
"resource": ""
} |
q279299 | ColorScheme.copy | test | 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()) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.