_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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
| 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 occurence of the command
in the | 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
-------
parsed_command : `ParsedCommand`
The parsed command from the source at the given index.
"""
parsed_elements = []
# Index of the parser in the source
running_index = start_index
for element in self.elements:
opening_bracket = element['bracket']
closing_bracket = self._brackets[opening_bracket]
# Find the opening bracket.
element_start = None
element_end = None
for i, c in enumerate(source[running_index:], start=running_index):
if c == element['bracket']:
element_start = i
break
elif c == '\n':
# No starting bracket on the line.
if element['required'] is True:
# Try to parse a single single-word token after the
# command, like '\input file'
content = self._parse_whitespace_argument(
source[running_index:],
self.name)
return ParsedCommand(
self.name,
[{'index': element['index'],
'name': element['name'],
'content': content.strip()}],
start_index,
| 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.
>>> source = 'Line 1\n' r'\input test.tex' '\nLine 2'
>>> LatexCommand._parse_whitespace_argument(source, 'input')
'test.tex'
Bracket delimited arguments (``\input{test.tex}``) are handled in
the normal logic of `_parse_command`.
| 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)
dst = netCDF4.Dataset(dst_path, 'w')
# Global attributes
for attname in src.ncattrs():
if attname not in skip_globals:
setattr(dst, attname, getattr(src, attname))
# Dimensions
unlimdim = None
unlimdimname = False
for dimname, dim in src.dimensions.items():
# Skip what we need to
if dimname in skip_dimensions:
continue
if dim.isunlimited():
unlimdim = dim
unlimdimname = dimname
dst.createDimension(dimname, None)
else:
dst.createDimension(dimname, len(dim))
# Variables
for varname, ncvar in src.variables.items():
# Skip what we need to
if varname in skip_variables:
continue
hasunlimdim = False
if unlimdimname and unlimdimname in ncvar.dimensions:
hasunlimdim = True
filler = None
if hasattr(ncvar, '_FillValue'):
filler = ncvar._FillValue
if ncvar.chunking == "contiguous":
var = dst.createVariable(varname, ncvar.dtype, ncvar.dimensions, fill_value=filler)
| 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')
depth_vars += nc.get_variables_by_attributes(standard_name=lambda v: v in ['height', 'depth' 'surface_altitude'], positive=lambda x: x is not None)
# Find the correct depth variable
depth_var = None
for d in depth_vars:
try:
if d._name in data_var.coordinates.split(" ") or d._name in data_var.dimensions:
depth_var = d
break
except AttributeError:
continue
times = netCDF4.num2date(time_var[:], units=time_var.units, calendar=getattr(time_var, 'calendar', 'standard'))
original_times_size = times.size
if depth_var is None and hasattr(data_var, 'sensor_depth'):
depth_type = get_type(data_var.sensor_depth)
depths = np.asarray([data_var.sensor_depth] * len(times)).flatten()
values = data_var[:].flatten()
elif depth_var is None:
depths = np.asarray([np.nan] * len(times)).flatten()
depth_type = get_type(depths)
values = data_var[:].flatten()
else:
depths = depth_var[:]
depth_type = get_type(depths)
if len(data_var.shape) > 1:
times = np.repeat(times, depths.size)
depths = np.tile(depths, original_times_size)
| 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`
Name of the query, such as ``'technote_repo'``.
Returns
-------
github_query : `GitHubQuery
A GitHub query or mutation object that you can pass to
`github_request` to execute the | 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
Path to the Git repository. Leave as `None` to use the current working
directory or if a ``repo`` argument is provided.
repo : `git.Repo`, optional
A `git.Repo` instance.
Returns
-------
commit_timestamp : `datetime.datetime`
The datetime of the most recent commit to the given file.
Raises
------
IOError
Raised if the ``filepath`` does not exist in the Git repository.
"""
logger = logging.getLogger(__name__)
if repo is None:
repo = git.repo.base.Repo(path=repo_path,
search_parent_directories=True)
repo_path = repo.working_tree_dir
head_commit = repo.head.commit
# filepath relative to the repo path
logger.debug('Using Git repo at %r', repo_path)
filepath = os.path.relpath(
os.path.abspath(filepath),
start=repo_path)
logger.debug('Repo-relative filepath is %r', filepath)
| 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 consider in getting the most recent commit
date. For example, ``('rst', 'svg', 'png')`` are content extensions
for a Sphinx project. **Extension comparision is case sensitive.** add
uppercase variants to match uppercase extensions.
acceptance_callback : callable
Callable function whose sole argument is a file path, and returns
`True` or `False` depending on whether the file's commit date should
be considered or not. This callback is only run on files that are
included by ``extensions``. Thus this callback is a way to exclude
specific files that would otherwise be included by their extension.
root_dir : 'str`, optional
Only content contained within this root directory is considered.
This directory must be, or be contained by, a Git repository. This is
the current working directory by default.
Returns
-------
commit_date : `datetime.datetime`
Datetime of the most recent content commit.
Raises
------
RuntimeError
Raised if no content files are found.
"""
logger = logging.getLogger(__name__)
def _null_callback(_):
return True
if acceptance_callback is None:
acceptance_callback = _null_callback
# Cache the repo object for each query
root_dir = os.path.abspath(root_dir)
repo = git.repo.base.Repo(path=root_dir, search_parent_directories=True)
# Iterate over all files with all file extensions, looking for the
# newest | 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 sensitive.
root_dir : 'str`, optional
Root directory. Current working directory by default.
Yields
------
filepath : `str`
File path, relative to ``root_dir``, with the given extension.
"""
# needed for comparison with os.path.splitext
if not extname.startswith('.'):
extname = '.' + extname
| 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_variables_by_attributes(axis='X')
>>> # Get variables with matching "standard_name" attribute.
>>> nc.get_variables_by_attributes(standard_name='northward_sea_water_velocity')
* Can pass in key=callable parameter and variables are returned if the
callable returns True. The callable should accept a single parameter,
the attribute value. None is given as the attribute value when the
attribute does not exist on the variable. For example,
>>> # Get Axis variables.
>>> vs = nc.get_variables_by_attributes(axis=lambda v: v in ['X', 'Y', 'Z', 'T'])
>>> # Get variables that don't have an "axis" attribute.
>>> vs = nc.get_variables_by_attributes(axis=lambda v: v is None)
>>> # Get variables that have a "grid_mapping" attribute.
>>> vs = nc.get_variables_by_attributes(grid_mapping=lambda v: v is not None)
"""
vs = []
has_value_flag = False
| 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': {}}
for k in self.ncattrs():
js['global'][k] = self.getncattr(k)
for varname, var in self.variables.items():
js[varname] = {}
for k in var.ncattrs():
z = var.getncattr(k)
try:
assert not np.isnan(z).all()
js[varname][k] = z
except AssertionError:
| 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
result = func(*args, **kwargs)
except OSError:
# Install pandoc and retry
message = "pandoc needed but not found. Now installing it for you."
logger.warning(message)
# This version of pandoc is known to be compatible with both
| 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`
Original content.
from_fmt : `str`
Format of the original ``content``. Format identifier must be one of
those known by Pandoc. See https://pandoc.org/MANUAL.html for details.
to_fmt : `str`
Output format for the content.
deparagraph : `bool`, optional
If `True`, then the
`lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is
used to remove paragraph (``<p>``, for example) tags around a single
paragraph of content. That filter does not affect content that
consists of multiple blocks (several paragraphs, or lists, for
example). Default is `False`.
For example, **without** this filter Pandoc will convert
the string ``"Title text"`` to ``"<p>Title text</p>"`` in HTML. The
paragraph tags aren't useful if you intend to wrap the converted
content in different tags, like ``<h1>``, using your own templating
system.
**With** this filter, Pandoc will convert the string ``"Title text"``
to ``"Title text"`` in HTML.
mathjax : `bool`, optional
If `True` then Pandoc will markup output content to work with MathJax.
Default is False.
smart : `bool`, optional
If `True` (default) then ascii characters will be converted to unicode
characters like smart quotes and em dashes. | 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
----------
content : `str`
Original content.
to_fmt : `str`
Output format for the content (see https://pandoc.org/MANUAL.html).
For example, 'html5'.
deparagraph : `bool`, optional
If `True`, then the
`lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is
used to remove paragraph (``<p>``, for example) tags around a single
paragraph of content. That filter does not affect content that
consists of multiple blocks (several paragraphs, or lists, for
example). Default is `False`.
For example, **without** this filter Pandoc will convert
the string ``"Title text"`` to ``"<p>Title text</p>"`` in HTML. The
paragraph tags aren't useful if you intend to wrap the converted
content in different tags, like ``<h1>``, using your own templating
system.
**With** this filter, Pandoc will convert the string ``"Title text"``
to ``"Title text"`` in HTML.
mathjax : `bool`, optional
If `True` then Pandoc will markup output content to work with MathJax.
Default is False.
smart | 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 dataset.
Examples
-------- | python | {
"resource": ""
} |
q265117 | JsonLdEncoder.default | validation | def default(self, obj):
"""Encode values as JSON strings.
This method overrides the default implementation from
`json.JSONEncoder`.
| 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:
| python | {
"resource": ""
} |
q265119 | Pip.install | validation | def install(self, package):
'''Install a python package using pip'''
| python | {
"resource": ""
} |
q265120 | Pip.upgrade | validation | def upgrade(self, package):
'''Update a python package using pip'''
logger.debug('Upgrading ' + 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 | python | {
"resource": ""
} |
q265122 | rmse | validation | def rmse(a, b):
"""Returns the root mean square error betwwen a and b
| python | {
"resource": ""
} |
q265123 | nmse | validation | def nmse(a, b):
"""Returns the normalized mean square error | python | {
"resource": ""
} |
q265124 | mfbe | validation | def mfbe(a, b):
"""Returns the mean fractionalized bias error
"""
| python | {
"resource": ""
} |
q265125 | foex | validation | def foex(a, b):
"""Returns the factor of exceedance
"""
| 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()
| python | {
"resource": ""
} |
q265127 | gmb | validation | def gmb(a, b):
"""Geometric mean bias
"""
| python | {
"resource": ""
} |
q265128 | gmv | validation | def gmv(a, b):
"""Geometric mean variance
"""
| python | {
"resource": ""
} |
q265129 | fmt | validation | def fmt(a, b):
"""Figure of merit in time
"""
return 100 * np.min([a, b], | 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', stderr(a, b)],
['mae', 'Mean Absolute Error', mae(a, b)],
['rmse', 'Root Mean Square Error', rmse(a, b)],
['nmse', 'Normalized Mean Square Error', nmse(a, b)],
['mfbe', 'Mean Fractionalized bias Error', mfbe(a, b)],
['fa2', 'Factor of Two', fa(a, b, 2)],
['foex', 'Factor of Exceedance', foex(a, b)],
['correlation', 'Correlation R', correlation(a, b)],
['determination', | python | {
"resource": ""
} |
q265131 | VirtualEnvironment.site_path | validation | def site_path(self):
'''Path to environments site-packages'''
if platform == 'win':
return | 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':
| 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 = set(sys.path) - old_syspath
for path in new_syspaths:
| python | {
"resource": ""
} |
q265134 | VirtualEnvironment.remove | validation | def remove(self):
'''
Remove this environment
'''
| 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:
| 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('myenv')
Create an environment elsewhere::
>>> cpenv.create('~/custom_location/myenv')
:param name_or_path: Name or full path of environment
:param config: Environment configuration including dependencies etc...
'''
# Get the real path of the environment
if utils.is_system_path(name_or_path):
path = unipath(name_or_path)
else:
| 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)
| 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) | 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:
| 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))
module_paths = get_module_paths()
for module_path in module_paths:
| 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)
| 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)
| 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.VirtualEnvironment):
data.append(get_info(obj))
modules = obj.get_modules()
if children and modules:
for mod in modules:
data.append(get_info(mod, indent=2, | 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(bold('\nActive modules'))
if env:
click.echo(format_objects([env] + active_modules))
available_modules = set(modules) - set(active_modules)
if available_modules:
click.echo(
bold('\nInactive modules in {}\n').format(cyan(env.name))
)
| 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'
' cpenv activate my_env\n'
' cpenv activate ./relative/path/to/my_env\n'
' cpenv activate my_env my_module\n'
)
click.echo(examples)
return
if skip_local:
cpenv.module_resolvers.remove(cpenv.resolver.module_resolver)
cpenv.module_resolvers.remove(cpenv.resolver.active_env_module_resolver)
if skip_shared:
cpenv.module_resolvers.remove(cpenv.resolver.modules_path_resolver)
try:
| 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'
' cpenv create my_env --config ./relative/path/to/config\n'
' cpenv create my_env --config git@github.com:user/config.git\n'
)
click.echo(examples)
return
click.echo(
blue('Creating a new virtual environment ' + name_or_path)
| 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 `cpenv module remove` instead.')
| 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'))
| 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)
| 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:
click.echo(bold_red('FAILED'))
raise
else:
click.echo(bold_green('OK!'))
click.echo('Browse to | 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 module add my_module ./path/to/my_module\n'
' cpenv module add my_module git@github.com:user/my_module.git'
' cpenv module add my_module git@github.com:user/my_module.git --branch=master --type=shared'
)
click.echo(examples)
return
if not name:
click.echo('Missing required argument: name')
return
if not path:
click.echo('Missing required argument: path')
env = cpenv.get_active_env()
if type=='local':
if not env:
click.echo('\nActivate an environment to add a local module.\n')
return
if click.confirm('\nAdd {} to active env {}?'.format(name, env.name)):
click.echo('Adding module...', nl=False)
try:
env.add_module(name, path, branch)
except:
click.echo(bold_red('FAILED'))
| 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))
module = r.resolved[0]
if isinstance(module, cpenv.VirtualEnvironment):
click.echo('\nCan only localize a module not an environment')
return
active_modules = cpenv.get_active_modules()
if module in active_modules:
click.echo('\nCan not localize an active module.')
return
if module in env.get_modules():
click.echo('\n{} is already local to {}'.format(module.name, env.name))
return
if click.confirm('\nAdd | python | {
"resource": ""
} |
q265153 | path_resolver | validation | def path_resolver(resolver, path):
'''Resolves VirtualEnvironments with a relative or absolute path''' | python | {
"resource": ""
} |
q265154 | home_resolver | validation | def home_resolver(resolver, path):
'''Resolves VirtualEnvironments in CPENV_HOME'''
from .api import get_home_path | python | {
"resource": ""
} |
q265155 | cache_resolver | validation | def cache_resolver(resolver, path):
'''Resolves VirtualEnvironments in | 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]
| 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:
| 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 array.
axes (list of int, optional): By default, reverse the dimensions,
otherwise permute the axes according to the values given.
"""
if isinstance(a, np.ndarray):
return np.transpose(a, axes)
elif isinstance(a, RemoteArray):
return a.transpose(*axes)
elif isinstance(a, Remote):
return _remote_to_array(a).transpose(*axes)
elif isinstance(a, DistArray):
if axes is None:
axes = | 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 is rolled until it lies before this
position. The default, 0, results in a "complete" roll.
Returns:
res (ndarray)
"""
if isinstance(a, np.ndarray):
return np.rollaxis(a, axis, start)
if axis not in range(a.ndim):
raise ValueError(
| 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.
"""
| 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 shape, except in the dimension corresponding to `axis`.
axis (int, optional): The axis along which the arrays will be joined.
Returns:
res: `ndarray`, if inputs were all local
`RemoteArray`, if inputs were all on the same remote engine
`DistArray`, if inputs were already scattered on different engines
"""
from distob import engine
if len(tup) is 0:
raise ValueError('need at least one array to concatenate')
first = tup[0]
others = tup[1:]
# allow subclasses to provide their own implementations of concatenate:
if (hasattr(first, 'concatenate') and
hasattr(type(first), '__array_interface__')):
return first.concatenate(others, axis)
# convert all arguments to arrays/RemoteArrays if they are not already:
arrays = []
for ar in tup:
if isinstance(ar, DistArray):
if axis == ar._distaxis:
arrays.extend(ar._subarrays)
else:
# Since not yet implemented arrays distributed on more than
# one axis, will fetch and re-scatter on the new axis:
arrays.append(gather(ar))
elif isinstance(ar, RemoteArray):
arrays.append(ar)
elif isinstance(ar, Remote):
arrays.append(_remote_to_array(ar))
elif hasattr(type(ar), '__array_interface__'):
# then treat as a local ndarray
arrays.append(ar)
else:
arrays.append(np.array(ar))
if all(isinstance(ar, np.ndarray) for ar in arrays):
return np.concatenate(arrays, axis)
total_length = 0
# validate dimensions are same, except for axis of concatenation:
commonshape = list(arrays[0].shape)
commonshape[axis] = None # ignore this axis for shape comparison
for ar in arrays:
total_length += ar.shape[axis]
shp = list(ar.shape)
shp[axis] = None
if shp != commonshape:
raise ValueError('incompatible shapes for concatenation')
| 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) # new common ndim | 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 are used for integer inputs.
Parameters
----------
a : array_like
Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the means are computed. The default is to
compute the mean of the flattened array.
If this is a tuple of ints, a mean is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default
is `float64`; for floating point inputs, it is the same as the
input dtype.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary.
See `doc.ufuncs` for details.
keepdims : bool, optional
| 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)
| 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)
| 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 = f.read()
if cmd.endswith('\x00'):
| 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)
| python | {
"resource": ""
} |
q265169 | launch | validation | def launch(prompt_prefix=None):
'''Launch a subshell'''
if prompt_prefix:
os.environ['PROMPT'] | 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):
| 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
"""
| 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 new timestamp and file body, and then monitor compare new timestamp
to originaltimestamp. If new timestamp and file body differ original,
monitor regard thease changes as `modification`. Then monitor create
instance of FileModificationObjectManager and FileModificationObject,
and monitor insert FileModificationObject to FileModificationObject-
Manager. Then, yield this object.
:param sleep: How times do you sleep in while roop.
"""
manager = FileModificationObjectManager()
timestamps = {}
| 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():
# query active directory
@app.status_job(timeout=5)
def paypal():
| 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('/', 1)[-1].split()
if color is None and cmd_detail[0] == 'less':
less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])
if not less_flags:
env['LESS'] = '-R'
color = True
elif 'r' in less_flags or 'R' in less_flags:
| 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 (np.mean, np.max, ...)
Retourne:
Un DataFrame de moyennes par mois
| 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())
| 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) | 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
utilisant uniquement les valeurs sur 1 heure mesurées quotidiennement
| python | {
"resource": ""
} |
q265179 | EnvironmentCache.validate | validation | def validate(self):
'''Validate all the entries in the environment cache.'''
for env in list(self):
| 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())
| 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 | 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 user aborts the input by sending a interrupt signal, this
function will catch it and raise a :exc:`Abort` exception.
.. versionadded:: 6.0
Added unicode support for cmd.exe on Windows.
.. versionadded:: 4.0
Added the `err` parameter.
:param text: the text to show for the prompt.
:param default: the default value to use if no input happens. If this
is not given it will prompt until it's aborted.
:param hide_input: if this is set to true then the input value will
be hidden.
:param confirmation_prompt: asks for confirmation for the value.
:param type: the type to use to check the value against.
:param value_proc: if this parameter is provided it's a function that
is invoked instead of the type conversion to
convert a value.
:param prompt_suffix: a suffix that should be added to the prompt.
:param show_default: shows or hides the default value in the prompt.
:param err: if set to true the file defaults to ``stderr`` instead of
``stdout``, the same as with echo.
"""
result = None
def prompt_func(text):
f = hide_input and hidden_prompt_func or visible_prompt_func
try:
# Write the prompt separately so that we get nice
# coloring through colorama on Windows
echo(text, nl=False, err=err)
return f('')
except (KeyboardInterrupt, EOFError):
# getpass doesn't print a newline if the user aborts input with ^C.
# Allegedly this behavior is inherited from getpass(3).
# A doc bug has been filed at https://bugs.python.org/issue24711
if hide_input:
echo(None, err=err)
raise | 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()
except:
raise DistobClusterError(
u"""Could not connect to an ipyparallel cluster. Make
sure a cluster is started (e.g. to use the CPUs of a
single computer, can type 'ipcluster start')""")
eids = client.ids
if not eids:
raise DistobClusterError(
u'No ipyparallel compute engines are available')
| 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
| python | {
"resource": ""
} |
q265186 | apply | validation | def apply(f, obj, *args, **kwargs):
"""Apply a function in parallel to each element of the input"""
| 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 isinstance(distob.engine, ObjectHub):
| 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 | python | {
"resource": ""
} |
q265189 | is_home_environment | validation | def is_home_environment(path):
'''Returns True if path is in CPENV_HOME'''
| python | {
"resource": ""
} |
q265190 | is_redirecting | validation | def is_redirecting(path):
'''Returns True if path contains a .cpenv file'''
candidate = unipath(path, '.cpenv') | 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:
| python | {
"resource": ""
} |
q265192 | expandpath | validation | def expandpath(path):
'''Returns an absolute expanded | python | {
"resource": ""
} |
q265193 | unipath | validation | def unipath(*paths):
'''Like os.path.join but also expands and normalizes path parts.'''
| 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__) | python | {
"resource": ""
} |
q265195 | ensure_path_exists | validation | def ensure_path_exists(path, *args):
'''Like os.makedirs but keeps quiet if path already exists'''
| 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, | 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:
| 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:
| 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]:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.