Search is not available for this dataset
text stringlengths 75 104k |
|---|
def createFromSource(cls, vs, name, registry):
''' returns a registry component for anything that's a valid package
name (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that).
'''
# we deliberately allow only lowerc... |
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:
... |
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
'''
... |
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... |
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) |
def remoteComponentFor(name, version_required, registry='modules'):
''' Return a RemoteComponent sublclass for the specified component name and
source url (or version specification)
Raises an exception if any arguments are invalid.
'''
try:
vs = sourceparse.parseSourceURL(version_re... |
def satisfyVersionFromSearchPaths(name, version_required, search_paths, update=False, type='module', inherit_shrinkwrap=None):
''' returns a Component/Target for the specified version, if found in the
list of search paths. If `update' is True, then also check for newer
versions of the found componen... |
def satisfyVersionByInstalling(name, version_required, working_directory, type='module', inherit_shrinkwrap=None):
''' installs and returns a Component/Target for the specified name+version
requirement, into a subdirectory of `working_directory'
'''
v = latestSuitableVersion(name, version_required, ... |
def _satisfyVersionByInstallingVersion(name, version_required, working_directory, version, type='module', inherit_shrinkwrap=None):
''' installs and returns a Component/Target for the specified version requirement into
'working_directory' using the provided remote version object.
This function is no... |
def satisfyVersion(
name,
version_required,
available,
search_paths,
working_directory,
update_installed=None,
type='module', # or 'target'
inherit_shrinkwrap=None
):
''' returns a Component/Target for the specified version (either to an already
... |
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 ... |
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 ... |
def origin(self):
''' Read the .yotta_origin.json file (if present), and return the value
of the 'url' property '''
if self.origin_info is None:
self.origin_info = {}
try:
self.origin_info = ordered_json.load(os.path.join(self.path, Origin_Info_Fname))... |
def outdated(self):
''' Return a truthy object if a newer suitable version is available,
otherwise return None.
(in fact the object returned is a ComponentVersion that can be used
to get the newer version)
'''
if self.latest_suitable_version and self.latest_s... |
def commitVCS(self, tag=None):
''' Commit the current working directory state (or do nothing if the
working directory is not version controlled)
'''
if not self.vcs:
return
self.vcs.commit(message='version %s' % tag, tag=tag) |
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... |
def writeDescription(self):
''' Write the current (possibly modified) component description to a
package description file in the component directory.
'''
ordered_json.dump(os.path.join(self.path, self.description_filename), self.description)
if self.vcs:
self.vcs.... |
def generateTarball(self, file_object):
''' Write a tarball of the current component/target to the file object
"file_object", which must already be open for writing at position 0
'''
archive_name = '%s-%s' % (self.getName(), self.getVersion())
def filterArchive(tarinfo):
... |
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... |
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... |
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.
'''
... |
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 ... |
def _truthyConfValue(v):
''' Determine yotta-config truthiness. In yotta config land truthiness is
different to python or json truthiness (in order to map nicely only
preprocessor and CMake definediness):
json -> python -> truthy/falsey
false -> False -> Falsey
... |
def getDependencySpecs(self, target=None):
''' Returns [DependencySpec]
These are returned in the order that they are listed in the
component description file: this is so that dependency resolution
proceeds in a predictable way.
'''
deps = []
def spe... |
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', {}).... |
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... |
def getDependencies(self,
available_components = None,
search_dirs = None,
target = None,
available_only = False,
test = False,
warnings = True
):
''' Returns {component_name:component}
'''
... |
def __getDependenciesWithProvider(self,
available_components = None,
search_dirs = None,
target = None,
update_installed = False,
provider = None,
... |
def __getDependenciesRecursiveWithProvider(self,
available_components = None,
search_dirs = None,
target = None,
traverse_links = False,
... |
def getDependenciesRecursive(self,
available_components = None,
processed = None,
search_dirs = None,
target = None,
available_only = False,
test = False
... |
def satisfyDependenciesRecursive(
self,
available_components = None,
search_dirs = None,
update_installed = False,
traverse_links = False,
target = None,
test = False
... |
def satisfyTarget(self, target_name_and_version, update_installed=False, additional_config=None, install_missing=True):
''' Ensure that the specified target name (and optionally version,
github ref or URL) is installed in the targets directory of the
current component
return... |
def getTarget(self, target_name_and_version, additional_config=None):
''' Return a derived target object representing the selected target: if
the target is not installed, or is invalid then the returned object
will test false in a boolean context.
Returns derived_target
... |
def getBinaries(self):
''' Return a dictionary of binaries to compile: {"dirname":"exename"},
this is used when automatically generating CMakeLists
Note that currently modules may define only a single executable
binary or library to be built by the automatic build system, by... |
def getLibs(self, explicit_only=False):
''' Return a dictionary of libraries to compile: {"dirname":"libname"},
this is used when automatically generating CMakeLists.
If explicit_only is not set, then in the absence of both 'lib' and
'bin' sections in the module.json file, t... |
def licenses(self):
''' Return a list of licenses that apply to this module. (Strings,
which may be SPDX identifiers)
'''
if 'license' in self.description:
return [self.description['license']]
else:
return [x['type'] for x in self.description['licenses... |
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:
... |
def getExtraSysIncludes(self):
''' Some components (e.g. libc) must export directories of header files
into the system include search path. They do this by adding a
'extraSysIncludes' : [ array of directories ] field in their
package description. This function returns the lis... |
def checkDependenciesForShrinkwrap(dependency_list):
''' return a list of errors encountered (e.g. dependency missing or
specification not met
'''
# sourceparse, , parse version specifications, internall
from yotta.lib import sourceparse
errors = []
# first gather the available versions ... |
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... |
def commitVersion(self, spec):
''' return a GithubComponentVersion object for a specific commit if valid
'''
import re
commit_match = re.match('^[a-f0-9]{7,40}$', spec, re.I)
if commit_match:
return GitCloneVersion('', spec, self)
return None |
def createFromSource(cls, vs, name=None):
''' returns a git component for any git:// url, or None if this is not
a git component.
Normally version will be empty, unless the original url was of the
form 'git://...#version', which can be used to grab a particular
t... |
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, ... |
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[... |
def loadAdditionalConfig(config_path):
''' returns (error, config)
'''
error = None
config = {}
if not config_path:
return (error, config)
if os.path.isfile(config_path):
try:
config = ordered_json.load(config_path)
except Exception as e:
error = "... |
def getDerivedTarget(
target_name_and_version,
targets_path,
application_dir = None,
install_missing = True,
update_installed = False,
additional_config = None,
shrinkwrap = None
):
# access, , get compo... |
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.... |
def getScript(self, scriptname):
''' return the specified script if one exists (possibly inherited from
a base target)
'''
for t in self.hierarchy:
s = t.getScript(scriptname)
if s:
return s
return None |
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... |
def getToolchainFiles(self):
''' return a list of toolchain file paths in override order (starting
at the bottom/leaf of the hierarchy and ending at the base).
The list is returned in the order they should be included
(most-derived last).
'''
return reversed([... |
def getAdditionalIncludes(self):
''' Return the list of cmake files which are to be included by yotta in
every module built. The list is returned in the order they should
be included (most-derived last).
'''
return reversed([
os.path.join(t.path, include_file)... |
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... |
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... |
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 = []
... |
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... |
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... |
def debug(self, builddir, program):
''' Launch a debugger for the specified program. Uses the `debug`
script if specified by the target, falls back to the `debug` and
`debugServer` commands if not. `program` is inserted into the
$program variable in commands.
'''
... |
def which(program):
''' look for "program" in PATH (respecting PATHEXT), and return the path to
it, or None if it was not found
'''
# current directory / absolute paths:
if os.path.exists(program) and os.access(program, os.X_OK):
return program
# PATH:
for path in os.environ['PAT... |
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... |
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... |
def unpackFromCache(cache_key, to_directory):
''' If the specified cache key exists, unpack the tarball into the
specified directory, otherwise raise NotInCache (a KeyError subclass).
'''
if cache_key is None:
raise NotInCache('"None" is never in cache')
cache_key = _encodeCacheKey(cach... |
def _downloadToCache(stream, hashinfo={}, origin_info=dict()):
''' Download the specified stream to a temporary cache directory, and
returns a cache key that can be used to access/remove the file.
You should use either removeFromCache(cache_key) or _moveCachedFile to
move the downloaded file... |
def _moveCachedFile(from_key, to_key):
''' Move a file atomically within the cache: used to make cached files
available at known keys, so they can be used by other processes.
'''
cache_dir = folders.cacheDirectory()
from_path = os.path.join(cache_dir, from_key)
to_path = os.path.join(cache... |
def unpackTarballStream(stream, into_directory, hash={}, cache_key=None, origin_info=dict()):
''' Unpack a responses stream that contains a tarball into a directory. If
a hash is provided, then it will be used as a cache key (for future
requests you can try to retrieve the key value from the cache f... |
def parseSourceURL(source_url):
''' Parse the specified version source URL (or version spec), and return an
instance of VersionSource
'''
name, spec = _getNonRegistryRef(source_url)
if spec:
return spec
try:
url_is_spec = version.Spec(source_url)
except ValueError:
... |
def parseTargetNameAndSpec(target_name_and_spec):
''' Parse targetname[@versionspec] and return a tuple
(target_name_string, version_spec_string).
targetname[,versionspec] is also supported (this is how target names
and specifications are stored internally, and was the documented way of
... |
def parseModuleNameAndSpec(module_name_and_spec):
''' Parse modulename[@versionspec] and return a tuple
(module_name_string, version_spec_string).
Also accepts raw github version specs (Owner/reponame#whatever), as the
name can be deduced from these.
Note that the specification spl... |
def gfit(X, sigma, p=5, nbin=200, unif_fraction=0.1):
"""
Fit empirical Bayes prior in the hierarchical model [Efron2014]_.
.. math::
mu ~ G, X ~ N(mu, sigma^2)
Parameters
----------
X: ndarray
A 1D array of observations.
sigma: float
Noise estimate on X.
p: in... |
def gbayes(x0, g_est, sigma):
"""
Estimate Bayes posterior with Gaussian noise [Efron2014]_.
Parameters
----------
x0: ndarray
an observation
g_est: float
a prior density, as returned by gfit
sigma: int
noise estimate
Returns
-------
An array of the post... |
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... |
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... |
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... |
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
... |
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... |
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/
"""
... |
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.
"""
... |
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... |
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 ... |
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'... |
def _get_environ_handler(name, d):
"""
Dynamically creates a Fabric task for each configuration role.
"""
def func(site=None, **kwargs):
from fabric import state
# We can't auto-set default_site, because that break tasks that have
# to operate over multiple sites.
# If ... |
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... |
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:
... |
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... |
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... |
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... |
def runs_once(meth):
"""
A wrapper around Fabric's runs_once() to support our dryrun feature.
"""
from burlap.common import get_dryrun, runs_once_methods
if get_dryrun():
pass
else:
runs_once_methods.append(meth)
_runs_once(meth)
return meth |
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_... |
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... |
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 |
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', '... |
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
... |
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.
... |
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'):... |
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... |
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... |
def copy(self, source, destination, recursive=False, use_sudo=False):
"""
Copy a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else ''
func('/bin/cp {0}{1} {2}'.format(options, quote(source), quote(destination))) |
def move(self, source, destination, use_sudo=False):
"""
Move a file or directory
"""
func = use_sudo and run_as_root or self.run
func('/bin/mv {0} {1}'.format(quote(source), quote(destination))) |
def remove(self, path, recursive=False, use_sudo=False):
"""
Remove a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else ''
func('/bin/rm {0}{1}'.format(options, quote(path))) |
def require(self, path=None, contents=None, source=None, url=None, md5=None,
use_sudo=False, owner=None, group='', mode=None, verify_remote=True,
temp_dir='/tmp'):
"""
Require a file to exist and have specific contents and properties.
You can provide either:
- *conten... |
def check_for_change(self):
"""
Determines if a new release has been made.
"""
r = self.local_renderer
lm = self.last_manifest
last_fingerprint = lm.fingerprint
current_fingerprint = self.get_target_geckodriver_version_number()
self.vprint('last_fingerprin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.