_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q258400 | BasePlayer._ensure_started | validation | def _ensure_started(self):
"""Ensure player backing process is started
"""
if self._process and self._process.poll() is None:
return
if not getattr(self, "_cmd"):
raise RuntimeError("Player command is not configured")
log.debug("Starting playback command... | python | {
"resource": ""
} |
q258401 | BasePlayer.play | validation | def play(self, song):
"""Play a new song from a Pandora model
Returns once the stream starts but does not shut down the remote audio
output backend process. Calls the input callback when the user has
input.
"""
self._callbacks.play(song)
self._load_track(song)
... | python | {
"resource": ""
} |
q258402 | BasePlayer.play_station | validation | def play_station(self, station):
"""Play the station until something ends it
This function will run forever until termintated by calling
end_station.
"""
for song in iterate_forever(station.get_playlist):
try:
self.play(song)
except StopIt... | python | {
"resource": ""
} |
q258403 | VLCPlayer._post_start | validation | def _post_start(self):
"""Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin... | python | {
"resource": ""
} |
q258404 | PlayerApp.station_selection_menu | validation | def station_selection_menu(self, error=None):
"""Format a station menu and make the user select a station
"""
self.screen.clear()
if error:
self.screen.print_error("{}\n".format(error))
for i, station in enumerate(self.stations):
i = "{:>3}".format(i)
... | python | {
"resource": ""
} |
q258405 | PlayerApp.input | validation | def input(self, input, song):
"""Input callback, handles key presses
"""
try:
cmd = getattr(self, self.CMD_MAP[input][1])
except (IndexError, KeyError):
return self.screen.print_error(
"Invalid command {!r}!".format(input))
cmd(song) | python | {
"resource": ""
} |
q258406 | retries | validation | def retries(max_tries, exceptions=(Exception,)):
"""Function decorator implementing retrying logic.
exceptions: A tuple of exception classes; default (Exception,)
The decorator will call the function up to max_tries times if it raises
an exception.
By default it catches instances of the Exception... | python | {
"resource": ""
} |
q258407 | iterate_forever | validation | def iterate_forever(func, *args, **kwargs):
"""Iterate over a finite iterator forever
When the iterator is exhausted will call the function again to generate a
new iterator and keep iterating.
"""
output = func(*args, **kwargs)
while True:
try:
playlist_item = next(output)
... | python | {
"resource": ""
} |
q258408 | Screen.get_integer | validation | def get_integer(prompt):
"""Gather user input and convert it to an integer
Will keep trying till the user enters an interger or until they ^C the
program.
"""
while True:
try:
return int(input(prompt).strip())
except ValueError:
... | python | {
"resource": ""
} |
q258409 | TaskPackageDropbox.open | validation | def open(self):
"""open the drop box
You need to call this method before starting putting packages.
Returns
-------
None
"""
self.workingArea.open()
self.runid_pkgidx_map = { }
self.runid_to_return = deque() | python | {
"resource": ""
} |
q258410 | TaskPackageDropbox.put | validation | def put(self, package):
"""put a task
This method places a task in the working area and have the
dispatcher execute it.
If you need to put multiple tasks, it can be much faster to
use `put_multiple()` than to use this method multiple times
depending of the dispatcher.
... | python | {
"resource": ""
} |
q258411 | TaskPackageDropbox.receive | validation | def receive(self):
"""return pairs of package indices and results of all tasks
This method waits until all tasks finish.
Returns
-------
list
A list of pairs of package indices and results
"""
ret = [ ] # a list of (pkgid, result)
while Tru... | python | {
"resource": ""
} |
q258412 | TaskPackageDropbox.poll | validation | def poll(self):
"""return pairs of package indices and results of finished tasks
This method does not wait for tasks to finish.
Returns
-------
list
A list of pairs of package indices and results
"""
self.runid_to_return.extend(self.dispatcher.poll... | python | {
"resource": ""
} |
q258413 | TaskPackageDropbox.receive_one | validation | def receive_one(self):
"""return a pair of a package index and result of a task
This method waits until a tasks finishes. It returns `None` if
no task is running.
Returns
-------
tuple or None
A pair of a package index and result. `None` if no tasks
... | python | {
"resource": ""
} |
q258414 | MPEventLoopRunner.run_multiple | validation | def run_multiple(self, eventLoops):
"""run the event loops in the background.
Args:
eventLoops (list): a list of event loops to run
"""
self.nruns += len(eventLoops)
return self.communicationChannel.put_multiple(eventLoops) | python | {
"resource": ""
} |
q258415 | MPEventLoopRunner.poll | validation | def poll(self):
"""Return pairs of run ids and results of finish event loops.
"""
ret = self.communicationChannel.receive_finished()
self.nruns -= len(ret)
return ret | python | {
"resource": ""
} |
q258416 | MPEventLoopRunner.receive_one | validation | def receive_one(self):
"""Return a pair of a run id and a result.
This method waits until an event loop finishes.
This method returns None if no loop is running.
"""
if self.nruns == 0:
return None
ret = self.communicationChannel.receive_one()
if ret ... | python | {
"resource": ""
} |
q258417 | MPEventLoopRunner.receive | validation | def receive(self):
"""Return pairs of run ids and results.
This method waits until all event loops finish
"""
ret = self.communicationChannel.receive_all()
self.nruns -= len(ret)
if self.nruns > 0:
import logging
logger = logging.getLogger(__name_... | python | {
"resource": ""
} |
q258418 | MPEventLoopRunner.end | validation | def end(self):
"""wait until all event loops end and returns the results.
"""
results = self.communicationChannel.receive()
if self.nruns != len(results):
import logging
logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
... | python | {
"resource": ""
} |
q258419 | key_vals_dict_to_tuple_list | validation | def key_vals_dict_to_tuple_list(key_vals_dict, fill=float('nan')):
"""Convert ``key_vals_dict`` to `tuple_list``.
Args:
key_vals_dict (dict): The first parameter.
fill: a value to fill missing data
Returns:
A list of tuples
"""
tuple_list = [ ]
if not key_vals_dict: ... | python | {
"resource": ""
} |
q258420 | WorkingArea.open | validation | def open(self):
"""Open the working area
Returns
-------
None
"""
self.path = self._prepare_dir(self.topdir)
self._copy_executable(area_path=self.path)
self._save_logging_levels(area_path=self.path)
self._put_python_modules(modules=self.python_mo... | python | {
"resource": ""
} |
q258421 | WorkingArea.put_package | validation | def put_package(self, package):
"""Put a package
Parameters
----------
package :
a task package
Returns
-------
int
A package index
"""
self.last_package_index += 1
package_index = self.last_package_index
... | python | {
"resource": ""
} |
q258422 | WorkingArea.collect_result | validation | def collect_result(self, package_index):
"""Collect the result of a task
Parameters
----------
package_index :
a package index
Returns
-------
obj
The result of the task
"""
result_fullpath = self.result_fullpath(package... | python | {
"resource": ""
} |
q258423 | WorkingArea.package_fullpath | validation | def package_fullpath(self, package_index):
"""Returns the full path of the package
This method returns the full path to the package. This method
simply constructs the path based on the convention and doesn't
check if the package actually exists.
Parameters
----------
... | python | {
"resource": ""
} |
q258424 | WorkingArea.result_relpath | validation | def result_relpath(self, package_index):
"""Returns the relative path of the result
This method returns the path to the result relative to the
top dir of the working area. This method simply constructs the
path based on the convention and doesn't check if the result
actually exi... | python | {
"resource": ""
} |
q258425 | WorkingArea.result_fullpath | validation | def result_fullpath(self, package_index):
"""Returns the full path of the result
This method returns the full path to the result. This method
simply constructs the path based on the convention and doesn't
check if the result actually exists.
Parameters
----------
... | python | {
"resource": ""
} |
q258426 | HTCondorJobSubmitter.run_multiple | validation | def run_multiple(self, workingArea, package_indices):
"""Submit multiple jobs
Parameters
----------
workingArea :
A workingArea
package_indices : list(int)
A list of package indices
Returns
-------
list(str)
The list o... | python | {
"resource": ""
} |
q258427 | HTCondorJobSubmitter.poll | validation | def poll(self):
"""Return the run IDs of the finished jobs
Returns
-------
list(str)
The list of the run IDs of the finished jobs
"""
clusterids = clusterprocids2clusterids(self.clusterprocids_outstanding)
clusterprocid_status_list = query_status_fo... | python | {
"resource": ""
} |
q258428 | HTCondorJobSubmitter.wait | validation | def wait(self):
"""Wait until all jobs finish and return the run IDs of the finished jobs
Returns
-------
list(str)
The list of the run IDs of the finished jobs
"""
sleep = 5
while True:
if self.clusterprocids_outstanding:
... | python | {
"resource": ""
} |
q258429 | HTCondorJobSubmitter.failed_runids | validation | def failed_runids(self, runids):
"""Provide the run IDs of failed jobs
Returns
-------
None
"""
# remove failed clusterprocids from self.clusterprocids_finished
# so that len(self.clusterprocids_finished)) becomes the number
# of the successfully finis... | python | {
"resource": ""
} |
q258430 | BranchAddressManager.getArrays | validation | def getArrays(self, tree, branchName):
"""return the array.array objects for the branch and its counter branch
This method returns a pair of the array.array objects. The first one is
for the given tree and branch name. The second one is for its counter
branch. The second one will be Non... | python | {
"resource": ""
} |
q258431 | CommunicationChannel.put | validation | def put(self, task, *args, **kwargs):
"""put a task and its arguments
If you need to put multiple tasks, it can be faster to put
multiple tasks with `put_multiple()` than to use this method
multiple times.
Parameters
----------
task : a function
A fu... | python | {
"resource": ""
} |
q258432 | CommunicationChannel.put_multiple | validation | def put_multiple(self, task_args_kwargs_list):
"""put a list of tasks and their arguments
This method can be used to put multiple tasks at once. Calling
this method once with multiple tasks can be much faster than
calling `put()` multiple times.
Parameters
----------
... | python | {
"resource": ""
} |
q258433 | CommunicationChannel.receive_finished | validation | def receive_finished(self):
"""return a list of pairs of IDs and results of finished tasks.
This method doesn't wait for tasks to finish. It returns IDs
and results which have already finished.
Returns
-------
list
A list of pairs of IDs and results
... | python | {
"resource": ""
} |
q258434 | CommunicationChannel.receive_one | validation | def receive_one(self):
"""return a pair of an ID and a result of a task.
This method waits for a task to finish.
Returns
-------
An ID and a result of a task. `None` if no task is running.
"""
if not self.isopen:
logger = logging.getLogger(__name__)... | python | {
"resource": ""
} |
q258435 | CommunicationChannel.receive_all | validation | def receive_all(self):
"""return a list of pairs of IDs and results of all tasks.
This method waits for all tasks to finish.
Returns
-------
list
A list of pairs of IDs and results
"""
if not self.isopen:
logger = logging.getLogger(__nam... | python | {
"resource": ""
} |
q258436 | CommunicationChannel.receive | validation | def receive(self):
"""return a list results of all tasks.
This method waits for all tasks to finish.
Returns
-------
list
A list of results of the tasks. The results are sorted in
the order in which the tasks are put.
"""
pkgidx_result_p... | python | {
"resource": ""
} |
q258437 | expand_path_cfg | validation | def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }):
"""expand a path config
Args:
path_cfg (str, tuple, dict): a config for path
alias_dict (dict): a dict for aliases
overriding_kargs (dict): to be used for recursive call
"""
if isinstance(path_cfg, str):
... | python | {
"resource": ""
} |
q258438 | _expand_tuple | validation | def _expand_tuple(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a tuple
"""
# e.g.,
# path_cfg = ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200})
# overriding_kargs = {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25}
new_path_cfg = path_cfg[0]
... | python | {
"resource": ""
} |
q258439 | SubprocessRunner.poll | validation | def poll(self):
"""check if the jobs are running and return a list of pids for
finished jobs
"""
finished_procs = [p for p in self.running_procs if p.poll() is not None]
self.running_procs = collections.deque([p for p in self.running_procs if p not in finished_procs])
f... | python | {
"resource": ""
} |
q258440 | SubprocessRunner.wait | validation | def wait(self):
"""wait until all jobs finish and return a list of pids
"""
finished_pids = [ ]
while self.running_procs:
finished_pids.extend(self.poll())
return finished_pids | python | {
"resource": ""
} |
q258441 | BranchAddressManagerForVector.getVector | validation | def getVector(self, tree, branchName):
"""return the ROOT.vector object for the branch.
"""
if (tree, branchName) in self.__class__.addressDict:
return self.__class__.addressDict[(tree, branchName)]
itsVector = self._getVector(tree, branchName)
self.__class__.addre... | python | {
"resource": ""
} |
q258442 | CMakeGen.configure | validation | def configure(self, component, all_dependencies):
''' Ensure all config-time files have been generated. Return a
dictionary of generated items.
'''
r = {}
builddir = self.buildroot
# only dependencies which are actually valid can contribute to the
# config d... | python | {
"resource": ""
} |
q258443 | _getTarball | validation | def _getTarball(url, into_directory, cache_key, origin_info=None):
'''unpack the specified tarball url into the specified directory'''
try:
access_common.unpackFromCache(cache_key, into_directory)
except KeyError as e:
tok = settings.getProperty('github', 'authtoken')
headers = {}
... | python | {
"resource": ""
} |
q258444 | GithubComponent.availableVersions | validation | def availableVersions(self):
''' return a list of Version objects, each with a tarball URL set '''
r = []
for t in self._getTags():
logger.debug("available version tag: %s", t)
# ignore empty tags:
if not len(t[0].strip()):
continue
... | python | {
"resource": ""
} |
q258445 | GithubComponent.availableTags | validation | def availableTags(self):
''' return a list of GithubComponentVersion objects for all tags
'''
return [
GithubComponentVersion(
'', t[0], t[1], self.name, cache_key=_createCacheKey('tag', t[0], t[1], self.name)
) for t in self._getTags()
] | python | {
"resource": ""
} |
q258446 | GithubComponent.availableBranches | validation | def availableBranches(self):
''' return a list of GithubComponentVersion objects for the tip of each branch
'''
return [
GithubComponentVersion(
'', b[0], b[1], self.name, cache_key=None
) for b in _getBranchHeads(self.repo).items()
] | python | {
"resource": ""
} |
q258447 | _raiseUnavailableFor401 | validation | def _raiseUnavailableFor401(message):
''' Returns a decorator to swallow a requests exception for modules that
are not accessible without logging in, and turn it into an Unavailable
exception.
'''
def __raiseUnavailableFor401(fn):
def wrapped(*args, **kwargs):
try:
... | python | {
"resource": ""
} |
q258448 | unpublish | validation | def unpublish(namespace, name, version, registry=None):
''' Try to unpublish a recently published version. Return any errors that
occur.
'''
registry = registry or Registry_Base_URL
url = '%s/%s/%s/versions/%s' % (
registry,
namespace,
name,
version
)
he... | python | {
"resource": ""
} |
q258449 | _JSONConfigParser.read | validation | def read(self, filenames):
'''' Read a list of files. Their configuration values are merged, with
preference to values from files earlier in the list.
'''
for fn in filenames:
try:
self.configs[fn] = ordered_json.load(fn)
except IOError:
... | python | {
"resource": ""
} |
q258450 | _JSONConfigParser.get | validation | def get(self, path):
''' return a configuration value
usage:
get('section.property')
Note that currently array indexes are not supported. You must
get the whole array.
returns None if any path element or the property is missing
'''
... | python | {
"resource": ""
} |
q258451 | _JSONConfigParser.set | validation | def set(self, path, value=None, filename=None):
''' Set a configuration value. If no filename is specified, the
property is set in the first configuration file. Note that if a
filename is specified and the property path is present in an
earlier filename then set property will... | python | {
"resource": ""
} |
q258452 | islast | validation | def islast(generator):
''' indicate whether the current item is the last one in a generator
'''
next_x = None
first = True
for x in generator:
if not first:
yield (next_x, False)
next_x = x
first = False
if not first:
yield (next_x, True) | python | {
"resource": ""
} |
q258453 | sourceDirValidationError | validation | def sourceDirValidationError(dirname, component_name):
''' validate source directory names in components '''
if dirname == component_name:
return 'Module %s public include directory %s should not contain source files' % (component_name, dirname)
elif dirname.lower() in ('source', 'src') and dirname ... | python | {
"resource": ""
} |
q258454 | displayOutdated | validation | def displayOutdated(modules, dependency_specs, use_colours):
''' print information about outdated modules,
return 0 if there is nothing to be done and nonzero otherwise
'''
if use_colours:
DIM = colorama.Style.DIM #pylint: disable=no-member
NORMAL = colorama.Style.NORMAL ... | python | {
"resource": ""
} |
q258455 | Pack.ignores | validation | def ignores(self, path):
''' Test if this module ignores the file at "path", which must be a
path relative to the root of the module.
If a file is within a directory that is ignored, the file is also
ignored.
'''
test_path = PurePath('/', path)
# als... | python | {
"resource": ""
} |
q258456 | Pack.publish | validation | def publish(self, registry=None):
''' Publish to the appropriate registry, return a description of any
errors that occured, or None if successful.
No VCS tagging is performed.
'''
if (registry is None) or (registry == registry_access.Registry_Base_URL):
if 'pr... | python | {
"resource": ""
} |
q258457 | Pack.unpublish | validation | def unpublish(self, registry=None):
''' Try to un-publish the current version. Return a description of any
errors that occured, or None if successful.
'''
return registry_access.unpublish(
self.getRegistryNamespace(),
self.getName(),
self.getVersio... | python | {
"resource": ""
} |
q258458 | Pack.getScript | validation | def getScript(self, scriptname):
''' Return the specified script command. If the first part of the
command is a .py file, then the current python interpreter is
prepended.
If the script is a single string, rather than an array, it is
shlex-split.
'''
... | python | {
"resource": ""
} |
q258459 | Pack.runScript | validation | def runScript(self, scriptname, additional_environment=None):
''' Run the specified script from the scripts section of the
module.json file in the directory of this module.
'''
import subprocess
import shlex
command = self.getScript(scriptname)
if command is ... | python | {
"resource": ""
} |
q258460 | Component.hasDependency | validation | def hasDependency(self, name, target=None, test_dependencies=False):
''' Check if this module has any dependencies with the specified name
in its dependencies list, or in target dependencies for the
specified target
'''
if name in self.description.get('dependencies', {}).... | python | {
"resource": ""
} |
q258461 | Component.hasDependencyRecursively | validation | def hasDependencyRecursively(self, name, target=None, test_dependencies=False):
''' Check if this module, or any of its dependencies, have a
dependencies with the specified name in their dependencies, or in
their targetDependencies corresponding to the specified target.
Note... | python | {
"resource": ""
} |
q258462 | Component.satisfyDependenciesRecursive | validation | def satisfyDependenciesRecursive(
self,
available_components = None,
search_dirs = None,
update_installed = False,
traverse_links = False,
target = None,
test = False
... | python | {
"resource": ""
} |
q258463 | Component.getExtraIncludes | validation | def getExtraIncludes(self):
''' Some components must export whole directories full of headers into
the search path. This is really really bad, and they shouldn't do
it, but support is provided as a concession to compatibility.
'''
if 'extraIncludes' in self.description:
... | python | {
"resource": ""
} |
q258464 | GitWorkingCopy.availableVersions | validation | def availableVersions(self):
''' return a list of GitCloneVersion objects for tags which are valid
semantic version idenfitifiers.
'''
r = []
for t in self.vcs.tags():
logger.debug("available version tag: %s", t)
# ignore empty tags:
if not... | python | {
"resource": ""
} |
q258465 | _mergeDictionaries | validation | def _mergeDictionaries(*args):
''' merge dictionaries of dictionaries recursively, with elements from
dictionaries earlier in the argument sequence taking precedence
'''
# to support merging of OrderedDicts, copy the result type from the first
# argument:
result = type(args[0])()
for k, ... | python | {
"resource": ""
} |
q258466 | _mirrorStructure | validation | def _mirrorStructure(dictionary, value):
''' create a new nested dictionary object with the same structure as
'dictionary', but with all scalar values replaced with 'value'
'''
result = type(dictionary)()
for k in dictionary.keys():
if isinstance(dictionary[k], dict):
result[... | python | {
"resource": ""
} |
q258467 | Target.baseTargetSpec | validation | def baseTargetSpec(self):
''' returns pack.DependencySpec for the base target of this target (or
None if this target does not inherit from another target.
'''
inherits = self.description.get('inherits', {})
if len(inherits) == 1:
name, version_req = list(inherits.... | python | {
"resource": ""
} |
q258468 | DerivedTarget._loadConfig | validation | def _loadConfig(self):
''' load the configuration information from the target hierarchy '''
config_dicts = [self.additional_config, self.app_config] + [t.getConfig() for t in self.hierarchy]
# create an identical set of dictionaries, but with the names of the
# sources in place of the va... | python | {
"resource": ""
} |
q258469 | DerivedTarget.inheritsFrom | validation | def inheritsFrom(self, target_name):
''' Return true if this target inherits from the named target (directly
or indirectly. Also returns true if this target is the named
target. Otherwise return false.
'''
for t in self.hierarchy:
if t and t.getName() == targe... | python | {
"resource": ""
} |
q258470 | DerivedTarget.exec_helper | validation | def exec_helper(self, cmd, builddir):
''' Execute the given command, returning an error message if an error occured
or None if the command was succesful.'''
try:
child = subprocess.Popen(cmd, cwd=builddir)
child.wait()
except OSError as e:
if e.err... | python | {
"resource": ""
} |
q258471 | DerivedTarget.build | validation | def build(self, builddir, component, args, release_build=False, build_args=None, targets=None,
release_no_debug_info_build=False):
''' Execute the commands necessary to build this component, and all of
its dependencies. '''
if build_args is None:
build_args = []
... | python | {
"resource": ""
} |
q258472 | DerivedTarget.findProgram | validation | def findProgram(self, builddir, program):
''' Return the builddir-relative path of program, if only a partial
path is specified. Returns None and logs an error message if the
program is ambiguous or not found
'''
# if this is an exact match, do no further checking:
if os... | python | {
"resource": ""
} |
q258473 | DerivedTarget.start | validation | def start(self, builddir, program, forward_args):
''' Launch the specified program. Uses the `start` script if specified
by the target, attempts to run it natively if that script is not
defined.
'''
child = None
try:
prog_path = self.findProgram(buildd... | python | {
"resource": ""
} |
q258474 | pruneCache | validation | def pruneCache():
''' Prune the cache '''
cache_dir = folders.cacheDirectory()
def fullpath(f):
return os.path.join(cache_dir, f)
def getMTimeSafe(f):
# it's possible that another process removed the file before we stat
# it, handle this gracefully
try:
return... | python | {
"resource": ""
} |
q258475 | sometimesPruneCache | validation | def sometimesPruneCache(p):
''' return decorator to prune cache after calling fn with a probability of p'''
def decorator(fn):
@functools.wraps(fn)
def wrapped(*args, **kwargs):
r = fn(*args, **kwargs)
if random.random() < p:
pruneCache()
retur... | python | {
"resource": ""
} |
q258476 | calibrateEB | validation | def calibrateEB(variances, sigma2):
"""
Calibrate noisy variance estimates with empirical Bayes.
Parameters
----------
vars: ndarray
List of variance estimates.
sigma2: int
Estimate of the Monte Carlo noise in vars.
Returns
-------
An array of the calibrated varianc... | python | {
"resource": ""
} |
q258477 | calc_inbag | validation | def calc_inbag(n_samples, forest):
"""
Derive samples used to create trees in scikit-learn RandomForest objects.
Recovers the samples in each tree from the random state of that tree using
:func:`forest._generate_sample_indices`.
Parameters
----------
n_samples : int
The number of s... | python | {
"resource": ""
} |
q258478 | _core_computation | validation | def _core_computation(X_train, X_test, inbag, pred_centered, n_trees,
memory_constrained=False, memory_limit=None,
test_mode=False):
"""
Helper function, that performs the core computation
Parameters
----------
X_train : ndarray
An array with shap... | python | {
"resource": ""
} |
q258479 | _bias_correction | validation | def _bias_correction(V_IJ, inbag, pred_centered, n_trees):
"""
Helper functions that implements bias correction
Parameters
----------
V_IJ : ndarray
Intermediate result in the computation.
inbag : ndarray
The inbag matrix that fit the data. If set to `None` (default) it
... | python | {
"resource": ""
} |
q258480 | random_forest_error | validation | def random_forest_error(forest, X_train, X_test, inbag=None,
calibrate=True, memory_constrained=False,
memory_limit=None):
"""
Calculate error bars from scikit-learn RandomForest estimators.
RandomForest is a regressor or classifier object
this variance c... | python | {
"resource": ""
} |
q258481 | SSLSatchel.generate_self_signed_certificate | validation | def generate_self_signed_certificate(self, domain='', r=None):
"""
Generates a self-signed certificate for use in an internal development
environment for testing SSL pages.
http://almostalldigital.wordpress.com/2013/03/07/self-signed-ssl-certificate-for-ec2-load-balancer/
"""
... | python | {
"resource": ""
} |
q258482 | SSLSatchel.generate_csr | validation | def generate_csr(self, domain='', r=None):
"""
Creates a certificate signing request to be submitted to a formal
certificate authority to generate a certificate.
Note, the provider may say the CSR must be created on the target server,
but this is not necessary.
"""
... | python | {
"resource": ""
} |
q258483 | SSLSatchel.get_expiration_date | validation | def get_expiration_date(self, fn):
"""
Reads the expiration date of a local crt file.
"""
r = self.local_renderer
r.env.crt_fn = fn
with hide('running'):
ret = r.local('openssl x509 -noout -in {ssl_crt_fn} -dates', capture=True)
matches = re.findall('n... | python | {
"resource": ""
} |
q258484 | SSLSatchel.list_expiration_dates | validation | def list_expiration_dates(self, base='roles/all/ssl'):
"""
Scans through all local .crt files and displays the expiration dates.
"""
max_fn_len = 0
max_date_len = 0
data = []
for fn in os.listdir(base):
fqfn = os.path.join(base, fn)
if not ... | python | {
"resource": ""
} |
q258485 | SSLSatchel.verify_certificate_chain | validation | def verify_certificate_chain(self, base=None, crt=None, csr=None, key=None):
"""
Confirms the key, CSR, and certificate files all match.
"""
from burlap.common import get_verbose, print_fail, print_success
r = self.local_renderer
if base:
crt = base + '.crt'... | python | {
"resource": ""
} |
q258486 | update_merge | validation | def update_merge(d, u):
"""
Recursively merges two dictionaries.
Uses fabric's AttributeDict so you can reference values via dot-notation.
e.g. env.value1.value2.value3...
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
"""
import collections... | python | {
"resource": ""
} |
q258487 | check_version | validation | def check_version():
"""
Compares the local version against the latest official version on PyPI and displays a warning message if a newer release is available.
This check can be disabled by setting the environment variable BURLAP_CHECK_VERSION=0.
"""
global CHECK_VERSION
if not CHECK_VERSION:
... | python | {
"resource": ""
} |
q258488 | populate_fabfile | validation | def populate_fabfile():
"""
Automatically includes all submodules and role selectors
in the top-level fabfile using spooky-scary black magic.
This allows us to avoid manually declaring imports for every module, e.g.
import burlap.pip
import burlap.vm
import burlap...
which... | python | {
"resource": ""
} |
q258489 | task_or_dryrun | validation | def task_or_dryrun(*args, **kwargs):
"""
Decorator declaring the wrapped function to be a new-style task.
May be invoked as a simple, argument-less decorator (i.e. ``@task``) or
with arguments customizing its behavior (e.g. ``@task(alias='myalias')``).
Please see the :ref:`new-style task <task-dec... | python | {
"resource": ""
} |
q258490 | task | validation | def task(*args, **kwargs):
"""
Decorator for registering a satchel method as a Fabric task.
Can be used like:
@task
def my_method(self):
...
@task(precursors=['other_satchel'])
def my_method(self):
...
"""
precursors = kwargs.pop('precursor... | python | {
"resource": ""
} |
q258491 | FileSatchel.is_file | validation | def is_file(self, path, use_sudo=False):
"""
Check if a path exists, and is a file.
"""
if self.is_local and not use_sudo:
return os.path.isfile(path)
else:
func = use_sudo and _sudo or _run
with self.settings(hide('running', 'warnings'), warn_... | python | {
"resource": ""
} |
q258492 | FileSatchel.is_dir | validation | def is_dir(self, path, use_sudo=False):
"""
Check if a path exists, and is a directory.
"""
if self.is_local and not use_sudo:
return os.path.isdir(path)
else:
func = use_sudo and _sudo or _run
with self.settings(hide('running', 'warnings'), wa... | python | {
"resource": ""
} |
q258493 | FileSatchel.is_link | validation | def is_link(self, path, use_sudo=False):
"""
Check if a path exists, and is a symbolic link.
"""
func = use_sudo and _sudo or _run
with self.settings(hide('running', 'warnings'), warn_only=True):
return func('[ -L "%(path)s" ]' % locals()).succeeded | python | {
"resource": ""
} |
q258494 | FileSatchel.get_owner | validation | def get_owner(self, path, use_sudo=False):
"""
Get the owner name of a file or directory.
"""
func = use_sudo and run_as_root or self.run
# I'd prefer to use quiet=True, but that's not supported with older
# versions of Fabric.
with self.settings(hide('running', '... | python | {
"resource": ""
} |
q258495 | FileSatchel.umask | validation | def umask(self, use_sudo=False):
"""
Get the user's umask.
Returns a string such as ``'0002'``, representing the user's umask
as an octal number.
If `use_sudo` is `True`, this function returns root's umask.
"""
func = use_sudo and run_as_root or self.run
... | python | {
"resource": ""
} |
q258496 | FileSatchel.upload_template | validation | def upload_template(self, filename, destination, context=None, use_jinja=False,
template_dir=None, use_sudo=False, backup=True,
mirror_local_mode=False, mode=None,
mkdir=False, chown=False, user=None):
"""
Upload a template file.
... | python | {
"resource": ""
} |
q258497 | FileSatchel.md5sum | validation | def md5sum(self, filename, use_sudo=False):
"""
Compute the MD5 sum of a file.
"""
func = use_sudo and run_as_root or self.run
with self.settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
# Linux (LSB)
if exists(u'/usr/bin/md5sum'):... | python | {
"resource": ""
} |
q258498 | FileSatchel.uncommented_lines | validation | def uncommented_lines(self, filename, use_sudo=False):
"""
Get the lines of a remote file, ignoring empty or commented ones
"""
func = run_as_root if use_sudo else self.run
res = func('cat %s' % quote(filename), quiet=True)
if res.succeeded:
return [line for l... | python | {
"resource": ""
} |
q258499 | FileSatchel.getmtime | validation | def getmtime(self, path, use_sudo=False):
"""
Return the time of last modification of path.
The return value is a number giving the number of seconds since the epoch
Same as :py:func:`os.path.getmtime()`
"""
func = use_sudo and run_as_root or self.run
with self.s... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.