_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q45300 | Socket._fair_send | train | async def _fair_send(self, frames):
"""
Send from the first available, non-blocking peer or wait until one
meets the condition.
:params frames: The frames to write.
:returns: The peer that was used.
"""
peer = await self._fair_get_out_peer()
peer.outbox.write_nowait(frames)
return peer | python | {
"resource": ""
} |
q45301 | Socket.subscribe | train | async def subscribe(self, topic):
"""
Subscribe the socket to the specified topic.
:param topic: The topic to subscribe to.
"""
if self.socket_type not in {SUB, XSUB}:
raise AssertionError(
"A %s socket cannot subscribe." % self.socket_type.decode(),
)
# Do this **BEFORE** awaiting so that new connections created during
# the execution below honor the setting.
self._subscriptions.append(topic)
tasks = [
asyncio.ensure_future(
peer.connection.local_subscribe(topic),
loop=self.loop,
)
for peer in self._peers
if peer.connection
]
if tasks:
try:
await asyncio.wait(tasks, loop=self.loop)
finally:
for task in tasks:
task.cancel() | python | {
"resource": ""
} |
q45302 | Socket.unsubscribe | train | async def unsubscribe(self, topic):
"""
Unsubscribe the socket from the specified topic.
:param topic: The topic to unsubscribe from.
"""
if self.socket_type not in {SUB, XSUB}:
raise AssertionError(
"A %s socket cannot unsubscribe." % self.socket_type.decode(),
)
# Do this **BEFORE** awaiting so that new connections created during
# the execution below honor the setting.
self._subscriptions.remove(topic)
tasks = [
asyncio.ensure_future(
peer.connection.local_unsubscribe(topic),
loop=self.loop,
)
for peer in self._peers
if peer.connection
]
if tasks:
try:
await asyncio.wait(tasks, loop=self.loop)
finally:
for task in tasks:
task.cancel() | python | {
"resource": ""
} |
q45303 | playerSurrendered | train | def playerSurrendered(cfg):
"""the player has forceibly left the game"""
if cfg.numAgents + cfg.numBots == 2:
otherResult = c.RESULT_VICTORY
else: otherResult = c.RESULT_UNDECIDED # if multiple players remain, they need to finish the match
return assignValue(cfg, c.RESULT_DEFEAT, otherResult) | python | {
"resource": ""
} |
q45304 | idPlayerResults | train | def idPlayerResults(cfg, rawResult):
"""interpret standard rawResult for all players with known IDs"""
result = {}
knownPlayers = []
dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult}
for p in cfg.players:
if p.playerID and p.playerID in dictResult: # identified player w/ result
knownPlayers.append(p)
result[p.name] = dictResult[p.playerID]
#if len(knownPlayers) == len(dictResult) - 1: # identified all but one player
# for p in cfg.players: # search for the not identified player
# if p in knownPlayers: continue # already found
# result.append( [p.name, p.playerID, dictResult[p.playerID]] )
# break # found missing player; stop searching
#for r in result:
# print("result:>", r)
return result | python | {
"resource": ""
} |
q45305 | GenericPositionsAdmin.save_model | train | def save_model(self, request, obj, form, change):
"""Add an ObjectPosition to the object."""
super(GenericPositionsAdmin, self).save_model(request, obj, form,
change)
c_type = ContentType.objects.get_for_model(obj)
try:
ObjectPosition.objects.get(content_type__pk=c_type.id,
object_id=obj.id)
except ObjectPosition.DoesNotExist:
position_objects = ObjectPosition.objects.filter(
content_type__pk=c_type.id, position__isnull=False).order_by(
'-position')
try:
position = (position_objects[0].position + 1)
except IndexError:
position = 1
ObjectPosition.objects.create(
content_object=obj, position=position) | python | {
"resource": ""
} |
q45306 | managed | train | def managed(name, packages=None, requirements=None, saltenv='base', user=None):
"""
Create and install python requirements in a conda enviroment
pip is installed by default in the new enviroment
name : path to the enviroment to be created
packages : None
single package or list of packages to install i.e. numpy, scipy=0.13.3, pandas
requirements : None
path to a `requirements.txt` file in the `pip freeze` format
saltenv : 'base'
Salt environment. Usefull when the name is file using the salt file system
(e.g. `salt://.../reqs.txt`)
user
The user under which to run the commands
"""
ret = {'name': name, 'changes': {}, 'comment': '', 'result': True}
comments = []
# Create virutalenv
try:
installation_comment = __salt__['conda.create'](name, user=user)
if installation_comment.endswith('created'):
comments.append('Virtual enviroment "%s" created' % name)
else:
comments.append('Virtual enviroment "%s" already exists' % name)
except Exception as e:
ret['comment'] = e
ret['result'] = False
return ret
# Install packages
if packages is not None:
installation_ret = installed(packages, env=name, saltenv=saltenv, user=user)
ret['result'] = ret['result'] and installation_ret['result']
comments.append('From list [%s]' % installation_ret['comment'])
ret['changes'].update(installation_ret['changes'])
if requirements is not None:
installation_ret = installed(requirements, env=name, saltenv=saltenv, user=user)
ret['result'] = ret['result'] and installation_ret['result']
comments.append('From file [%s]' % installation_ret['comment'])
ret['changes'].update(installation_ret['changes'])
ret['comment'] = '. '.join(comments)
return ret | python | {
"resource": ""
} |
q45307 | GridEngineProvider.get_configs | train | def get_configs(self, command):
"""Compose a dictionary with information for writing the submit script."""
logger.debug("Requesting one block with {} nodes per block and {} tasks per node".format(
self.nodes_per_block, self.tasks_per_node))
job_config = {}
job_config["submit_script_dir"] = self.channel.script_dir
job_config["nodes"] = self.nodes_per_block
job_config["walltime"] = wtime_to_minutes(self.walltime)
job_config["overrides"] = self.overrides
job_config["user_script"] = command
job_config["user_script"] = self.launcher(command,
self.tasks_per_node,
self.nodes_per_block)
return job_config | python | {
"resource": ""
} |
q45308 | qr2scad | train | def qr2scad(stream):
"""Convert black pixels to OpenSCAD cubes."""
img = Image.open(stream)
# Convert to black and white 8-bit
if img.mode != 'L':
img = img.convert('L')
# Invert color to get the right bounding box
img = ImageOps.invert(img)
bbox = img.getbbox()
# Crop to only contain contents within the PDPs
img = img.crop(bbox)
width, height = img.size
assert width == height,\
'The QR code should be a square, but we found it to be %(w)sx%(h)s' % {
'w': width,
'h': height
}
qr_side = width
# QR code superpixel size
qr_pixel_size = (list(img.getdata()).index(0) / PDP_SIDE)
# Get the resize factor from the PDP size
new_size = qr_side / qr_pixel_size
# Set a more reasonable size
img = img.resize((new_size, new_size))
qr_side = new_size
img_matrix = img.load()
result = 'module _qr_code_dot() {\n'
result += ' cube([%(block_side)s, %(block_side)s, 1]);\n' % {
'block_side': BLOCK_SIDE
}
result += '}\n'
result += 'module qr_code() {\n'
for row in range(qr_side):
for column in range(qr_side):
if img_matrix[column, row] != 0:
result += ' translate([%(x)s, %(y)s, 0])' % {
'x': BLOCK_SIZE * column - qr_side / 2,
'y': -BLOCK_SIZE * row + qr_side / 2
}
result += ' _qr_code_dot();\n'
result += '}\n'
result += 'qr_code_size = %d;' % (qr_side)
return result | python | {
"resource": ""
} |
q45309 | run | train | def run(*args):
"""Load given `envfile` and run `command` with `params`"""
if not args:
args = sys.argv[1:]
if len(args) < 2:
print('Usage: runenv <envfile> <command> <params>')
sys.exit(0)
os.environ.update(create_env(args[0]))
os.environ['_RUNENV_WRAPPED'] = '1'
runnable_path = args[1]
if not runnable_path.startswith(('/', '.')):
runnable_path = spawn.find_executable(runnable_path)
try:
if not(stat.S_IXUSR & os.stat(runnable_path)[stat.ST_MODE]):
print('File `%s is not executable' % runnable_path)
sys.exit(1)
return subprocess.check_call(
args[1:], env=os.environ
)
except subprocess.CalledProcessError as e:
return e.returncode | python | {
"resource": ""
} |
q45310 | create_env | train | def create_env(env_file):
"""Create environ dictionary from current os.environ and
variables got from given `env_file`"""
environ = {}
with open(env_file, 'r') as f:
for line in f.readlines():
line = line.rstrip(os.linesep)
if '=' not in line:
continue
if line.startswith('#'):
continue
key, value = line.split('=', 1)
environ[key] = parse_value(value)
return environ | python | {
"resource": ""
} |
q45311 | info | train | def info(args):
" Show information about site. "
site = find_site(args.PATH)
print_header("%s -- install information" % site.get_name())
LOGGER.debug(site.get_info(full=True))
return True | python | {
"resource": ""
} |
q45312 | module | train | def module(args):
" Copy module source to current directory. "
mod = op.join(settings.MOD_DIR, args.MODULE)
assert op.exists(mod), "Not found module: %s" % args.MODULE
if not args.DEST.startswith(op.sep):
args.DEST = op.join(getcwd(), args.DEST)
print_header("Copy module source")
copytree(mod, args.DEST) | python | {
"resource": ""
} |
q45313 | uninstall | train | def uninstall(args):
" Uninstall site. "
site = find_site(args.PATH)
site.run_remove()
site.clean()
if not listdir(op.dirname(site.deploy_dir)):
call('sudo rm -rf %s' % op.dirname(site.deploy_dir)) | python | {
"resource": ""
} |
q45314 | template | train | def template(args):
" Add or remove templates from site. "
site = Site(args.PATH)
if args.ACTION == "add":
return site.add_template(args.TEMPLATE)
return site.remove_template(args.TEMPLATE) | python | {
"resource": ""
} |
q45315 | shell | train | def shell(args):
" A helper command to be used for shell integration "
print
print "# Makesite integration "
print "# ==================== "
print "export MAKESITE_HOME=%s" % args.path
print "source %s" % op.join(settings.BASEDIR, 'shell.sh')
print | python | {
"resource": ""
} |
q45316 | install | train | def install(args):
" Install site from sources or module "
# Deactivate virtualenv
if 'VIRTUAL_ENV' in environ:
LOGGER.warning('Virtualenv enabled: %s' % environ['VIRTUAL_ENV'])
# Install from base modules
if args.module:
args.src = op.join(settings.MOD_DIR, args.module)
assert op.exists(args.src), "Not found module: %s" % args.module
# Fix project name
args.PROJECT = args.PROJECT.replace('-', '_')
args.home = op.abspath(args.path)
# Create engine
engine = Installer(args)
args.deploy_dir = engine.target_dir
# Check dir exists
assert args.info or args.repeat or args.update or not op.exists(
engine.target_dir), "Path %s exists. Stop deploy." % args.deploy_dir
try:
if args.repeat:
site = Site(engine.target_dir)
site.run_install()
return site
site = engine.clone_source()
if not site:
return True
engine.build(args.update)
site.run_install()
return site
except (CalledProcessError, AssertionError):
LOGGER.error("Installation failed")
LOGGER.error("Fix errors and repeat installation with (-r) or run 'makesite uninstall %s' for cancel." % args.deploy_dir)
raise | python | {
"resource": ""
} |
q45317 | autocomplete | train | def autocomplete(force=False):
" Shell autocompletion support. "
if 'MAKESITE_AUTO_COMPLETE' not in environ and not force:
return
commands = filter(lambda cmd: cmd != 'main', ACTIONS.keys())
cwords = environ['COMP_WORDS'].split()[1:]
cword = int(environ['COMP_CWORD'])
try:
current = cwords[cword - 1]
except IndexError:
current = ''
try:
sub_action = [cmd for cmd in commands if cmd in cwords][0]
if sub_action in ['info', 'uninstall', 'update', 'template']:
if settings.MAKESITE_HOME:
if not current or current.startswith('/'):
sites = list(gen_sites(settings.MAKESITE_HOME))
print ' '.join(site.deploy_dir for site in sites if site.
deploy_dir.startswith(current))
else:
names = map(lambda s: s.get_name(
), gen_sites(settings.MAKESITE_HOME))
print ' '.join(
name for name in names if name.startswith(current))
elif sub_action == 'install' and (cwords[-1] == '-m' or (current and cwords[-2] == '-m')):
print ' '.join(
mod for mod in get_base_modules() if mod.startswith(current))
elif sub_action == 'install' and (cwords[-1] == '-t' or (current and cwords[-2] == '-t')):
print ' '.join(tpl for tpl in get_base_templates(
) if tpl.startswith(current))
elif sub_action == 'module':
print ' '.join(
tpl for tpl in get_base_modules() if tpl.startswith(current))
except IndexError:
print (' '.join(a for a in commands if a.startswith(current)))
sys.exit(1) | python | {
"resource": ""
} |
q45318 | DistanceMatrix._error_and_gradient | train | def _error_and_gradient(self, x):
"""Compute the error and the gradient.
This is the function optimized by :obj:`scipy.optimize.minimize`.
Args:
x (`array-like`): [`m` * `n`, ] matrix.
Returns:
`tuple`: containing:
- Error (`float`)
- Gradient (`np.array`) [`m`, `n`]
"""
coords = x.reshape((self.m, self.n))
d = squareform(pdist(coords))
diff = self.D - d
error = self._error(diff)
gradient = self._gradient(diff, d, coords)
return error, gradient.ravel() | python | {
"resource": ""
} |
q45319 | DistanceMatrix.optimize | train | def optimize(self, start=None, n=2):
"""Run multidimensional scaling on this distance matrix.
Args:
start (`None` or `array-like`): Starting coordinates. If
`start=None`, random starting coordinates are used. If
`array-like` must have shape [`m` * `n`, ].
n (`int`): Number of dimensions to embed samples in.
Examples:
.. doctest::
>>> import pandas as pd
>>> from pymds import DistanceMatrix
>>> dist = pd.DataFrame({
... 'a': [0.0, 1.0, 2.0],
... 'b': [1.0, 0.0, 3 ** 0.5],
... 'c': [2.0, 3 ** 0.5, 0.0]} , index=['a', 'b', 'c'])
>>> dm = DistanceMatrix(dist)
>>> pro = dm.optimize(n=2)
>>> pro.coords.shape
(3, 2)
>>> type(pro)
<class 'pymds.mds.Projection'>
Returns: :py:class:`pymds.Projection`
"""
self.n = n
if start is None:
start = np.random.rand(self.m * self.n) * 10
optim = minimize(
fun=self._error_and_gradient,
x0=start,
jac=True,
method='L-BFGS-B')
index = self.index if hasattr(self, "index") else None
return Projection.from_optimize_result(
result=optim, n=self.n, m=self.m, index=index) | python | {
"resource": ""
} |
q45320 | DistanceMatrix.optimize_batch | train | def optimize_batch(self, batchsize=10, returns='best', paralell=True):
"""
Run multiple optimizations using different starting coordinates.
Args:
batchsize (`int`): Number of optimizations to run.
returns (`str`): If ``'all'``, return results of all optimizations,
ordered by stress, ascending. If ``'best'`` return the
projection with the lowest stress.
parallel (`bool`): If ``True``, run optimizations in parallel.
Examples:
.. doctest::
>>> import pandas as pd
>>> from pymds import DistanceMatrix
>>> dist = pd.DataFrame({
... 'a': [0.0, 1.0, 2.0],
... 'b': [1.0, 0.0, 3 ** 0.5],
... 'c': [2.0, 3 ** 0.5, 0.0]} , index=['a', 'b', 'c'])
>>> dm = DistanceMatrix(dist)
>>> batch = dm.optimize_batch(batchsize=3, returns='all')
>>> len(batch)
3
>>> type(batch[0])
<class 'pymds.mds.Projection'>
Returns:
`list` or :py:class:`pymds.Projection`:
`list`: Length batchsize, containing instances of
:py:class:`pymds.Projection`. Sorted by stress, ascending.
or
:py:class:`pymds.Projection`: Projection with the lowest
stress.
"""
if returns not in ('best', 'all'):
raise ValueError('returns must be either "best" or "all"')
starts = [np.random.rand(self.m * 2) * 10 for i in range(batchsize)]
if paralell:
with Pool() as p:
results = p.map(self.optimize, starts)
else:
results = map(self.optimize, starts)
results = sorted(results, key=lambda x: x.stress)
return results if returns == 'all' else results[0] | python | {
"resource": ""
} |
q45321 | Projection.from_optimize_result | train | def from_optimize_result(cls, result, n, m, index=None):
"""Construct a Projection from the output of an optimization.
Args:
result (:py:class:`scipy.optimize.OptimizeResult`): Object
returned by :py:func:`scipy.optimize.minimize`.
n (`int`): Number of dimensions.
m (`int`): Number of samples.
index (`list-like`): Names of samples. (Optional).
Returns:
:py:class:`pymds.Projection`
"""
coords = pd.DataFrame(result.x.reshape((m, n)), index=index)
projection = cls(coords)
projection.stress = result.fun
return projection | python | {
"resource": ""
} |
q45322 | Projection._get_samples_shared_with | train | def _get_samples_shared_with(self, other, index=None):
"""Find samples shared with another dataset.
Args:
other
(:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`
or `array-like`):
The other dataset. If `other` is an instance of
:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`,
then `other` must have indexes in common with this projection.
If `array-like`, then other must have same dimensions as
`self.coords`.
index (`list-like` or `None`): If `other` is an instance of
:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`
then only return samples in index.
Returns:
`tuple`: containing:
- this (`numpy.array`) Shape [`x`, `n`].
- other (`numpy.array`) Shape [`x`, `n`].
"""
if isinstance(other, (pd.DataFrame, Projection)):
df_other = other.coords if isinstance(other, Projection) else other
if len(set(df_other.index)) != len(df_other.index):
raise ValueError("other index has duplicates")
if len(set(self.coords.index)) != len(self.coords.index):
raise ValueError("This projection index has duplicates")
if index:
uniq_idx = set(index)
if len(uniq_idx) != len(index):
raise ValueError("index has has duplicates")
if uniq_idx - set(df_other.index):
raise ValueError("index has samples not in other")
if uniq_idx - set(self.coords.index):
raise ValueError(
"index has samples not in this projection")
else:
uniq_idx = set(df_other.index) & set(self.coords.index)
if not len(uniq_idx):
raise ValueError(
"No samples shared between other and this projection")
idx = list(uniq_idx)
return self.coords.loc[idx, :].values, df_other.loc[idx, :].values
else:
other = np.array(other)
if other.shape != self.coords.shape:
raise ValueError(
"array-like must have the same shape as self.coords")
return self.coords.values, other | python | {
"resource": ""
} |
q45323 | Projection.plot | train | def plot(self, **kwds):
"""Plot the coordinates in the first two dimensions of the projection.
Removes axis and tick labels, and sets the grid spacing to 1 unit.
One way to display the grid is to use `Seaborn`_:
Args:
**kwds: Passed to :py:meth:`pandas.DataFrame.plot.scatter`.
Examples:
>>> from pymds import DistanceMatrix
>>> import pandas as pd
>>> import seaborn as sns
>>> sns.set_style('whitegrid')
>>> dist = pd.DataFrame({
... 'a': [0.0, 1.0, 2.0],
... 'b': [1.0, 0.0, 3 ** 0.5],
... 'c': [2.0, 3 ** 0.5, 0.0]} , index=['a', 'b', 'c'])
>>> dm = DistanceMatrix(dist)
>>> pro = dm.optimize()
>>> ax = pro.plot(c='black', s=50, edgecolor='white')
Returns:
:py:obj:`matplotlib.axes.Axes`
.. _Seaborn:
https://seaborn.pydata.org/
"""
ax = plt.gca()
self.coords.plot.scatter(x=0, y=1, ax=ax, **kwds)
ax.get_xaxis().set_major_locator(MultipleLocator(base=1.0))
ax.get_yaxis().set_major_locator(MultipleLocator(base=1.0))
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_xlabel('')
ax.set_ylabel('')
ax.set_aspect(1)
return ax | python | {
"resource": ""
} |
q45324 | Projection.plot_lines_to | train | def plot_lines_to(self, other, index=None, **kwds):
"""Plot lines from samples shared between this projection and another
dataset.
Args:
other
(:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`
or `array-like`):
The other dataset to plot lines to. If other is an instance of
:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`,
then other must have indexes in common with this projection.
If `array-like`, then other must have the same dimensions as
`self.coords`.
index (`list-like` or `None`): Only draw lines between samples in
index. All elements in index must be samples in this projection
and other.
**kwds: Passed to :py:obj:`matplotlib.collections.LineCollection`.
Examples:
>>> import numpy as np
>>> from pymds import Projection
>>> pro = Projection(np.random.randn(50, 2))
>>> R = np.array([[0, -1], [1, 0]])
>>> other = np.dot(pro.coords, R) # Rotate 90 deg
>>> ax = pro.plot(c='black', edgecolor='white', zorder=20)
>>> ax = pro.plot_lines_to(other, linewidths=0.3)
Returns:
:py:obj:`matplotlib.axes.Axes`
"""
start, end = self._get_samples_shared_with(other, index=index)
segments = [[start[i, :], end[i, :]] for i in range(start.shape[0])]
ax = plt.gca()
ax.add_artist(LineCollection(segments=segments, **kwds))
return ax | python | {
"resource": ""
} |
q45325 | Projection.orient_to | train | def orient_to(self, other, index=None, inplace=False, scaling=False):
"""Orient this Projection to another dataset.
Orient this projection using reflection, rotation and translation to
match another projection using procrustes superimposition. Scaling is
optional.
Args:
other
(:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`
or `array-like`):
The other dataset to orient this projection to.
If other is an instance of :py:class:`pymds.Projection` or
:py:class:`pandas.DataFrame`, then other must have indexes in
common with this projection. If `array-like`, then other must
have the same dimensions as self.coords.
index (`list-like` or `None`): If other is an instance of
:py:class:`pandas.DataFrame` or :py:class:`pymds.Projection`
then orient this projection to other using only samples in
index.
inplace (`bool`): Update coordinates of this projection inplace,
or return an instance of :py:class:`pymds.Projection`.
scaling (`bool`): Allow scaling. (Not implemented yet).
Examples:
.. doctest::
>>> import numpy as np
>>> import pandas as pd
>>> from pymds import Projection
>>> array = np.random.randn(10, 2)
>>> pro = Projection(pd.DataFrame(array))
>>> # Flip left-right, rotate 90 deg and translate
>>> other = np.fliplr(array)
>>> other = np.dot(other, np.array([[0, -1], [1, 0]]))
>>> other += np.array([10, -5])
>>> oriented = pro.orient_to(other)
>>> (oriented.coords.values - other).sum() < 1e-6
True
Returns:
:py:class:`pymds.Projection`: If ``inplace=False``.
"""
arr_self, arr_other = self._get_samples_shared_with(other, index=index)
if scaling:
raise NotImplementedError()
else:
self_mean = arr_self.mean(axis=0)
other_mean = arr_other.mean(axis=0)
A = arr_self - self_mean
B = arr_other - other_mean
R, _ = orthogonal_procrustes(A, B)
to_rotate = self.coords - self.coords.mean(axis=0)
oriented = np.dot(to_rotate, R) + other_mean
oriented = pd.DataFrame(oriented, index=self.coords.index)
if inplace:
self.coords = oriented
else:
return Projection(oriented) | python | {
"resource": ""
} |
q45326 | create | train | def create(name, packages=None, user=None):
"""
Create a conda env
"""
packages = packages or ''
packages = packages.split(',')
packages.append('pip')
args = packages + ['--yes', '-q']
cmd = _create_conda_cmd('create', args=args, env=name, user=user)
ret = _execcmd(cmd, user=user, return0=True)
if ret['retcode'] == 0:
ret['result'] = True
ret['comment'] = 'Virtual enviroment "%s" successfully created' % name
else:
if ret['stderr'].startswith('Error: prefix already exists:'):
ret['result'] = True
ret['comment'] = 'Virtual enviroment "%s" already exists' % name
else:
ret['result'] = False
ret['error'] = salt.exceptions.CommandExecutionError(ret['stderr'])
return ret | python | {
"resource": ""
} |
q45327 | list_ | train | def list_(env=None, user=None):
"""
List the installed packages on an environment
Returns
-------
Dictionary: {package: {version: 1.0.0, build: 1 } ... }
"""
cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user)
ret = _execcmd(cmd, user=user)
if ret['retcode'] == 0:
pkg_list = json.loads(ret['stdout'])
packages = {}
for pkg in pkg_list:
pkg_info = pkg.split('-')
name, version, build = '-'.join(pkg_info[:-2]), pkg_info[-2], pkg_info[-1]
packages[name] = {'version': version, 'build': build}
return packages
else:
return ret | python | {
"resource": ""
} |
q45328 | update | train | def update(packages, env=None, user=None):
"""
Update conda packages in a conda env
Attributes
----------
packages: list of packages comma delimited
"""
packages = ' '.join(packages.split(','))
cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)
return _execcmd(cmd, user=user) | python | {
"resource": ""
} |
q45329 | remove | train | def remove(packages, env=None, user=None):
"""
Remove conda packages in a conda env
Attributes
----------
packages: list of packages comma delimited
"""
packages = ' '.join(packages.split(','))
cmd = _create_conda_cmd('remove', args=[packages, '--yes', '-q'], env=env, user=user)
return _execcmd(cmd, user=user, return0=True) | python | {
"resource": ""
} |
q45330 | _create_conda_cmd | train | def _create_conda_cmd(conda_cmd, args=None, env=None, user=None):
"""
Utility to create a valid conda command
"""
cmd = [_get_conda_path(user=user), conda_cmd]
if env:
cmd.extend(['-n', env])
if args is not None and isinstance(args, list) and args != []:
cmd.extend(args)
return cmd | python | {
"resource": ""
} |
q45331 | UAgentInfo.initDeviceScan | train | def initDeviceScan(self):
"""Initialize Key Stored Values."""
self.__isIphone = self.detectIphoneOrIpod()
self.__isAndroidPhone = self.detectAndroidPhone()
self.__isTierTablet = self.detectTierTablet()
self.__isTierIphone = self.detectTierIphone()
self.__isTierRichCss = self.detectTierRichCss()
self.__isTierGenericMobile = self.detectTierOtherPhones() | python | {
"resource": ""
} |
q45332 | UAgentInfo.detectIphone | train | def detectIphone(self):
"""Return detection of an iPhone
Detects if the current device is an iPhone.
"""
# The iPad and iPod touch say they're an iPhone! So let's disambiguate.
return UAgentInfo.deviceIphone in self.__userAgent \
and not self.detectIpad() \
and not self.detectIpod() | python | {
"resource": ""
} |
q45333 | UAgentInfo.detectIphoneOrIpod | train | def detectIphoneOrIpod(self):
"""Return detection of an iPhone or iPod Touch
Detects if the current device is an iPhone or iPod Touch.
"""
#We repeat the searches here because some iPods may report themselves as an iPhone, which would be okay.
return UAgentInfo.deviceIphone in self.__userAgent \
or UAgentInfo.deviceIpod in self.__userAgent | python | {
"resource": ""
} |
q45334 | UAgentInfo.detectAndroid | train | def detectAndroid(self):
"""Return detection of an Android device
Detects *any* Android OS-based device: phone, tablet, and multi-media player.
Also detects Google TV.
"""
if UAgentInfo.deviceAndroid in self.__userAgent \
or self.detectGoogleTV():
return True
return False | python | {
"resource": ""
} |
q45335 | UAgentInfo.detectAndroidPhone | train | def detectAndroidPhone(self):
"""Return detection of an Android phone
Detects if the current device is a (small-ish) Android OS-based device
used for calling and/or multi-media (like a Samsung Galaxy Player).
Google says these devices will have 'Android' AND 'mobile' in user agent.
Ignores tablets (Honeycomb and later).
"""
#First, let's make sure we're on an Android device.
if not self.detectAndroid():
return False
#If it's Android and has 'mobile' in it, Google says it's a phone.
if UAgentInfo.mobile in self.__userAgent:
return True
#Special check for Android devices with Opera Mobile/Mini. They should report here.
if self.detectOperaMobile():
return True
return False | python | {
"resource": ""
} |
q45336 | UAgentInfo.detectAndroidTablet | train | def detectAndroidTablet(self):
"""Return detection of an Android tablet
Detects if the current device is a (self-reported) Android tablet.
Google says these devices will have 'Android' and NOT 'mobile' in their user agent.
"""
#First, let's make sure we're on an Android device.
if not self.detectAndroid():
return False
#Special check for Android devices with Opera Mobile/Mini. They should NOT report here.
if self.detectOperaMobile():
return False
#Otherwise, if it's Android and does NOT have 'mobile' in it, Google says it's a tablet.
return UAgentInfo.mobile not in self.__userAgent | python | {
"resource": ""
} |
q45337 | UAgentInfo.detectS60OssBrowser | train | def detectS60OssBrowser(self):
"""Return detection of Symbian S60 Browser
Detects if the current browser is the Symbian S60 Open Source Browser.
"""
#First, test for WebKit, then make sure it's either Symbian or S60.
return self.detectWebkit() \
and (UAgentInfo.deviceSymbian in self.__userAgent
or UAgentInfo.deviceS60 in self.__userAgent) | python | {
"resource": ""
} |
q45338 | UAgentInfo.detectSymbianOS | train | def detectSymbianOS(self):
"""Return detection of SymbianOS
Detects if the current device is any Symbian OS-based device,
including older S60, Series 70, Series 80, Series 90, and UIQ,
or other browsers running on these devices.
"""
return UAgentInfo.deviceSymbian in self.__userAgent \
or UAgentInfo.deviceS60 in self.__userAgent \
or UAgentInfo.deviceS70 in self.__userAgent \
or UAgentInfo.deviceS80 in self.__userAgent \
or UAgentInfo.deviceS90 in self.__userAgent | python | {
"resource": ""
} |
q45339 | UAgentInfo.detectWindowsMobile | train | def detectWindowsMobile(self):
"""Return detection of Windows Mobile
Detects if the current browser is a Windows Mobile device.
Excludes Windows Phone 7 devices.
Focuses on Windows Mobile 6.xx and earlier.
"""
#Exclude new Windows Phone.
if self.detectWindowsPhone():
return False
#Most devices use 'Windows CE', but some report 'iemobile'
# and some older ones report as 'PIE' for Pocket IE.
# We also look for instances of HTC and Windows for many of their WinMo devices.
if UAgentInfo.deviceWinMob in self.__userAgent \
or UAgentInfo.deviceIeMob in self.__userAgent \
or UAgentInfo.enginePie in self.__userAgent:
return True
# Test for certain Windwos Mobile-based HTC devices.
if UAgentInfo.manuHtc in self.__userAgent \
and UAgentInfo.deviceWindows in self.__userAgent:
return True
if self.detectWapWml() \
and UAgentInfo.deviceWindows in self.__userAgent:
return True
#Test for Windows Mobile PPC but not old Macintosh PowerPC.
return UAgentInfo.devicePpc in self.__userAgent \
and UAgentInfo.deviceMacPpc not in self.__userAgent | python | {
"resource": ""
} |
q45340 | UAgentInfo.detectBlackBerry | train | def detectBlackBerry(self):
"""Return detection of Blackberry
Detects if the current browser is any BlackBerry.
Includes the PlayBook.
"""
return UAgentInfo.deviceBB in self.__userAgent \
or UAgentInfo.vndRIM in self.__httpAccept | python | {
"resource": ""
} |
q45341 | UAgentInfo.detectBlackBerry10Phone | train | def detectBlackBerry10Phone(self):
"""Return detection of a Blackberry 10 OS phone
Detects if the current browser is a BlackBerry 10 OS phone.
Excludes the PlayBook.
"""
return UAgentInfo.deviceBB10 in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent | python | {
"resource": ""
} |
q45342 | UAgentInfo.detectBlackBerryTouch | train | def detectBlackBerryTouch(self):
"""Return detection of a Blackberry touchscreen device
Detects if the current browser is a BlackBerry Touch
device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook.
"""
return UAgentInfo.deviceBBStorm in self.__userAgent \
or UAgentInfo.deviceBBTorch in self.__userAgent \
or UAgentInfo.deviceBBBoldTouch in self.__userAgent \
or UAgentInfo.deviceBBCurveTouch in self.__userAgent | python | {
"resource": ""
} |
q45343 | UAgentInfo.detectBlackBerryHigh | train | def detectBlackBerryHigh(self):
"""Return detection of a Blackberry device with a better browser
Detects if the current browser is a BlackBerry device AND
has a more capable recent browser. Excludes the Playbook.
Examples, Storm, Bold, Tour, Curve2
Excludes the new BlackBerry OS 6 and 7 browser!!
"""
#Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser
if self.detectBlackBerryWebKit():
return False
if not self.detectBlackBerry():
return False
return self.detectBlackBerryTouch() \
or UAgentInfo.deviceBBBold in self.__userAgent \
or UAgentInfo.deviceBBTour in self.__userAgent \
or UAgentInfo.deviceBBCurve in self.__userAgent | python | {
"resource": ""
} |
q45344 | UAgentInfo.detectPalmOS | train | def detectPalmOS(self):
"""Return detection of a PalmOS device
Detects if the current browser is on a PalmOS device.
"""
#Most devices nowadays report as 'Palm', but some older ones reported as Blazer or Xiino.
if UAgentInfo.devicePalm in self.__userAgent \
or UAgentInfo.engineBlazer in self.__userAgent \
or UAgentInfo.engineXiino in self.__userAgent:
# Make sure it's not WebOS
return not self.detectPalmWebOS()
return False | python | {
"resource": ""
} |
q45345 | UAgentInfo.detectWebOSTablet | train | def detectWebOSTablet(self):
"""Return detection of an HP WebOS tablet
Detects if the current browser is on an HP tablet running WebOS.
"""
return UAgentInfo.deviceWebOShp in self.__userAgent \
and UAgentInfo.deviceTablet in self.__userAgent | python | {
"resource": ""
} |
q45346 | UAgentInfo.detectWebOSTV | train | def detectWebOSTV(self):
"""Return detection of a WebOS smart TV
Detects if the current browser is on a WebOS smart TV.
"""
return UAgentInfo.deviceWebOStv in self.__userAgent \
and UAgentInfo.smartTV2 in self.__userAgent | python | {
"resource": ""
} |
q45347 | UAgentInfo.detectTizen | train | def detectTizen(self):
"""Return detection of a Tizen device
Detects a device running the Tizen smartphone OS.
"""
return UAgentInfo.deviceTizen in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent | python | {
"resource": ""
} |
q45348 | UAgentInfo.detectTizenTV | train | def detectTizenTV(self):
"""Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV.
"""
return UAgentInfo.deviceTizen in self.__userAgent \
and UAgentInfo.smartTV1 in self.__userAgent | python | {
"resource": ""
} |
q45349 | UAgentInfo.detectMeegoPhone | train | def detectMeegoPhone(self):
"""Return detection of a Meego phone
Detects a phone running the Meego OS.
"""
return UAgentInfo.deviceMeego in self.__userAgent \
and UAgentInfo.mobi in self.__userAgent | python | {
"resource": ""
} |
q45350 | UAgentInfo.detectFirefoxOSPhone | train | def detectFirefoxOSPhone(self):
"""Return detection of a Firefox OS phone
Detects a phone (probably) running the Firefox OS.
"""
if self.detectIos() \
or self.detectAndroid() \
or self.detectSailfish():
return False
if UAgentInfo.engineFirefox in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent:
return True
return False | python | {
"resource": ""
} |
q45351 | UAgentInfo.detectFirefoxOSTablet | train | def detectFirefoxOSTablet(self):
"""Return detection of a Firefox OS tablet
Detects a tablet (probably) running the Firefox OS.
"""
if self.detectIos() \
or self.detectAndroid() \
or self.detectSailfish():
return False
if UAgentInfo.engineFirefox in self.__userAgent \
and UAgentInfo.deviceTablet in self.__userAgent:
return True
return False | python | {
"resource": ""
} |
q45352 | UAgentInfo.detectSailfishPhone | train | def detectSailfishPhone(self):
"""Return detection of a Sailfish phone
Detects a phone running the Sailfish OS.
"""
if self.detectSailfish() \
and UAgentInfo.mobile in self.__userAgent:
return True
return False | python | {
"resource": ""
} |
q45353 | UAgentInfo.detectUbuntuPhone | train | def detectUbuntuPhone(self):
"""Return detection of an Ubuntu Mobile OS phone
Detects a phone running the Ubuntu Mobile OS.
"""
if UAgentInfo.deviceUbuntu in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent:
return True
return False | python | {
"resource": ""
} |
q45354 | UAgentInfo.detectUbuntuTablet | train | def detectUbuntuTablet(self):
"""Return detection of an Ubuntu Mobile OS tablet
Detects a tablet running the Ubuntu Mobile OS.
"""
if UAgentInfo.deviceUbuntu in self.__userAgent \
and UAgentInfo.deviceTablet in self.__userAgent:
return True
return False | python | {
"resource": ""
} |
q45355 | UAgentInfo.detectDangerHiptop | train | def detectDangerHiptop(self):
"""Return detection of a Danger Hiptop
Detects the Danger Hiptop device.
"""
return UAgentInfo.deviceDanger in self.__userAgent \
or UAgentInfo.deviceHiptop in self.__userAgent | python | {
"resource": ""
} |
q45356 | UAgentInfo.detectOperaMobile | train | def detectOperaMobile(self):
"""Return detection of an Opera browser for a mobile device
Detects Opera Mobile or Opera Mini.
"""
return UAgentInfo.engineOpera in self.__userAgent \
and (UAgentInfo.mini in self.__userAgent
or UAgentInfo.mobi in self.__userAgent) | python | {
"resource": ""
} |
q45357 | UAgentInfo.detectWapWml | train | def detectWapWml(self):
"""Return detection of a WAP- or WML-capable device
Detects whether the device supports WAP or WML.
"""
return UAgentInfo.vndwap in self.__httpAccept \
or UAgentInfo.wml in self.__httpAccept | python | {
"resource": ""
} |
q45358 | UAgentInfo.detectGamingHandheld | train | def detectGamingHandheld(self):
"""Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
"""
return UAgentInfo.devicePlaystation in self.__userAgent \
and UAgentInfo.devicePlaystationVita in self.__userAgent | python | {
"resource": ""
} |
q45359 | UAgentInfo.detectNintendo | train | def detectNintendo(self):
"""Return detection of Nintendo
Detects if the current device is a Nintendo game device.
"""
return UAgentInfo.deviceNintendo in self.__userAgent \
or UAgentInfo.deviceNintendo in self.__userAgent \
or UAgentInfo.deviceNintendo in self.__userAgent | python | {
"resource": ""
} |
q45360 | UAgentInfo.detectMidpCapable | train | def detectMidpCapable(self):
"""Return detection of a MIDP mobile Java-capable device
Detects if the current device supports MIDP, a mobile Java technology.
"""
return UAgentInfo.deviceMidp in self.__userAgent \
or UAgentInfo.deviceMidp in self.__httpAccept | python | {
"resource": ""
} |
q45361 | UAgentInfo.detectMaemoTablet | train | def detectMaemoTablet(self):
"""Return detection of a Maemo OS tablet
Detects if the current device is on one of the Maemo-based Nokia Internet Tablets.
"""
if UAgentInfo.maemo in self.__userAgent:
return True
return UAgentInfo.linux in self.__userAgent \
and UAgentInfo.deviceTablet in self.__userAgent \
and not self.detectWebOSTablet() \
and not self.detectAndroid() | python | {
"resource": ""
} |
q45362 | UAgentInfo.detectSonyMylo | train | def detectSonyMylo(self):
"""Return detection of a Sony Mylo device
Detects if the current browser is a Sony Mylo device.
"""
return UAgentInfo.manuSony in self.__userAgent \
and (UAgentInfo.qtembedded in self.__userAgent
or UAgentInfo.mylocom2 in self.__userAgent) | python | {
"resource": ""
} |
q45363 | UAgentInfo.detectSmartphone | train | def detectSmartphone(self):
"""Return detection of a general smartphone device
Checks to see whether the device is *any* 'smartphone'.
Note: It's better to use DetectTierIphone() for modern touchscreen devices.
"""
return self.detectTierIphone() \
or self.detectS60OssBrowser() \
or self.detectSymbianOS() \
or self.detectWindowsMobile() \
or self.detectBlackBerry() \
or self.detectMeegoPhone() \
or self.detectPalmWebOS() | python | {
"resource": ""
} |
q45364 | UAgentInfo.detectMobileQuick | train | def detectMobileQuick(self):
"""Return detection of any mobile device using the quicker method
Detects if the current device is a mobile device.
This method catches most of the popular modern devices.
Excludes Apple iPads and other modern tablets.
"""
#Let's exclude tablets
if self.__isTierTablet:
return False
#Most mobile browsing is done on smartphones
if self.detectSmartphone():
return True
#Catch-all for many mobile devices
if UAgentInfo.mobile in self.__userAgent:
return True
if self.detectOperaMobile():
return True
#We also look for Kindle devices
if self.detectKindle() \
or self.detectAmazonSilk():
return True
if self.detectWapWml() \
or self.detectMidpCapable() \
or self.detectBrewDevice():
return True
if UAgentInfo.engineNetfront in self.__userAgent \
or UAgentInfo.engineUpBrowser in self.__userAgent:
return True
return False | python | {
"resource": ""
} |
q45365 | UAgentInfo.detectMobileLong | train | def detectMobileLong(self):
"""Return detection of any mobile device using the more thorough method
The longer and more thorough way to detect for a mobile device.
Will probably detect most feature phones,
smartphone-class devices, Internet Tablets,
Internet-enabled game consoles, etc.
This ought to catch a lot of the more obscure and older devices, also --
but no promises on thoroughness!
"""
if self.detectMobileQuick() \
or self.detectGameConsole():
return True
if self.detectDangerHiptop() \
or self.detectMaemoTablet() \
or self.detectSonyMylo() \
or self.detectArchos():
return True
if UAgentInfo.devicePda in self.__userAgent \
and UAgentInfo.disUpdate not in self.__userAgent:
return True
#detect older phones from certain manufacturers and operators.
return UAgentInfo.uplink in self.__userAgent \
or UAgentInfo.engineOpenWeb in self.__userAgent \
or UAgentInfo.manuSamsung1 in self.__userAgent \
or UAgentInfo.manuSonyEricsson in self.__userAgent \
or UAgentInfo.manuericsson in self.__userAgent \
or UAgentInfo.svcDocomo in self.__userAgent \
or UAgentInfo.svcKddi in self.__userAgent \
or UAgentInfo.svcVodafone in self.__userAgent | python | {
"resource": ""
} |
q45366 | UAgentInfo.detectTierTablet | train | def detectTierTablet(self):
"""Return detection of any device in the Tablet Tier
The quick way to detect for a tier of devices.
This method detects for the new generation of
HTML 5 capable, larger screen tablets.
Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc.
"""
return self.detectIpad() \
or self.detectAndroidTablet() \
or self.detectBlackBerryTablet() \
or self.detectFirefoxOSTablet() \
or self.detectUbuntuTablet() \
or self.detectWebOSTablet() | python | {
"resource": ""
} |
q45367 | UAgentInfo.detectTierRichCss | train | def detectTierRichCss(self):
"""Return detection of any device in the 'Rich CSS' Tier
The quick way to detect for a tier of devices.
This method detects for devices which are likely to be capable
of viewing CSS content optimized for the iPhone,
but may not necessarily support JavaScript.
Excludes all iPhone Tier devices.
"""
#The following devices are explicitly ok.
#Note: 'High' BlackBerry devices ONLY
if not self.detectMobileQuick():
return False
#Exclude iPhone Tier and e-Ink Kindle devices
if self.detectTierIphone() \
or self.detectKindle():
return False
#The following devices are explicitly ok.
#Note: 'High' BlackBerry devices ONLY
#Older Windows 'Mobile' isn't good enough for iPhone Tier.
return self.detectWebkit() \
or self.detectS60OssBrowser() \
or self.detectBlackBerryHigh() \
or self.detectWindowsMobile() \
or UAgentInfo.engineTelecaQ in self.__userAgent | python | {
"resource": ""
} |
q45368 | Status.str_to_date | train | def str_to_date(self):
"""
Returns the date attribute as a date object.
:returns: Date of the status if it exists.
:rtype: date or NoneType
"""
if hasattr(self, 'date'):
return date(*list(map(int, self.date.split('-'))))
else:
return None | python | {
"resource": ""
} |
q45369 | cancel_on_closing | train | def cancel_on_closing(func):
"""
Automatically cancels a function or coroutine when the defining instance
gets closed.
:param func: The function to cancel on closing.
:returns: A decorated function or coroutine.
"""
@wraps(func)
async def wrapper(self, *args, **kwargs):
return await self.await_until_closing(func(self, *args, **kwargs))
return wrapper | python | {
"resource": ""
} |
q45370 | ClosableAsyncObject.await_until_closing | train | async def await_until_closing(self, coro):
"""
Wait for some task to complete but aborts as soon asthe instance is
being closed.
:param coro: The coroutine or future-like object to wait for.
"""
wait_task = asyncio.ensure_future(self.wait_closing(), loop=self.loop)
coro_task = asyncio.ensure_future(coro, loop=self.loop)
try:
done, pending = await asyncio.wait(
[wait_task, coro_task],
return_when=asyncio.FIRST_COMPLETED,
loop=self.loop,
)
finally:
wait_task.cancel()
coro_task.cancel()
# It could be that the previous instructions cancelled coro_task if it
# wasn't done yet.
return await coro_task | python | {
"resource": ""
} |
q45371 | ClosableAsyncObject._set_closed | train | def _set_closed(self, future):
"""
Indicate that the instance is effectively closed.
:param future: The close future.
"""
logger.debug("%s[%s] closed.", self.__class__.__name__, id(self))
self.on_closed.emit(self)
self._closed_future.set_result(future.result()) | python | {
"resource": ""
} |
q45372 | ClosableAsyncObject.close | train | def close(self):
"""
Close the instance.
"""
if not self.closed and not self.closing:
logger.debug(
"%s[%s] closing...",
self.__class__.__name__,
id(self),
)
self._closing.set()
future = asyncio.ensure_future(self.on_close(), loop=self.loop)
future.add_done_callback(self._set_closed) | python | {
"resource": ""
} |
q45373 | CompositeClosableAsyncObject.register_child | train | def register_child(self, child):
"""
Register a new child that will be closed whenever the current instance
closes.
:param child: The child instance.
"""
if self.closing:
child.close()
else:
self._children.add(child)
child.on_closed.connect(self.unregister_child) | python | {
"resource": ""
} |
q45374 | CompositeClosableAsyncObject.unregister_child | train | def unregister_child(self, child):
"""
Unregister an existing child that is no longer to be owned by the
current instance.
:param child: The child instance.
"""
self._children.remove(child)
child.on_closed.disconnect(self.unregister_child) | python | {
"resource": ""
} |
q45375 | AsyncTimeout.on_open | train | def on_open(self, callback, timeout):
"""
Initialize a new timeout.
:param callback: The callback to execute when the timeout reaches the
end of its life. May be a coroutine function.
:param timeout: The maximum time to wait for, in seconds.
"""
super().on_open()
self.callback = callback
self.timeout = timeout
self.revive_event = asyncio.Event(loop=self.loop) | python | {
"resource": ""
} |
q45376 | AsyncTimeout.revive | train | def revive(self, timeout=None):
"""
Revive the timeout.
:param timeout: If not `None`, specifies a new timeout value to use.
"""
if timeout is not None:
self.timeout = timeout
self.revive_event.set() | python | {
"resource": ""
} |
q45377 | AsyncPeriodicTimer.on_open | train | def on_open(self, callback, period):
"""
Initialize a new timer.
:param callback: The function or coroutine function to call on each
tick.
:param period: The interval of time between two ticks.
"""
super().on_open()
self.callback = callback
self.period = period
self.reset_event = asyncio.Event(loop=self.loop) | python | {
"resource": ""
} |
q45378 | AsyncPeriodicTimer.reset | train | def reset(self, period=None):
"""
Reset the internal timer, effectively causing the next tick to happen
in `self.period` seconds.
:param period: If not `None`, specifies a new period to use.
"""
if period is not None:
self.period = period
self.reset_event.set() | python | {
"resource": ""
} |
q45379 | AsyncBox.read | train | async def read(self):
"""
Read from the box in a blocking manner.
:returns: An item from the box.
"""
result = await self._queue.get()
self._can_write.set()
if self._queue.empty():
self._can_read.clear()
return result | python | {
"resource": ""
} |
q45380 | AsyncBox.read_nowait | train | def read_nowait(self):
"""
Read from the box in a non-blocking manner.
If the box is empty, an exception is thrown. You should always check
for emptiness with `empty` or `wait_not_empty` before calling this
method.
:returns: An item from the box.
"""
result = self._queue.get_nowait()
self._can_write.set()
if self._queue.empty():
self._can_read.clear()
return result | python | {
"resource": ""
} |
q45381 | AsyncBox.write | train | async def write(self, item):
"""
Write an item in the queue.
:param item: The item.
"""
await self._queue.put(item)
self._can_read.set()
if self._queue.full():
self._can_write.clear() | python | {
"resource": ""
} |
q45382 | AsyncBox.write_nowait | train | def write_nowait(self, item):
"""
Write in the box in a non-blocking manner.
If the box is full, an exception is thrown. You should always check
for fullness with `full` or `wait_not_full` before calling this method.
:param item: An item.
"""
self._queue.put_nowait(item)
self._can_read.set()
if self._queue.full():
self._can_write.clear() | python | {
"resource": ""
} |
q45383 | AsyncBox.clone | train | def clone(self):
"""
Clone the box.
:returns: A new box with the same item queue.
The cloned box is not closed, no matter the initial state of the
original instance.
"""
result = AsyncBox(maxsize=self._maxsize, loop=self.loop)
result._queue = self._queue
result._can_read = self._can_read
result._can_write = self._can_write
return result | python | {
"resource": ""
} |
q45384 | LValue.get_expr | train | def get_expr(self, ctx):
"""
Returns the MUF needed to get the contents of the lvalue.
Returned MUF will push the contained value onto the stack.
"""
varname = ctx.lookup_variable(self.varname)
if varname is None:
val = ctx.lookup_constant(self.varname)
if val:
try:
return val.generate_code(ctx)
except AttributeError:
return val
raise MuvError(
"Undeclared identifier '%s'." % self.varname,
position=self.position
)
if len(self.indexing) == 0:
return "{var} @".format(
var=varname,
)
if len(self.indexing) == 1:
return "{var} @ {idx} []".format(
var=varname,
idx=self.indexing[0],
)
return (
"{var} @ {{ {idx} }}list array_nested_get".format(
var=varname,
idx=" ".join(str(x) for x in self.indexing),
)
) | python | {
"resource": ""
} |
q45385 | Cluster.create_bare | train | def create_bare(self):
"""
Create instances for the Bare provider
"""
self.instances = []
for ip in self.settings['NODES']:
new_instance = Instance.new(settings=self.settings, cluster=self)
new_instance.ip = ip
self.instances.append(new_instance) | python | {
"resource": ""
} |
q45386 | Cluster.create_cloud | train | def create_cloud(self):
"""
Create instances for the cloud providers
"""
instances = []
for i in range(self.settings['NUMBER_NODES']):
new_instance = Instance.new(settings=self.settings, cluster=self)
instances.append(new_instance)
create_nodes = [instance.create(suffix=i) for i, instance in enumerate(instances)]
fetch_nodes = [instance.node for instance in instances]
self.driver.wait_until_running(fetch_nodes)
node_ids = [node.id for node in fetch_nodes]
all_nodes = self.driver.list_nodes()
new_nodes = [node for node in all_nodes if node.id in node_ids]
for instance, node in zip(instances, new_nodes):
instance.node = node
self.instances = instances | python | {
"resource": ""
} |
q45387 | deserialize_uri | train | def deserialize_uri(value):
"""
Deserialize a representation of a BNode or URIRef.
"""
if isinstance(value, BNode):
return value
if isinstance(value, URIRef):
return value
if not value:
return None
if not isinstance(value, basestring):
raise ValueError("Cannot create URI from {0} of type {1}".format(value, value.__class__))
if value.startswith("_:"):
return BNode(value[2:])
return URIRef(value) | python | {
"resource": ""
} |
q45388 | serialize_uri | train | def serialize_uri(value):
"""
Serialize a BNode or URIRef.
"""
if isinstance(value, BNode):
return value.n3()
if isinstance(value, URIRef):
return unicode(value)
raise ValueError("Cannot get prepvalue for {0} of type {1}".format(value, value.__class__)) | python | {
"resource": ""
} |
q45389 | CrabGateway.list_gewesten | train | def list_gewesten(self, sort=1):
'''
List all `gewesten` in Belgium.
:param integer sort: What field to sort on.
:rtype: A :class`list` of class: `Gewest`.
'''
def creator():
res = crab_gateway_request(self.client, 'ListGewesten', sort)
tmp = {}
for r in res.GewestItem:
if r.GewestId not in tmp:
tmp[r.GewestId] = {}
tmp[r.GewestId][r.TaalCodeGewestNaam] = r.GewestNaam
return[
Gewest(
k,
v
)for k, v in tmp.items()
]
if self.caches['permanent'].is_configured:
key = 'ListGewesten#%s' % sort
gewesten = self.caches['permanent'].get_or_create(key, creator)
else:
gewesten = creator()
for g in gewesten:
g.set_gateway(self)
return gewesten | python | {
"resource": ""
} |
q45390 | CrabGateway.get_gewest_by_id | train | def get_gewest_by_id(self, id):
'''
Get a `gewest` by id.
:param integer id: The id of a `gewest`.
:rtype: A :class:`Gewest`.
'''
def creator():
nl = crab_gateway_request(
self.client, 'GetGewestByGewestIdAndTaalCode', id, 'nl'
)
fr = crab_gateway_request(
self.client, 'GetGewestByGewestIdAndTaalCode', id, 'fr'
)
de = crab_gateway_request(
self.client, 'GetGewestByGewestIdAndTaalCode', id, 'de'
)
if nl == None:
raise GatewayResourceNotFoundException()
return Gewest(
nl.GewestId,
{
'nl': nl.GewestNaam,
'fr': fr.GewestNaam,
'de': de.GewestNaam
},
(nl.CenterX, nl.CenterY),
(nl.MinimumX, nl.MinimumY, nl.MaximumX, nl.MaximumY),
)
if self.caches['permanent'].is_configured:
key = 'GetGewestByGewestId#%s' % id
gewest = self.caches['long'].get_or_create(key, creator)
else:
gewest = creator()
gewest.set_gateway(self)
return gewest | python | {
"resource": ""
} |
q45391 | CrabGateway.list_provincies | train | def list_provincies(self, gewest=2):
'''
List all `provincies` in a `gewest`.
:param gewest: The :class:`Gewest` for which the \
`provincies` are wanted.
:param integer sort: What field to sort on.
:rtype: A :class:`list` of :class:`Provincie`.
'''
try:
gewest_id = gewest.id
except AttributeError:
gewest_id = gewest
def creator():
return [Provincie(p[0], p[1], Gewest(p[2])) for p in self.provincies if p[2] == gewest_id]
if self.caches['permanent'].is_configured:
key = 'ListProvinciesByGewestId#%s' % gewest_id
provincies = self.caches['permanent'].get_or_create(key, creator)
else:
provincies = creator()
for p in provincies:
p.set_gateway(self)
return provincies | python | {
"resource": ""
} |
q45392 | CrabGateway.get_provincie_by_id | train | def get_provincie_by_id(self, niscode):
'''
Retrieve a `provincie` by the niscode.
:param integer niscode: The niscode of the provincie.
:rtype: :class:`Provincie`
'''
def creator():
for p in self.provincies:
if p[0] == niscode:
return Provincie(p[0], p[1], Gewest(p[2]))
if self.caches['permanent'].is_configured:
key = 'GetProvincieByProvincieNiscode#%s' % niscode
provincie = self.caches['permanent'].get_or_create(key, creator)
else:
provincie = creator()
if provincie == None:
raise GatewayResourceNotFoundException()
provincie.set_gateway(self)
return provincie | python | {
"resource": ""
} |
q45393 | CrabGateway.list_gemeenten_by_provincie | train | def list_gemeenten_by_provincie(self, provincie):
'''
List all `gemeenten` in a `provincie`.
:param provincie: The :class:`Provincie` for which the \
`gemeenten` are wanted.
:rtype: A :class:`list` of :class:`Gemeente`.
'''
try:
gewest = provincie.gewest
prov = provincie
except AttributeError:
prov = self.get_provincie_by_id(provincie)
gewest = prov.gewest
gewest.clear_gateway()
def creator():
gewest_gemeenten = self.list_gemeenten(gewest.id)
return[
Gemeente(
r.id,
r.naam,
r.niscode,
gewest
)for r in gewest_gemeenten if str(r.niscode)[0] == str(prov.niscode)[0]
]
if self.caches['permanent'].is_configured:
key = 'ListGemeentenByProvincieId#%s' % prov.id
gemeente = self.caches['long'].get_or_create(key, creator)
else:
gemeente = creator()
for g in gemeente:
g.set_gateway(self)
return gemeente | python | {
"resource": ""
} |
q45394 | CrabGateway.list_gemeenten | train | def list_gemeenten(self, gewest=2, sort=1):
'''
List all `gemeenten` in a `gewest`.
:param gewest: The :class:`Gewest` for which the \
`gemeenten` are wanted.
:param integer sort: What field to sort on.
:rtype: A :class:`list` of :class:`Gemeente`.
'''
try:
gewest_id = gewest.id
except AttributeError:
gewest_id = gewest
gewest = self.get_gewest_by_id(gewest_id)
gewest.clear_gateway()
def creator():
res = crab_gateway_request(
self.client, 'ListGemeentenByGewestId', gewest_id, sort
)
return[
Gemeente(
r.GemeenteId,
r.GemeenteNaam,
r.NISGemeenteCode,
gewest
)for r in res.GemeenteItem if r.TaalCode == r.TaalCodeGemeenteNaam
]
if self.caches['permanent'].is_configured:
key = 'ListGemeentenByGewestId#%s#%s' % (gewest_id, sort)
gemeenten = self.caches['permanent'].get_or_create(key, creator)
else:
gemeenten = creator()
for g in gemeenten:
g.set_gateway(self)
return gemeenten | python | {
"resource": ""
} |
q45395 | CrabGateway.get_gemeente_by_id | train | def get_gemeente_by_id(self, id):
'''
Retrieve a `gemeente` by the crab id.
:param integer id: The CRAB id of the gemeente.
:rtype: :class:`Gemeente`
'''
def creator():
res = crab_gateway_request(
self.client, 'GetGemeenteByGemeenteId', id
)
if res == None:
raise GatewayResourceNotFoundException()
return Gemeente(
res.GemeenteId,
res.GemeenteNaam,
res.NisGemeenteCode,
Gewest(res.GewestId),
res.TaalCode,
(res.CenterX, res.CenterY),
(res.MinimumX, res.MinimumY, res.MaximumX, res.MaximumY),
Metadata(
res.BeginDatum,
res.BeginTijd,
self.get_bewerking(res.BeginBewerking),
self.get_organisatie(res.BeginOrganisatie)
)
)
if self.caches['long'].is_configured:
key = 'GetGemeenteByGemeenteId#%s' % id
gemeente = self.caches['long'].get_or_create(key, creator)
else:
gemeente = creator()
gemeente.set_gateway(self)
return gemeente | python | {
"resource": ""
} |
q45396 | CrabGateway.list_deelgemeenten | train | def list_deelgemeenten(self, gewest=2):
'''
List all `deelgemeenten` in a `gewest`.
:param gewest: The :class:`Gewest` for which the \
`deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`.
'''
try:
gewest_id = gewest.id
except AttributeError:
gewest_id = gewest
if gewest_id != 2:
raise ValueError('Currently only deelgemeenten in Flanders are known.')
def creator():
return [Deelgemeente(dg['id'], dg['naam'], dg['gemeente_niscode']) for dg in self.deelgemeenten.values()]
if self.caches['permanent'].is_configured:
key = 'ListDeelgemeentenByGewestId#%s' % gewest_id
deelgemeenten = self.caches['permanent'].get_or_create(key, creator)
else:
deelgemeenten = creator()
for dg in deelgemeenten:
dg.set_gateway(self)
return deelgemeenten | python | {
"resource": ""
} |
q45397 | CrabGateway.list_deelgemeenten_by_gemeente | train | def list_deelgemeenten_by_gemeente(self, gemeente):
'''
List all `deelgemeenten` in a `gemeente`.
:param gemeente: The :class:`Gemeente` for which the \
`deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`.
'''
try:
niscode = gemeente.niscode
except AttributeError:
niscode = gemeente
def creator():
return [
Deelgemeente(dg['id'], dg['naam'], dg['gemeente_niscode'])
for dg in self.deelgemeenten.values() if dg['gemeente_niscode'] == niscode
]
if self.caches['permanent'].is_configured:
key = 'ListDeelgemeentenByGemeenteId#%s' % niscode
deelgemeenten = self.caches['permanent'].get_or_create(key, creator)
else:
deelgemeenten = creator()
for dg in deelgemeenten:
dg.set_gateway(self)
return deelgemeenten | python | {
"resource": ""
} |
q45398 | CrabGateway.get_deelgemeente_by_id | train | def get_deelgemeente_by_id(self, id):
'''
Retrieve a `deelgemeente` by the id.
:param string id: The id of the deelgemeente.
:rtype: :class:`Deelgemeente`
'''
def creator():
if id in self.deelgemeenten:
dg = self.deelgemeenten[id]
return Deelgemeente(dg['id'], dg['naam'], dg['gemeente_niscode'])
else:
return None
if self.caches['permanent'].is_configured:
key = 'GetDeelgemeenteByDeelgemeenteId#%s' % id
deelgemeente = self.caches['permanent'].get_or_create(key, creator)
else:
deelgemeente = creator()
if deelgemeente == None:
raise GatewayResourceNotFoundException()
deelgemeente.set_gateway(self)
return deelgemeente | python | {
"resource": ""
} |
q45399 | CrabGateway.list_straten | train | def list_straten(self, gemeente, sort=1):
'''
List all `straten` in a `Gemeente`.
:param gemeente: The :class:`Gemeente` for which the \
`straten` are wanted.
:rtype: A :class:`list` of :class:`Straat`
'''
try:
id = gemeente.id
except AttributeError:
id = gemeente
def creator():
res = crab_gateway_request(
self.client, 'ListStraatnamenWithStatusByGemeenteId',
id, sort
)
try:
return[
Straat(
r.StraatnaamId,
r.StraatnaamLabel,
id,
r.StatusStraatnaam
)for r in res.StraatnaamWithStatusItem
]
except AttributeError:
return []
if self.caches['long'].is_configured:
key = 'ListStraatnamenWithStatusByGemeenteId#%s%s' % (id, sort)
straten = self.caches['long'].get_or_create(key, creator)
else:
straten = creator()
for s in straten:
s.set_gateway(self)
return straten | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.