_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q265100 | PointerCache.child_end_handler | validation | def child_end_handler(self,scache):
'''
_upgrade_breadth_info
update breadth, breadth_path, and add desc to desc_level
'''
desc = self.desc
desc_level = scache.desc_level
breadth = desc_level.__len__()
desc['breadth'] = breadth
desc['breadt... | python | {
"resource": ""
} |
q265101 | LatexCommand.parse | validation | def parse(self, source):
"""Parse command content from the LaTeX source.
Parameters
----------
source : `str`
The full source of the tex document.
Yields
------
parsed_command : `ParsedCommand`
Yields parsed commands instances for each oc... | python | {
"resource": ""
} |
q265102 | LatexCommand._parse_command | validation | def _parse_command(self, source, start_index):
"""Parse a single command.
Parameters
----------
source : `str`
The full source of the tex document.
start_index : `int`
Character index in ``source`` where the command begins.
Returns
------... | python | {
"resource": ""
} |
q265103 | LatexCommand._parse_whitespace_argument | validation | def _parse_whitespace_argument(source, name):
r"""Attempt to parse a single token on the first line of this source.
This method is used for parsing whitespace-delimited arguments, like
``\input file``. The source should ideally contain `` file`` along
with a newline character.
... | python | {
"resource": ""
} |
q265104 | TMDDEventConverter.list_from_document | validation | def list_from_document(cls, doc):
"""Returns a list of TMDDEventConverter elements.
doc is an XML Element containing one or more <FEU> events
"""
objs = []
for feu in doc.xpath('//FEU'):
detail_els = feu.xpath('event-element-details/event-element-detail')
... | python | {
"resource": ""
} |
q265105 | clone | validation | def clone(src, dst_path, skip_globals, skip_dimensions, skip_variables):
"""
Mostly ripped from nc3tonc4 in netCDF4-python.
Added ability to skip dimension and variables.
Removed all of the unpacking logic for shorts.
"""
if os.path.exists(dst_path):
os.unlink(dst_path)
... | python | {
"resource": ""
} |
q265106 | get_dataframe_from_variable | validation | def get_dataframe_from_variable(nc, data_var):
""" Returns a Pandas DataFrame of the data.
This always returns positive down depths
"""
time_var = nc.get_variables_by_attributes(standard_name='time')[0]
depth_vars = nc.get_variables_by_attributes(axis=lambda v: v is not None and v.lower() == 'z... | python | {
"resource": ""
} |
q265107 | GitHubQuery.load | validation | def load(cls, query_name):
"""Load a pre-made query.
These queries are distributed with lsstprojectmeta. See
:file:`lsstrojectmeta/data/githubv4/README.rst` inside the
package repository for details on available queries.
Parameters
----------
query_name : `str`
... | python | {
"resource": ""
} |
q265108 | read_git_commit_timestamp_for_file | validation | def read_git_commit_timestamp_for_file(filepath, repo_path=None, repo=None):
"""Obtain the timestamp for the most recent commit to a given file in a
Git repository.
Parameters
----------
filepath : `str`
Absolute or repository-relative path for a file.
repo_path : `str`, optional
... | python | {
"resource": ""
} |
q265109 | get_content_commit_date | validation | def get_content_commit_date(extensions, acceptance_callback=None,
root_dir='.'):
"""Get the datetime for the most recent commit to a project that
affected certain types of content.
Parameters
----------
extensions : sequence of 'str'
Extensions of files to consid... | python | {
"resource": ""
} |
q265110 | _iter_filepaths_with_extension | validation | def _iter_filepaths_with_extension(extname, root_dir='.'):
"""Iterative over relative filepaths of files in a directory, and
sub-directories, with the given extension.
Parameters
----------
extname : `str`
Extension name (such as 'txt' or 'rst'). Extension comparison is
case sensiti... | python | {
"resource": ""
} |
q265111 | EnhancedDataset.get_variables_by_attributes | validation | def get_variables_by_attributes(self, **kwargs):
""" Returns variables that match specific conditions.
* Can pass in key=value parameters and variables are returned that
contain all of the matches. For example,
>>> # Get variables with x-axis attribute.
>>> vs = nc.get_variabl... | python | {
"resource": ""
} |
q265112 | EnhancedDataset.json_attributes | validation | def json_attributes(self, vfuncs=None):
"""
vfuncs can be any callable that accepts a single argument, the
Variable object, and returns a dictionary of new attributes to
set. These will overwrite existing attributes
"""
vfuncs = vfuncs or []
js = {'global': {}}
... | python | {
"resource": ""
} |
q265113 | ensure_pandoc | validation | def ensure_pandoc(func):
"""Decorate a function that uses pypandoc to ensure that pandoc is
installed if necessary.
"""
logger = logging.getLogger(__name__)
@functools.wraps(func)
def _install_and_run(*args, **kwargs):
try:
# First try to run pypandoc function
re... | python | {
"resource": ""
} |
q265114 | convert_text | validation | def convert_text(content, from_fmt, to_fmt, deparagraph=False, mathjax=False,
smart=True, extra_args=None):
"""Convert text from one markup format to another using pandoc.
This function is a thin wrapper around `pypandoc.convert_text`.
Parameters
----------
content : `str`
... | python | {
"resource": ""
} |
q265115 | convert_lsstdoc_tex | validation | def convert_lsstdoc_tex(
content, to_fmt, deparagraph=False, mathjax=False,
smart=True, extra_args=None):
"""Convert lsstdoc-class LaTeX to another markup format.
This function is a thin wrapper around `convert_text` that automatically
includes common lsstdoc LaTeX macros.
Parameters
... | python | {
"resource": ""
} |
q265116 | decode_jsonld | validation | def decode_jsonld(jsonld_text):
"""Decode a JSON-LD dataset, including decoding datetime
strings into `datetime.datetime` objects.
Parameters
----------
encoded_dataset : `str`
The JSON-LD dataset encoded as a string.
Returns
-------
jsonld_dataset : `dict`
A JSON-LD da... | python | {
"resource": ""
} |
q265117 | JsonLdEncoder.default | validation | def default(self, obj):
"""Encode values as JSON strings.
This method overrides the default implementation from
`json.JSONEncoder`.
"""
if isinstance(obj, datetime.datetime):
return self._encode_datetime(obj)
# Fallback to the default encoding
return... | python | {
"resource": ""
} |
q265118 | Git.find_repos | validation | def find_repos(self, depth=10):
'''Get all git repositories within this environment'''
repos = []
for root, subdirs, files in walk_dn(self.root, depth=depth):
if 'modules' in root:
continue
if '.git' in subdirs:
repos.append(root)
... | python | {
"resource": ""
} |
q265119 | Pip.install | validation | def install(self, package):
'''Install a python package using pip'''
logger.debug('Installing ' + package)
shell.run(self.pip_path, 'install', package) | python | {
"resource": ""
} |
q265120 | Pip.upgrade | validation | def upgrade(self, package):
'''Update a python package using pip'''
logger.debug('Upgrading ' + package)
shell.run(self.pip_path, 'install', '--upgrade', '--no-deps', package)
shell.run(self.pip_path, 'install', package) | python | {
"resource": ""
} |
q265121 | df_quantile | validation | def df_quantile(df, nb=100):
"""Returns the nb quantiles for datas in a dataframe
"""
quantiles = np.linspace(0, 1., nb)
res = pd.DataFrame()
for q in quantiles:
res = res.append(df.quantile(q), ignore_index=True)
return res | python | {
"resource": ""
} |
q265122 | rmse | validation | def rmse(a, b):
"""Returns the root mean square error betwwen a and b
"""
return np.sqrt(np.square(a - b).mean()) | python | {
"resource": ""
} |
q265123 | nmse | validation | def nmse(a, b):
"""Returns the normalized mean square error of a and b
"""
return np.square(a - b).mean() / (a.mean() * b.mean()) | python | {
"resource": ""
} |
q265124 | mfbe | validation | def mfbe(a, b):
"""Returns the mean fractionalized bias error
"""
return 2 * bias(a, b) / (a.mean() + b.mean()) | python | {
"resource": ""
} |
q265125 | foex | validation | def foex(a, b):
"""Returns the factor of exceedance
"""
return (np.sum(a > b, dtype=float) / len(a) - 0.5) * 100 | python | {
"resource": ""
} |
q265126 | correlation | validation | def correlation(a, b):
"""Computes the correlation between a and b, says the Pearson's correlation
coefficient R
"""
diff1 = a - a.mean()
diff2 = b - b.mean()
return (diff1 * diff2).mean() / (np.sqrt(np.square(diff1).mean() * np.square(diff2).mean())) | python | {
"resource": ""
} |
q265127 | gmb | validation | def gmb(a, b):
"""Geometric mean bias
"""
return np.exp(np.log(a).mean() - np.log(b).mean()) | python | {
"resource": ""
} |
q265128 | gmv | validation | def gmv(a, b):
"""Geometric mean variance
"""
return np.exp(np.square(np.log(a) - np.log(b)).mean()) | python | {
"resource": ""
} |
q265129 | fmt | validation | def fmt(a, b):
"""Figure of merit in time
"""
return 100 * np.min([a, b], axis=0).sum() / np.max([a, b], axis=0).sum() | python | {
"resource": ""
} |
q265130 | fullStats | validation | def fullStats(a, b):
"""Performs several stats on a against b, typically a is the predictions
array, and b the observations array
Returns:
A dataFrame of stat name, stat description, result
"""
stats = [
['bias', 'Bias', bias(a, b)],
['stderr', 'Standard Deviation Error', s... | python | {
"resource": ""
} |
q265131 | VirtualEnvironment.site_path | validation | def site_path(self):
'''Path to environments site-packages'''
if platform == 'win':
return unipath(self.path, 'Lib', 'site-packages')
py_ver = 'python{0}'.format(sys.version[:3])
return unipath(self.path, 'lib', py_ver, 'site-packages') | python | {
"resource": ""
} |
q265132 | VirtualEnvironment._pre_activate | validation | def _pre_activate(self):
'''
Prior to activating, store everything necessary to deactivate this
environment.
'''
if 'CPENV_CLEAN_ENV' not in os.environ:
if platform == 'win':
os.environ['PROMPT'] = '$P$G'
else:
os.environ['... | python | {
"resource": ""
} |
q265133 | VirtualEnvironment._activate | validation | def _activate(self):
'''
Do some serious mangling to the current python environment...
This is necessary to activate an environment via python.
'''
old_syspath = set(sys.path)
site.addsitedir(self.site_path)
site.addsitedir(self.bin_path)
new_syspaths = s... | python | {
"resource": ""
} |
q265134 | VirtualEnvironment.remove | validation | def remove(self):
'''
Remove this environment
'''
self.run_hook('preremove')
utils.rmtree(self.path)
self.run_hook('postremove') | python | {
"resource": ""
} |
q265135 | Module.command | validation | def command(self):
'''Command used to launch this application module'''
cmd = self.config.get('command', None)
if cmd is None:
return
cmd = cmd[platform]
return cmd['path'], cmd['args'] | python | {
"resource": ""
} |
q265136 | create | validation | def create(name_or_path=None, config=None):
'''Create a virtual environment. You can pass either the name of a new
environment to create in your CPENV_HOME directory OR specify a full path
to create an environment outisde your CPENV_HOME.
Create an environment in CPENV_HOME::
>>> cpenv.create(... | python | {
"resource": ""
} |
q265137 | remove | validation | def remove(name_or_path):
'''Remove an environment or module
:param name_or_path: name or path to environment or module
'''
r = resolve(name_or_path)
r.resolved[0].remove()
EnvironmentCache.discard(r.resolved[0])
EnvironmentCache.save() | python | {
"resource": ""
} |
q265138 | launch | validation | def launch(module_name, *args, **kwargs):
'''Activates and launches a module
:param module_name: name of module to launch
'''
r = resolve(module_name)
r.activate()
mod = r.resolved[0]
mod.launch(*args, **kwargs) | python | {
"resource": ""
} |
q265139 | deactivate | validation | def deactivate():
'''Deactivates an environment by restoring all env vars to a clean state
stored prior to activating environments
'''
if 'CPENV_ACTIVE' not in os.environ or 'CPENV_CLEAN_ENV' not in os.environ:
raise EnvironmentError('Can not deactivate environment...')
utils.restore_env_f... | python | {
"resource": ""
} |
q265140 | get_modules | validation | def get_modules():
'''Returns a list of available modules.'''
modules = set()
cwd = os.getcwd()
for d in os.listdir(cwd):
if d == 'module.yml':
modules.add(Module(cwd))
path = unipath(cwd, d)
if utils.is_module(path):
modules.add(Module(cwd))
modu... | python | {
"resource": ""
} |
q265141 | add_active_module | validation | def add_active_module(module):
'''Add a module to CPENV_ACTIVE_MODULES environment variable'''
modules = set(get_active_modules())
modules.add(module)
new_modules_path = os.pathsep.join([m.path for m in modules])
os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path) | python | {
"resource": ""
} |
q265142 | rem_active_module | validation | def rem_active_module(module):
'''Remove a module from CPENV_ACTIVE_MODULES environment variable'''
modules = set(get_active_modules())
modules.discard(module)
new_modules_path = os.pathsep.join([m.path for m in modules])
os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path) | python | {
"resource": ""
} |
q265143 | format_objects | validation | def format_objects(objects, children=False, columns=None, header=True):
'''Format a list of environments and modules for terminal output'''
columns = columns or ('NAME', 'TYPE', 'PATH')
objects = sorted(objects, key=_type_and_name)
data = []
for obj in objects:
if isinstance(obj, cpenv.Virt... | python | {
"resource": ""
} |
q265144 | info | validation | def info():
'''Show context info'''
env = cpenv.get_active_env()
modules = []
if env:
modules = env.get_modules()
active_modules = cpenv.get_active_modules()
if not env and not modules and not active_modules:
click.echo('\nNo active modules...')
return
click.echo(b... | python | {
"resource": ""
} |
q265145 | activate | validation | def activate(paths, skip_local, skip_shared):
'''Activate an environment'''
if not paths:
ctx = click.get_current_context()
if cpenv.get_active_env():
ctx.invoke(info)
return
click.echo(ctx.get_help())
examples = (
'\nExamples: \n'
... | python | {
"resource": ""
} |
q265146 | create | validation | def create(name_or_path, config):
'''Create a new environment.'''
if not name_or_path:
ctx = click.get_current_context()
click.echo(ctx.get_help())
examples = (
'\nExamples:\n'
' cpenv create my_env\n'
' cpenv create ./relative/path/to/my_env\n'... | python | {
"resource": ""
} |
q265147 | remove | validation | def remove(name_or_path):
'''Remove an environment'''
click.echo()
try:
r = cpenv.resolve(name_or_path)
except cpenv.ResolveError as e:
click.echo(e)
return
obj = r.resolved[0]
if not isinstance(obj, cpenv.VirtualEnvironment):
click.echo('{} is a module. Use `cp... | python | {
"resource": ""
} |
q265148 | add | validation | def add(path):
'''Add an environment to the cache. Allows you to activate the environment
by name instead of by full path'''
click.echo('\nAdding {} to cache......'.format(path), nl=False)
try:
r = cpenv.resolve(path)
except Exception as e:
click.echo(bold_red('FAILED'))
cli... | python | {
"resource": ""
} |
q265149 | remove | validation | def remove(path):
'''Remove a cached environment. Removed paths will no longer be able to
be activated by name'''
r = cpenv.resolve(path)
if isinstance(r.resolved[0], cpenv.VirtualEnvironment):
EnvironmentCache.discard(r.resolved[0])
EnvironmentCache.save() | python | {
"resource": ""
} |
q265150 | create | validation | def create(name_or_path, config):
'''Create a new template module.
You can also specify a filesystem path like "./modules/new_module"
'''
click.echo('Creating module {}...'.format(name_or_path), nl=False)
try:
module = cpenv.create_module(name_or_path, config)
except Exception as e:
... | python | {
"resource": ""
} |
q265151 | add | validation | def add(name, path, branch, type):
'''Add a module to an environment. PATH can be a git repository path or
a filesystem path. '''
if not name and not path:
ctx = click.get_current_context()
click.echo(ctx.get_help())
examples = (
'\nExamples:\n'
' cpenv mo... | python | {
"resource": ""
} |
q265152 | localize | validation | def localize(name):
'''Copy a global module to the active environment.'''
env = cpenv.get_active_env()
if not env:
click.echo('You need to activate an environment first.')
return
try:
r = cpenv.resolve(name)
except cpenv.ResolveError as e:
click.echo('\n' + str(e))
... | python | {
"resource": ""
} |
q265153 | path_resolver | validation | def path_resolver(resolver, path):
'''Resolves VirtualEnvironments with a relative or absolute path'''
path = unipath(path)
if is_environment(path):
return VirtualEnvironment(path)
raise ResolveError | python | {
"resource": ""
} |
q265154 | home_resolver | validation | def home_resolver(resolver, path):
'''Resolves VirtualEnvironments in CPENV_HOME'''
from .api import get_home_path
path = unipath(get_home_path(), path)
if is_environment(path):
return VirtualEnvironment(path)
raise ResolveError | python | {
"resource": ""
} |
q265155 | cache_resolver | validation | def cache_resolver(resolver, path):
'''Resolves VirtualEnvironments in EnvironmentCache'''
env = resolver.cache.find(path)
if env:
return env
raise ResolveError | python | {
"resource": ""
} |
q265156 | module_resolver | validation | def module_resolver(resolver, path):
'''Resolves module in previously resolved environment.'''
if resolver.resolved:
if isinstance(resolver.resolved[0], VirtualEnvironment):
env = resolver.resolved[0]
mod = env.get_module(path)
if mod:
return mod
... | python | {
"resource": ""
} |
q265157 | active_env_module_resolver | validation | def active_env_module_resolver(resolver, path):
'''Resolves modules in currently active environment.'''
from .api import get_active_env
env = get_active_env()
if not env:
raise ResolveError
mod = env.get_module(path)
if not mod:
raise ResolveError
return mod | python | {
"resource": ""
} |
q265158 | redirect_resolver | validation | def redirect_resolver(resolver, path):
'''Resolves environment from .cpenv file...recursively walks up the tree
in attempt to find a .cpenv file'''
if not os.path.exists(path):
raise ResolveError
if os.path.isfile(path):
path = os.path.dirname(path)
for root, _, _ in walk_up(path)... | python | {
"resource": ""
} |
q265159 | transpose | validation | def transpose(a, axes=None):
"""Returns a view of the array with axes transposed.
For a 1-D array, this has no effect.
For a 2-D array, this is the usual matrix transpose.
For an n-D array, if axes are given, their order indicates how the
axes are permuted
Args:
a (array_like): Input arr... | python | {
"resource": ""
} |
q265160 | rollaxis | validation | def rollaxis(a, axis, start=0):
"""Roll the specified axis backwards, until it lies in a given position.
Args:
a (array_like): Input array.
axis (int): The axis to roll backwards. The positions of the other axes
do not change relative to one another.
start (int, optional): The axis ... | python | {
"resource": ""
} |
q265161 | expand_dims | validation | def expand_dims(a, axis):
"""Insert a new axis, corresponding to a given position in the array shape
Args:
a (array_like): Input array.
axis (int): Position (amongst axes) where new axis is to be inserted.
"""
if hasattr(a, 'expand_dims') and hasattr(type(a), '__array_interface__'):
... | python | {
"resource": ""
} |
q265162 | concatenate | validation | def concatenate(tup, axis=0):
"""Join a sequence of arrays together.
Will aim to join `ndarray`, `RemoteArray`, and `DistArray` without moving
their data, if they happen to be on different engines.
Args:
tup (sequence of array_like): Arrays to be concatenated. They must have
the same sh... | python | {
"resource": ""
} |
q265163 | _broadcast_shape | validation | def _broadcast_shape(*args):
"""Return the shape that would result from broadcasting the inputs"""
#TODO: currently incorrect result if a Sequence is provided as an input
shapes = [a.shape if hasattr(type(a), '__array_interface__')
else () for a in args]
ndim = max(len(sh) for sh in shapes... | python | {
"resource": ""
} |
q265164 | mean | validation | def mean(a, axis=None, dtype=None, out=None, keepdims=False):
"""
Compute the arithmetic mean along the specified axis.
Returns the average of the array elements. The average is taken over
the flattened array by default, otherwise over the specified axis.
`float64` intermediate and return values a... | python | {
"resource": ""
} |
q265165 | DistArray._valid_distaxis | validation | def _valid_distaxis(shapes, ax):
"""`ax` is a valid candidate for a distributed axis if the given
subarray shapes are all the same when ignoring axis `ax`"""
compare_shapes = np.vstack(shapes)
if ax < compare_shapes.shape[1]:
compare_shapes[:, ax] = -1
return np.count... | python | {
"resource": ""
} |
q265166 | run | validation | def run(*args, **kwargs):
'''Returns True if successful, False if failure'''
kwargs.setdefault('env', os.environ)
kwargs.setdefault('shell', True)
try:
subprocess.check_call(' '.join(args), **kwargs)
return True
except subprocess.CalledProcessError:
logger.debug('Error runn... | python | {
"resource": ""
} |
q265167 | cmd | validation | def cmd():
'''Return a command to launch a subshell'''
if platform == 'win':
return ['cmd.exe', '/K']
elif platform == 'linux':
ppid = os.getppid()
ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid)
try:
with open(ppid_cmdline_file) as f:
cmd =... | python | {
"resource": ""
} |
q265168 | prompt | validation | def prompt(prefix=None, colored=True):
'''Generate a prompt with a given prefix
linux/osx: [prefix] user@host cwd $
win: [prefix] cwd:
'''
if platform == 'win':
return '[{0}] $P$G'.format(prefix)
else:
if colored:
return (
'[{0}] ' # White pre... | python | {
"resource": ""
} |
q265169 | launch | validation | def launch(prompt_prefix=None):
'''Launch a subshell'''
if prompt_prefix:
os.environ['PROMPT'] = prompt(prompt_prefix)
subprocess.call(cmd(), env=os.environ.data) | python | {
"resource": ""
} |
q265170 | FileModificationMonitor.add_file | validation | def add_file(self, file, **kwargs):
"""Append a file to file repository.
For file monitoring, monitor instance needs file.
Please put the name of file to `file` argument.
:param file: the name of file you want monitor.
"""
if os.access(file, os.F_OK):
if ... | python | {
"resource": ""
} |
q265171 | FileModificationMonitor.add_files | validation | def add_files(self, filelist, **kwargs):
"""Append files to file repository.
ModificationMonitor can append files to repository using this.
Please put the list of file names to `filelist` argument.
:param filelist: the list of file nmaes
"""
# check filelist is... | python | {
"resource": ""
} |
q265172 | FileModificationMonitor.monitor | validation | def monitor(self, sleep=5):
"""Run file modification monitor.
The monitor can catch file modification using timestamp and file body.
Monitor has timestamp data and file body data. And insert timestamp
data and file body data before into while roop. In while roop, monitor
get ... | python | {
"resource": ""
} |
q265173 | RestPoints.status_job | validation | def status_job(self, fn=None, name=None, timeout=3):
"""Decorator that invokes `add_status_job`.
::
@app.status_job
def postgresql():
# query/ping postgres
@app.status_job(name="Active Directory")
def active_directory():
... | python | {
"resource": ""
} |
q265174 | _pipepager | validation | def _pipepager(text, cmd, color):
"""Page through text by feeding it to another program. Invoking a
pager through this might support colors.
"""
import subprocess
env = dict(os.environ)
# If we're piping to less we might support colors under the
# condition that
cmd_detail = cmd.rsplit... | python | {
"resource": ""
} |
q265175 | profil_annuel | validation | def profil_annuel(df, func='mean'):
"""
Calcul du profil annuel
Paramètres:
df: DataFrame de données dont l'index est une série temporelle
(cf module xair par exemple)
func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...)
soit la fonction elle-même ... | python | {
"resource": ""
} |
q265176 | run_global_hook | validation | def run_global_hook(hook_name, *args):
'''Attempt to run a global hook by name with args'''
hook_finder = HookFinder(get_global_hook_path())
hook = hook_finder(hook_name)
if hook:
hook.run(*args) | python | {
"resource": ""
} |
q265177 | moyennes_glissantes | validation | def moyennes_glissantes(df, sur=8, rep=0.75):
"""
Calcule de moyennes glissantes
Paramètres:
df: DataFrame de mesures sur lequel appliqué le calcul
sur: (int, par défaut 8) Nombre d'observations sur lequel s'appuiera le
calcul
rep: (float, défaut 0.75) Taux de réprésentativité en dessous du... | python | {
"resource": ""
} |
q265178 | aot40_vegetation | validation | def aot40_vegetation(df, nb_an):
"""
Calcul de l'AOT40 du 1er mai au 31 juillet
*AOT40 : AOT 40 ( exprimé en micro g/m³ par heure ) signifie la somme des
différences entre les concentrations horaires supérieures à 40 parties par
milliard ( 40 ppb soit 80 micro g/m³ ), durant une période donnée en
... | python | {
"resource": ""
} |
q265179 | EnvironmentCache.validate | validation | def validate(self):
'''Validate all the entries in the environment cache.'''
for env in list(self):
if not env.exists:
self.remove(env) | python | {
"resource": ""
} |
q265180 | EnvironmentCache.load | validation | def load(self):
'''Load the environment cache from disk.'''
if not os.path.exists(self.path):
return
with open(self.path, 'r') as f:
env_data = yaml.load(f.read())
if env_data:
for env in env_data:
self.add(VirtualEnvironment(env['ro... | python | {
"resource": ""
} |
q265181 | EnvironmentCache.save | validation | def save(self):
'''Save the environment cache to disk.'''
env_data = [dict(name=env.name, root=env.path) for env in self]
encode = yaml.safe_dump(env_data, default_flow_style=False)
with open(self.path, 'w') as f:
f.write(encode) | python | {
"resource": ""
} |
q265182 | prompt | validation | def prompt(text, default=None, hide_input=False,
confirmation_prompt=False, type=None,
value_proc=None, prompt_suffix=': ',
show_default=True, err=False):
"""Prompts a user for input. This is a convenience function that can
be used to prompt a user for input later.
If the ... | python | {
"resource": ""
} |
q265183 | echo_via_pager | validation | def echo_via_pager(text, color=None):
"""This function takes a text and shows it via an environment specific
pager on stdout.
.. versionchanged:: 3.0
Added the `color` flag.
:param text: the text to page.
:param color: controls if the pager supports ANSI colors or not. The
... | python | {
"resource": ""
} |
q265184 | setup_engines | validation | def setup_engines(client=None):
"""Prepare all iPython engines for distributed object processing.
Args:
client (ipyparallel.Client, optional): If None, will create a client
using the default ipyparallel profile.
"""
if not client:
try:
client = ipyparallel.Client()
... | python | {
"resource": ""
} |
q265185 | gather | validation | def gather(obj):
"""Retrieve objects that have been distributed, making them local again"""
if hasattr(obj, '__distob_gather__'):
return obj.__distob_gather__()
elif (isinstance(obj, collections.Sequence) and
not isinstance(obj, string_types)):
return [gather(subobj) for subobj ... | python | {
"resource": ""
} |
q265186 | apply | validation | def apply(f, obj, *args, **kwargs):
"""Apply a function in parallel to each element of the input"""
return vectorize(f)(obj, *args, **kwargs) | python | {
"resource": ""
} |
q265187 | ObjectHub.register_proxy_type | validation | def register_proxy_type(cls, real_type, proxy_type):
"""Configure engines so that remote methods returning values of type
`real_type` will instead return by proxy, as type `proxy_type`
"""
if distob.engine is None:
cls._initial_proxy_types[real_type] = proxy_type
elif... | python | {
"resource": ""
} |
q265188 | is_git_repo | validation | def is_git_repo(path):
'''Returns True if path is a git repository.'''
if path.startswith('git@') or path.startswith('https://'):
return True
if os.path.exists(unipath(path, '.git')):
return True
return False | python | {
"resource": ""
} |
q265189 | is_home_environment | validation | def is_home_environment(path):
'''Returns True if path is in CPENV_HOME'''
home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv'))
path = unipath(path)
return path.startswith(home) | python | {
"resource": ""
} |
q265190 | is_redirecting | validation | def is_redirecting(path):
'''Returns True if path contains a .cpenv file'''
candidate = unipath(path, '.cpenv')
return os.path.exists(candidate) and os.path.isfile(candidate) | python | {
"resource": ""
} |
q265191 | redirect_to_env_paths | validation | def redirect_to_env_paths(path):
'''Get environment path from redirect file'''
with open(path, 'r') as f:
redirected = f.read()
return shlex.split(redirected) | python | {
"resource": ""
} |
q265192 | expandpath | validation | def expandpath(path):
'''Returns an absolute expanded path'''
return os.path.abspath(os.path.expandvars(os.path.expanduser(path))) | python | {
"resource": ""
} |
q265193 | unipath | validation | def unipath(*paths):
'''Like os.path.join but also expands and normalizes path parts.'''
return os.path.normpath(expandpath(os.path.join(*paths))) | python | {
"resource": ""
} |
q265194 | binpath | validation | def binpath(*paths):
'''Like os.path.join but acts relative to this packages bin path.'''
package_root = os.path.dirname(__file__)
return os.path.normpath(os.path.join(package_root, 'bin', *paths)) | python | {
"resource": ""
} |
q265195 | ensure_path_exists | validation | def ensure_path_exists(path, *args):
'''Like os.makedirs but keeps quiet if path already exists'''
if os.path.exists(path):
return
os.makedirs(path, *args) | python | {
"resource": ""
} |
q265196 | walk_dn | validation | def walk_dn(start_dir, depth=10):
'''
Walk down a directory tree. Same as os.walk but allows for a depth limit
via depth argument
'''
start_depth = len(os.path.split(start_dir))
end_depth = start_depth + depth
for root, subdirs, files in os.walk(start_dir):
yield root, subdirs, fil... | python | {
"resource": ""
} |
q265197 | walk_up | validation | def walk_up(start_dir, depth=20):
'''
Walk up a directory tree
'''
root = start_dir
for i in xrange(depth):
contents = os.listdir(root)
subdirs, files = [], []
for f in contents:
if os.path.isdir(os.path.join(root, f)):
subdirs.append(f)
... | python | {
"resource": ""
} |
q265198 | preprocess_dict | validation | def preprocess_dict(d):
'''
Preprocess a dict to be used as environment variables.
:param d: dict to be processed
'''
out_env = {}
for k, v in d.items():
if not type(v) in PREPROCESSORS:
raise KeyError('Invalid type in dict: {}'.format(type(v)))
out_env[k] = PREPR... | python | {
"resource": ""
} |
q265199 | _join_seq | validation | def _join_seq(d, k, v):
'''Add a sequence value to env dict'''
if k not in d:
d[k] = list(v)
elif isinstance(d[k], list):
for item in v:
if item not in d[k]:
d[k].insert(0, item)
elif isinstance(d[k], string_types):
v.append(d[k])
d[k] = v | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.