code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def solar_position_numba(unixtime, lat, lon, elev, pressure, temp, delta_t,
atmos_refract, numthreads, sst=False, esd=False):
"""Calculate the solar position using the numba compiled functions
and multiple threads. Very slow if functions are not numba compiled.
"""
# these args ... | Calculate the solar position using the numba compiled functions
and multiple threads. Very slow if functions are not numba compiled. |
def run(self):
"""Load table data to :class:`EuroStatsValue` objects
"""
# -- start documentation include: eurostats-run-1
# create a new indicator metadata object
indicator = models.EuroStatIndicator(
number=self.number,
description=self.description,
... | Load table data to :class:`EuroStatsValue` objects |
def data_to_dict(self, sysbase=False):
"""
Return the loaded model parameters as one dictionary.
Each key of the dictionary is a parameter name, and the value is a
list of all the parameter values.
:param sysbase: use system base quantities
:type sysbase: bool
"... | Return the loaded model parameters as one dictionary.
Each key of the dictionary is a parameter name, and the value is a
list of all the parameter values.
:param sysbase: use system base quantities
:type sysbase: bool |
def read_cdx(file, encoding='utf8'):
'''Iterate CDX file.
Args:
file (str): A file object.
encoding (str): The encoding of the file.
Returns:
iterator: Each item is a dict that maps from field key to value.
'''
with codecs.getreader(encoding)(file) as stream:
header... | Iterate CDX file.
Args:
file (str): A file object.
encoding (str): The encoding of the file.
Returns:
iterator: Each item is a dict that maps from field key to value. |
def available(name):
'''
Check if a service is available on the system.
Args:
name (str): The name of the service to check
Returns:
bool: ``True`` if the service is available, ``False`` otherwise
CLI Example:
.. code-block:: bash
salt '*' service.available <service n... | Check if a service is available on the system.
Args:
name (str): The name of the service to check
Returns:
bool: ``True`` if the service is available, ``False`` otherwise
CLI Example:
.. code-block:: bash
salt '*' service.available <service name> |
def to_operator(self):
"""Try to convert channel to a unitary representation Operator."""
mat = _to_operator(self.rep, self._data, *self.dim)
return Operator(mat, self.input_dims(), self.output_dims()) | Try to convert channel to a unitary representation Operator. |
def load_schema(name):
"""
loads the schema by name
:param name name of the model
"""
schema = import_schema_to_json(name)
#salesking specific swap
#//set link relation as key name to make it easier to call these
for item in schema['links']:
#//set link relation as key name to... | loads the schema by name
:param name name of the model |
def _repo_url_to_path(self, repo):
"""Convert a `repo` url to a file path for local storage."""
repo = repo.replace('http://', '')
repo = repo.replace('https://', '')
repo = repo.replace('/', '_')
return os.sep.join([self._data_directory, repo]) | Convert a `repo` url to a file path for local storage. |
def export_project(self):
""" Processes misc options specific for GCC ARM, and run generator """
generated_projects = deepcopy(self.generated_projects)
self.process_data_for_makefile(self.workspace)
generated_projects['path'], generated_projects['files']['makefile'] = self.gen_file_jinja... | Processes misc options specific for GCC ARM, and run generator |
def catalog(self, table='', column=''):
"""Lookup the values available for querying."""
lookup_table = self.lookup_table
if lookup_table is not None:
if table:
if column:
column = column.upper()
return lookup_table[table][column... | Lookup the values available for querying. |
def get(self, index):
"""Get a chunk by index"""
assert index <= self.count
assert index < self.size
offset = index * self.chunk_size
return self.data[offset:offset + self.chunk_size] | Get a chunk by index |
def _active_mounts_aix(ret):
'''
List active mounts on AIX systems
'''
for line in __salt__['cmd.run_stdout']('mount -p').split('\n'):
comps = re.sub(r"\s+", " ", line).split()
if comps:
if comps[0] == 'node' or comps[0] == '--------':
continue
com... | List active mounts on AIX systems |
def delete_project(self, tenant_name, part_name):
"""Delete project on the DCNM.
:param tenant_name: name of project.
:param part_name: name of partition.
"""
res = self._delete_partition(tenant_name, part_name)
if res and res.status_code in self._resp_ok:
LO... | Delete project on the DCNM.
:param tenant_name: name of project.
:param part_name: name of partition. |
def take_screenshot(self, screenshot_name=None, screenshot_path=None):
"""Take a screenshot
Use the screenshot_name args when you want to take a
screenshot for reference
If the `runner:cache_screenshot` config is set to True then
screenshot sharing all the same name wil... | Take a screenshot
Use the screenshot_name args when you want to take a
screenshot for reference
If the `runner:cache_screenshot` config is set to True then
screenshot sharing all the same name will be saved only once
The screenshot_path args is exclusively used by the
... |
def raise_for_status(self):
"""Raises stored :class:`HTTPError` or :class:`URLError`, if occurred.
"""
if not self.ok:
reason = self.reason or 'No response from %s' % self.url
if not self.status_code:
raise HttpConnectionError(reason, response=self)
... | Raises stored :class:`HTTPError` or :class:`URLError`, if occurred. |
def run(self, args=None):
"""! @brief Main entry point for command line processing."""
try:
self._args = self.build_parser().parse_args(args)
# Running without a subcommand will print usage.
if self._args.cmd is None:
if self._args.help_op... | ! @brief Main entry point for command line processing. |
def get_advanced_foreign_key_options_sql(self, foreign_key):
"""
Returns the FOREIGN KEY query section dealing with non-standard options
as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
:param foreign_key: The foreign key
:type foreign_key: ForeignKeyConstraint
:rtype: str
... | Returns the FOREIGN KEY query section dealing with non-standard options
as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
:param foreign_key: The foreign key
:type foreign_key: ForeignKeyConstraint
:rtype: str |
def compileActions(self):
"""Build the action table from the text above
"""
import re
self.actionList = actions = [None]*121
#Action 73, which is too long, looks like this when expanded:
actions[73] = "b' the '+w+b' of the '"
#find out what the columns are
... | Build the action table from the text above |
def setFontWeight(self, weight):
"""
Sets the font weight for this editor to the inputed weight.
:param weight | <QFont.Weight>
"""
font = self.currentFont()
font.setWeight(weight)
self.setCurrentFont(font) | Sets the font weight for this editor to the inputed weight.
:param weight | <QFont.Weight> |
def set_config_file(self, path):
"""
Set the config file. The contents must be valid YAML and there
must be a top-level element 'tasks'. The listed tasks will be
started according to their configuration, and the file will
be watched for future changes. The changes will be acti... | Set the config file. The contents must be valid YAML and there
must be a top-level element 'tasks'. The listed tasks will be
started according to their configuration, and the file will
be watched for future changes. The changes will be activated
by appropriate changes to the running t... |
def collect(self, device, ip, user, password):
""" Collects metrics for our netapp filer --START HERE--
"""
if netappsdk is None:
self.log.error(
'Failed to import netappsdk.NaServer or netappsdk.NaElement')
return
if device in self.running:
... | Collects metrics for our netapp filer --START HERE-- |
def nagiosCommandHelp(**kwargs):
"""
Returns command help document when no command is specified
"""
with open(os.path.join(DIRECTORY, 'document.html')) as document:
return document.read() | Returns command help document when no command is specified |
def api_client_two_way(connection, connection_responder, client_class=xbahn.api.Client):
"""
Establishes an API client for two-way communication
connection with an API Server
Arguments:
- connection (xbahn.connection.Connection)
- connection_responder (xbahn.connection.Connection): ... | Establishes an API client for two-way communication
connection with an API Server
Arguments:
- connection (xbahn.connection.Connection)
- connection_responder (xbahn.connection.Connection): This connection will
be used by the server to send requests to the client
Keyword Ar... |
def register_model(self, storagemodel:object):
""" set up an Tableservice for an StorageTableModel in your Azure Storage Account
Will create the Table if not exist!
required Parameter is:
- storagemodel: StorageTableModel(Object)
"""
modeldefinitio... | set up an Tableservice for an StorageTableModel in your Azure Storage Account
Will create the Table if not exist!
required Parameter is:
- storagemodel: StorageTableModel(Object) |
def _convert(x, factor1, factor2):
"""
Converts mixing ratio x in comp1 - comp2 tie line to that in
c1 - c2 tie line.
Args:
x (float): Mixing ratio x in comp1 - comp2 tie line, a float
between 0 and 1.
factor1 (float): Compositional ratio between ... | Converts mixing ratio x in comp1 - comp2 tie line to that in
c1 - c2 tie line.
Args:
x (float): Mixing ratio x in comp1 - comp2 tie line, a float
between 0 and 1.
factor1 (float): Compositional ratio between composition c1 and
processed compositio... |
def close(self):
"""Shutdown and free all resources."""
if self._controller is not None:
self._controller.quit()
self._controller = None
if self._process is not None:
self._process.close()
self._process = None | Shutdown and free all resources. |
def scatterviz(X,
y=None,
ax=None,
features=None,
classes=None,
color=None,
colormap=None,
markers=None,
alpha=1.0,
**kwargs):
"""Displays a bivariate scatter plot.
This helper... | Displays a bivariate scatter plot.
This helper function is a quick wrapper to utilize the ScatterVisualizer
(Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n, def... |
def get_expanded(self, *args, **kwargs):
"""
Same as :py:meth:`get_default`, but *expandvars* and *expanduser* arguments are set to
*True* by default.
"""
kwargs.setdefault("expandvars", True)
kwargs.setdefault("expanduser", True)
return self.get_default(*args, **... | Same as :py:meth:`get_default`, but *expandvars* and *expanduser* arguments are set to
*True* by default. |
def get_col(self, alias, output_field=None):
"""Get the decryption for col."""
if output_field is None:
output_field = self
if alias != self.model._meta.db_table or output_field != self:
return DecryptedCol(
alias,
self,
out... | Get the decryption for col. |
def slice_locs(self, start=None, end=None, step=None, kind=None):
"""
Compute slice locations for input labels.
Parameters
----------
start : label, default None
If None, defaults to the beginning
end : label, default None
If None, defaults to the... | Compute slice locations for input labels.
Parameters
----------
start : label, default None
If None, defaults to the beginning
end : label, default None
If None, defaults to the end
step : int, defaults None
If None, defaults to 1
kind... |
def run(self):
"""
run CMake
"""
command = [self.cmake]
if self.generator:
command.extend([
'-G', self.generator
])
if self.path:
command.append(self.path)
if self.definitions is not None:
for item... | run CMake |
def update(self, update_finished_cb):
"""Request an update of the memory content"""
if not self._update_finished_cb:
self._update_finished_cb = update_finished_cb
self.anchor_data = []
self.nr_of_anchors = 0
self.valid = False
logger.debug('Upd... | Request an update of the memory content |
def _gather_local_posterior(self, use_gather,
gather_size, gather_offset):
"""Gather/Gatherv local posterior
Parameters
----------
comm : object
MPI communication group
use_gather : boolean
Whether to use Gather or Gather... | Gather/Gatherv local posterior
Parameters
----------
comm : object
MPI communication group
use_gather : boolean
Whether to use Gather or Gatherv
gather_size : 1D array
The size of each local posterior
gather_offset : 1D array
... |
def _validate_file_ownership(owner, group, file_name, optional=False):
"""
Validate that a specified file is owned by `owner:group`.
:param owner: Name of the owner
:type owner: str
:param group: Name of the group
:type group: str
:param file_name: Path to the file to verify
:type file_... | Validate that a specified file is owned by `owner:group`.
:param owner: Name of the owner
:type owner: str
:param group: Name of the group
:type group: str
:param file_name: Path to the file to verify
:type file_name: str
:param optional: Is this file optional,
ie: Shou... |
def get_unhidden_ungenerated_python_files(directory: str) -> Iterable[str]:
"""Iterates through relevant python files within the given directory.
Args:
directory: The top-level directory to explore.
Yields:
File paths.
"""
for dirpath, dirnames, filenames in os.walk(directory, topd... | Iterates through relevant python files within the given directory.
Args:
directory: The top-level directory to explore.
Yields:
File paths. |
def truth(message, expected=None):
""" Convenience decorator that applies [`Check`](#check) to a callable.
```python
from good import truth
@truth(u'Must be an existing directory')
def isDir(v):
return os.path.isdir(v)
```
:param message: Validation error message
:type message... | Convenience decorator that applies [`Check`](#check) to a callable.
```python
from good import truth
@truth(u'Must be an existing directory')
def isDir(v):
return os.path.isdir(v)
```
:param message: Validation error message
:type message: unicode
:param expected: Expected val... |
def load_input():
""" Open existing input file """
file = open(_input_file, 'r')
result = json.loads(file.read().strip('\0').strip())
file.close()
return result | Open existing input file |
def corner_shape_parameters(corners, frame_shape, cb_shape):
"""
Return a tuple of shape parameters for a given set of corners. This is
based on the parameters from ROS's perception library[1]. The parameters
returned are mean x- and y- co-ordinate normalised onto the interval
[0,1], the relative si... | Return a tuple of shape parameters for a given set of corners. This is
based on the parameters from ROS's perception library[1]. The parameters
returned are mean x- and y- co-ordinate normalised onto the interval
[0,1], the relative size of the set of corners within the frame on the
interval [0,1] and a... |
def add_answer_for_student(student_item, vote, rationale):
"""
Add an answer for a student to the backend
Args:
student_item (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
vote (int): the option that student vot... | Add an answer for a student to the backend
Args:
student_item (dict): The location of the problem this submission is
associated with, as defined by a course, student, and item.
vote (int): the option that student voted for
rationale (str): the reason why the student vote for the... |
def hash160(data):
"""Return ripemd160(sha256(data))"""
rh = hashlib.new('ripemd160', sha256(data).digest())
return rh.digest() | Return ripemd160(sha256(data)) |
def linear_warp(X, d, n, *args):
r"""Warp inputs with a linear transformation.
Applies the warping
.. math::
w(x) = \frac{x-a}{b-a}
to each dimension. If you set `a=min(X)` and `b=max(X)` then this is a
convenient way to map your inputs to the unit hypercube.
... | r"""Warp inputs with a linear transformation.
Applies the warping
.. math::
w(x) = \frac{x-a}{b-a}
to each dimension. If you set `a=min(X)` and `b=max(X)` then this is a
convenient way to map your inputs to the unit hypercube.
Parameters
----------
X : ar... |
def setitem(self, key, value):
"""Maps dictionary keys to values for assignment. Called for
dictionary style access with assignment.
"""
with self.lock:
self.tbl[key] = value | Maps dictionary keys to values for assignment. Called for
dictionary style access with assignment. |
def op_list_venvs(self):
"""Prints out and returns a list of known virtual environments.
:rtype: list
:return: list of virtual environments
"""
self.logger.info('Listing known virtual environments ...')
venvs = self.get_venvs()
for venv in venvs:
self... | Prints out and returns a list of known virtual environments.
:rtype: list
:return: list of virtual environments |
def raises(self):
"""Return list of :raises meta."""
return [
DocstringRaises.from_meta(meta)
for meta in self.meta
if meta.args[0] in {'raises', 'raise', 'except', 'exception'}
] | Return list of :raises meta. |
def spectral_flux(d0, d1):
"""
Computes the spectral flux feature of the current frame
"""
# compute the spectral flux as the sum of square distances:
d0 = np.mean(d0, axis=1)
d1 = np.mean(d1, axis=1)
nFFT = min(len(d0) // 2, len(d1) // 2)
X = FFT(d0, nFFT)
Xprev = FFT(d1, nFFT)
... | Computes the spectral flux feature of the current frame |
def _WaitForStartup(self, deadline):
"""Waits for the emulator to start.
Args:
deadline: deadline in seconds
Returns:
True if the emulator responds within the deadline, False otherwise.
"""
start = time.time()
sleep = 0.05
def Elapsed():
return time.time() - start
w... | Waits for the emulator to start.
Args:
deadline: deadline in seconds
Returns:
True if the emulator responds within the deadline, False otherwise. |
def step(self, observations):
""" Sample action from an action space for given state """
q_values = self(observations)
return {
'actions': self.q_head.sample(q_values),
'q': q_values
} | Sample action from an action space for given state |
def freeze_all(self):
'''
Stop all activity of the agents running.
'''
d = defer.succeed(None)
for x in self.iter_agents():
d.addCallback(defer.drop_param, x._cancel_long_running_protocols)
d.addCallback(defer.drop_param, x._cancel_all_delayed_calls)
... | Stop all activity of the agents running. |
def http_get_metadata(metadata_path, timeout=__HTTP_DEFAULT_TIMEOUT_SEC):
"""
Fetch AWS metadata from http://169.254.169.254/latest/meta-data/<metadata_path>
ARGS:
metadata_path - the optional path and required key to the EC2 metadata (e.g. "instance-id")
RETURN:
response content on success
RAISE:
... | Fetch AWS metadata from http://169.254.169.254/latest/meta-data/<metadata_path>
ARGS:
metadata_path - the optional path and required key to the EC2 metadata (e.g. "instance-id")
RETURN:
response content on success
RAISE:
URLError if there was a problem reading metadata |
def repeat_last_axis(array, count):
"""
Restride `array` to repeat `count` times along the last axis.
Parameters
----------
array : np.array
The array to restride.
count : int
Number of times to repeat `array`.
Returns
-------
result : array
Array of shape a... | Restride `array` to repeat `count` times along the last axis.
Parameters
----------
array : np.array
The array to restride.
count : int
Number of times to repeat `array`.
Returns
-------
result : array
Array of shape array.shape + (count,) composed of `array` repeat... |
def _deleteFile(self,directory,fn,dentry,db,service):
"""Deletets file and changes status to '?' if no
more services manages the file
"""
# FIXME : can switch back to only managing once service
# at a time
logger.debug("%s - Deleting"%(fn))
if fn not in db:
... | Deletets file and changes status to '?' if no
more services manages the file |
def plot_pseudosection(df, plot_key, spacing=1, ctypes=None, dd_merge=False,
cb=False, **kwargs):
"""Create a pseudosection plot for a given measurement
Parameters
----------
df: dataframe
measurement dataframe, one measurement frame (i.e., only one frequency
etc)... | Create a pseudosection plot for a given measurement
Parameters
----------
df: dataframe
measurement dataframe, one measurement frame (i.e., only one frequency
etc)
key:
which key to colorcode
spacing: float, optional
assumed electrode spacing
ctypes: list of stri... |
def tryDynMod(name):
'''
Dynamically import a python module or exception.
'''
try:
return importlib.import_module(name)
except ModuleNotFoundError:
raise s_exc.NoSuchDyn(name=name) | Dynamically import a python module or exception. |
def _RunMethod(dev, args, extra):
"""Runs a method registered via MakeSubparser."""
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io.StringIO):
sys.stdout.writ... | Runs a method registered via MakeSubparser. |
def convert_coord_object(coord):
"""Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile"""
assert isinstance(coord, Coordinate)
coord = coord.container()
return Tile(int(coord.zoom), int(coord.column), int(coord.row)) | Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile |
def _get_title(self):
"""According to http://support.microsoft.com/kb/124103 the buffer
size is 1024
Does not support unicode, only ANSI"""
#TODO: unicode support
strbuffer = self.ctypes.create_string_buffer(1024)
size = self.ctypes.c_short(1024)
#unicode... | According to http://support.microsoft.com/kb/124103 the buffer
size is 1024
Does not support unicode, only ANSI |
def postcmd(self, stop, line):
''' Exit cmd cleanly. '''
self.color_prompt()
return Cmd.postcmd(self, stop, line) | Exit cmd cleanly. |
def inputs(self):
'''A list of Theano variables for feedforward computations.'''
return [l.input for l in self.layers if isinstance(l, layers.Input)] | A list of Theano variables for feedforward computations. |
def stop(self):
"""Stop this DMBS daemon. If it's not currently running, do nothing.
Don't return until it's terminated.
"""
log.info('Stopping PostgreSQL at %s:%s', self.host, self.port)
if self._is_running():
cmd = [
PostgresFinder.find_root() / 'p... | Stop this DMBS daemon. If it's not currently running, do nothing.
Don't return until it's terminated. |
def is_active(cache, token):
"""
Accepts the cache and ID token and checks to see if the profile is
currently logged in. If so, return the token, otherwise throw a
NotAuthenticatedException.
:param cache:
:param token:
:return:
"""
profile = cache.get(token)
if not profile:
... | Accepts the cache and ID token and checks to see if the profile is
currently logged in. If so, return the token, otherwise throw a
NotAuthenticatedException.
:param cache:
:param token:
:return: |
def assert_match(actual_char_or_str, expected_char_or_str):
"""If values don't match, print them and raise a ValueError, otherwise,
continue
Raises: ValueError if argumetns do not match"""
if expected_char_or_str != actual_char_or_str:
print("Expected")
pprint(expected_char_or_str)
... | If values don't match, print them and raise a ValueError, otherwise,
continue
Raises: ValueError if argumetns do not match |
def grouper(iterable: Iterable, size: int) -> Iterable:
"""
Collect data into fixed-length chunks or blocks without discarding underfilled chunks or padding them.
:param iterable: A sequence of inputs.
:param size: Chunk size.
:return: Sequence of chunks.
"""
it = iter(iterable)
while T... | Collect data into fixed-length chunks or blocks without discarding underfilled chunks or padding them.
:param iterable: A sequence of inputs.
:param size: Chunk size.
:return: Sequence of chunks. |
def to_html(self, write_to):
"""Method to convert the repository list to a search results page and
write it to a HTML file.
:param write_to: File/Path to write the html file to.
"""
page_html = self.get_html()
with open(write_to, "wb") as writefile:
writefil... | Method to convert the repository list to a search results page and
write it to a HTML file.
:param write_to: File/Path to write the html file to. |
def available_configuration_files(self):
"""A list of strings with the absolute pathnames of the available configuration files."""
known_files = [GLOBAL_CONFIG, LOCAL_CONFIG, self.environment.get('PIP_ACCEL_CONFIG')]
absolute_paths = [parse_path(pathname) for pathname in known_files if pathname]... | A list of strings with the absolute pathnames of the available configuration files. |
def handle_not_found(exception, **extra):
"""Custom blueprint exception handler."""
assert isinstance(exception, NotFound)
page = Page.query.filter(db.or_(Page.url == request.path,
Page.url == request.path + "/")).first()
if page:
_add_url_rule(page.url)
... | Custom blueprint exception handler. |
def _writeTracebackMessage(logger, typ, exception, traceback):
"""
Write a traceback to the log.
@param typ: The class of the exception.
@param exception: The L{Exception} instance.
@param traceback: The traceback, a C{str}.
"""
msg = TRACEBACK_MESSAGE(
reason=exception, traceback... | Write a traceback to the log.
@param typ: The class of the exception.
@param exception: The L{Exception} instance.
@param traceback: The traceback, a C{str}. |
def sens_power_encode(self, adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp):
'''
Voltage and current sensor data
adc121_vspb_volt : Power board voltage sensor reading in volts (float)
adc121_cspb_amp : Power board cur... | Voltage and current sensor data
adc121_vspb_volt : Power board voltage sensor reading in volts (float)
adc121_cspb_amp : Power board current sensor reading in amps (float)
adc121_cs1_amp : Board current sensor 1 reading in amps (float)
... |
def get_workflow_id_and_project(path):
'''
:param path: a path or ID to a workflow object
:type path: string
:returns: tuple of (workflow ID, project ID)
Returns the workflow and project IDs from the given path if
available; otherwise, exits with an appropriate error message.
'''
projec... | :param path: a path or ID to a workflow object
:type path: string
:returns: tuple of (workflow ID, project ID)
Returns the workflow and project IDs from the given path if
available; otherwise, exits with an appropriate error message. |
def _iter(self):
"""Generate (name, est, weight) tuples excluding None transformers
"""
get_weight = (self.transformer_weights or {}).get
return ((name, trans, get_weight(name))
for name, trans in self.transformer_list
if trans is not None) | Generate (name, est, weight) tuples excluding None transformers |
def CreateStorageReaderForFile(cls, path):
"""Creates a storage reader based on the file.
Args:
path (str): path to the storage file.
Returns:
StorageReader: a storage reader or None if the storage file cannot be
opened or the storage format is not supported.
"""
if sqlite_fi... | Creates a storage reader based on the file.
Args:
path (str): path to the storage file.
Returns:
StorageReader: a storage reader or None if the storage file cannot be
opened or the storage format is not supported. |
def break_bond(self, ind1, ind2, tol=0.2):
"""
Returns two molecules based on breaking the bond between atoms at index
ind1 and ind2.
Args:
ind1 (int): Index of first site.
ind2 (int): Index of second site.
tol (float): Relative tolerance to test. Bas... | Returns two molecules based on breaking the bond between atoms at index
ind1 and ind2.
Args:
ind1 (int): Index of first site.
ind2 (int): Index of second site.
tol (float): Relative tolerance to test. Basically, the code
checks if the distance between... |
def task_delete(self, **kw):
""" Marks a task as deleted. """
id, task = self.get_task(**kw)
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
self._execute(id, 'delete')
return self.get_task(uuid=task['uuid'])[1] | Marks a task as deleted. |
def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True):
"""
Get file from ipfs
We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise
"""
if validate:
from snet_cli.resources.proto.unixfs_pb2 import Data
from snet_cli.resources... | Get file from ipfs
We must check the hash becasue we cannot believe that ipfs_client wasn't been compromise |
def change(self, event):
"""Change an existing object"""
try:
data, schema, user, client = self._get_args(event)
except AttributeError:
return
try:
uuid = data['uuid']
change = data['change']
field = change['field']
... | Change an existing object |
def _get_pkgng_version(jail=None, chroot=None, root=None):
'''
return the version of 'pkg'
'''
cmd = _pkg(jail, chroot, root) + ['--version']
return __salt__['cmd.run'](cmd).strip() | return the version of 'pkg' |
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
"""
Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or wri... | Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or writable file-like object to write the image data
to.
*prop*
If provi... |
def set_xticklabels_position(self, row, column, position):
"""Specify the position of the axis tick labels.
This is generally only useful for multiplots containing only one
row. This can be used to e.g. alternatively draw the tick labels
on the bottom or the top of the subplot.
... | Specify the position of the axis tick labels.
This is generally only useful for multiplots containing only one
row. This can be used to e.g. alternatively draw the tick labels
on the bottom or the top of the subplot.
:param row,column: specify the subplot.
:param position: 'to... |
def handle_combined_input(args):
"""Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting.
"""
cur_args = args[:]
while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)):
... | Check for cases where we have a combined input nested list.
In these cases the CWL will be double nested:
[[[rec_a], [rec_b]]]
and we remove the outer nesting. |
def _load_url(url):
"""
Loads a URL resource from a remote server
"""
try:
response = requests.get(url)
return BytesIO(response.content)
except IOError as ex:
parser.error("{url} could not be loaded remotely! ({ex})".format(url=url, ex=ex)) | Loads a URL resource from a remote server |
def _get_YYTfactor(self, Y):
"""
find a matrix L which satisfies LLT = YYT.
Note that L may have fewer columns than Y.
"""
N, D = Y.shape
if (N>=D):
return Y.view(np.ndarray)
else:
return jitchol(tdot(Y)) | find a matrix L which satisfies LLT = YYT.
Note that L may have fewer columns than Y. |
def is_valid_coordinate(img, i, j, k):
"""Return True if the given (i, j, k) voxel grid coordinate values are within the img boundaries.
Parameters
----------
@param img:
@param i:
@param j:
@param k:
Returns
-------
bool
"""
imgx, imgy, imgz = get_shape(img)
return... | Return True if the given (i, j, k) voxel grid coordinate values are within the img boundaries.
Parameters
----------
@param img:
@param i:
@param j:
@param k:
Returns
-------
bool |
def curse(rest):
"Curse the day!"
if rest:
cursee = rest
else:
cursee = 'the day'
karma.Karma.store.change(cursee, -1)
return "/me curses %s!" % cursee | Curse the day! |
def verify(self, msg, sig, key):
"""
Verify a message signature
:param msg: The message
:param sig: A signature
:param key: A ec.EllipticCurvePublicKey to use for the verification.
:raises: BadSignature if the signature can't be verified.
:return: True
""... | Verify a message signature
:param msg: The message
:param sig: A signature
:param key: A ec.EllipticCurvePublicKey to use for the verification.
:raises: BadSignature if the signature can't be verified.
:return: True |
def _resource_prefix(self, resource=None):
"""Get elastic prefix for given resource.
Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``.
"""
px = 'ELASTICSEARCH'
if resource and config.DOMAIN[resource].get('elastic_prefix'):
px = config.... | Get elastic prefix for given resource.
Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``. |
def from_(self, table, alias=None):
"""
Establece el origen de datos (y un alias opcionalmente).
"""
if isinstance(table, str):
table = [[table, alias]]
self.raw_tables = table
return self | Establece el origen de datos (y un alias opcionalmente). |
def copy_sig(sig, opts, isdiff):
"""Deploy a sig"""
info("[+] \033[92mDeploying signature:\033[0m %s" % sig)
if isdiff:
sourcefile = os.path.join(opts.workdir, '%s.cdiff' % sig)
destfile = os.path.join(opts.mirrordir, '%s.cdiff' % sig)
else:
sourcefile = os.path.join(opts.workdir... | Deploy a sig |
def _parse_team_name(self, team):
"""
Parse the team name in the contract table.
The team names in the contract table contain special encoded characters
that are not supported by Python 2.7. These characters should be
filtered out to get the proper team name.
Parameters... | Parse the team name in the contract table.
The team names in the contract table contain special encoded characters
that are not supported by Python 2.7. These characters should be
filtered out to get the proper team name.
Parameters
----------
team : string
... |
def linescore(self):
"""Returns the linescore for the game as a DataFrame."""
doc = self.get_main_doc()
table = doc('table#line_score')
columns = [th.text() for th in table('tr.thead').items('th')]
columns[0] = 'team_id'
data = [
[sportsref.utils.flatten_lin... | Returns the linescore for the game as a DataFrame. |
def not_storable(_type):
"""
Helper for tagging unserializable types.
Arguments:
_type (type): type to be ignored.
Returns:
Storable: storable instance that does not poke.
"""
return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type))) | Helper for tagging unserializable types.
Arguments:
_type (type): type to be ignored.
Returns:
Storable: storable instance that does not poke. |
def write_local_file(fp, name_bytes, writer, dt):
"""
Writes a zip file local file header structure at the current file position.
Returns data_len, crc32 for the data.
:param fp: the file point to which to write the header
:param name: the name of the file
:param writer: a ... | Writes a zip file local file header structure at the current file position.
Returns data_len, crc32 for the data.
:param fp: the file point to which to write the header
:param name: the name of the file
:param writer: a function taking an fp parameter to do the writing, returns crc32
... |
def zcr(data):
"""Computes zero crossing rate of segment"""
data = np.mean(data, axis=1)
count = len(data)
countZ = np.sum(np.abs(np.diff(np.sign(data)))) / 2
return (np.float64(countZ) / np.float64(count - 1.0)) | Computes zero crossing rate of segment |
def _plot_x(self, iabscissa=1, x_opt=None, remark=None,
annotations=None):
"""If ``x_opt is not None`` the difference to x_opt is plotted
in log scale
"""
if not hasattr(self, 'x'):
_print_warning('no x-attributed found, use methods ' +
... | If ``x_opt is not None`` the difference to x_opt is plotted
in log scale |
def _handler_swagger_ui(self, request, spec, version):
"""
---
parameters:
- name: spec
in: query
type: string
- name: version
in: query
type: integer
enum: [2,3]
"""
version = version or self._versio... | ---
parameters:
- name: spec
in: query
type: string
- name: version
in: query
type: integer
enum: [2,3] |
def _add_token(self, token, parent_node='root'):
"""add a token to this docgraph"""
if parent_node == 'root':
parent_node = self.root
token_node_id = 'token:{}'.format(self.token_count)
self.add_node(token_node_id, layers={self.ns, self.ns+':token'},
at... | add a token to this docgraph |
def run(config, tag, bucket, account, not_bucket, not_account, debug, region):
"""Run across a set of accounts and buckets."""
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s: %(name)s:%(levelname)s %(message)s")
logging.getLogger('botocore').setLevel(level=logging.WARNING)
... | Run across a set of accounts and buckets. |
def guass(self, mu: float, sigma: float) -> float:
"""Return a random number using Gaussian distribution.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
"""
return float(
... | Return a random number using Gaussian distribution.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float. |
def compute_mu(L_aug, Y, k, p):
"""Given label matrix L_aug and labels Y, compute the true mu params.
Args:
L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix
Y: (np.array int) [n] The true labels in {1,...,k}
k: (int) Cardinality
p: (np.array float) [k] The class... | Given label matrix L_aug and labels Y, compute the true mu params.
Args:
L: (np.array {0,1}) [n, d] The augmented (indicator) label matrix
Y: (np.array int) [n] The true labels in {1,...,k}
k: (int) Cardinality
p: (np.array float) [k] The class balance |
def write(self, data):
"""
Write data to the file. If write buffering is on (``bufsize`` was
specified and non-zero), some or all of the data may not actually be
written yet. (Use `flush` or `close` to force buffered data to be
written out.)
:param data: ``str``/``byte... | Write data to the file. If write buffering is on (``bufsize`` was
specified and non-zero), some or all of the data may not actually be
written yet. (Use `flush` or `close` to force buffered data to be
written out.)
:param data: ``str``/``bytes`` data to write |
def deltasigma_nfw(self):
"""Calculate NFW differential surface mass density profile.
Generate the differential surface mass density profiles of each cluster
halo, assuming a spherical NFW model. Optionally includes the effect of
cluster miscentering offsets, if the parent object was in... | Calculate NFW differential surface mass density profile.
Generate the differential surface mass density profiles of each cluster
halo, assuming a spherical NFW model. Optionally includes the effect of
cluster miscentering offsets, if the parent object was initialized
with offsets.
... |
def interpret_stats(results):
"""Generates the string to be shown as updates after the execution of a
Cypher query
:param results: ``ResultSet`` with the raw results of the execution of
the Cypher query
"""
stats = results.stats
contains_updates = stats.pop("contains_updates... | Generates the string to be shown as updates after the execution of a
Cypher query
:param results: ``ResultSet`` with the raw results of the execution of
the Cypher query |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.