code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def strftime(self, fmt):
"""Format using strftime(). The date part of the timestamp passed
to underlying strftime should not be used.
"""
# The year must be >= 1000 else Python's strftime implementation
# can raise a bogus exception.
timetuple = (1900, 1, 1,
... | Format using strftime(). The date part of the timestamp passed
to underlying strftime should not be used. |
def addMonitor(self, monitorFriendlyName, monitorURL):
"""
Returns True if Monitor was added, otherwise False.
"""
url = self.baseUrl
url += "newMonitor?apiKey=%s" % self.apiKey
url += "&monitorFriendlyName=%s" % monitorFriendlyName
url += "&monitorURL=%s&monitorT... | Returns True if Monitor was added, otherwise False. |
def _wait_for_handles(handles, timeout=-1):
"""
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
"""
arrtype = HANDLE * len(handles)
handle_array = a... | Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx |
def add_row(self, row):
"""Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields"""
if self._field_names and len(row) != len(self._field_names):
raise Exception("Row has incorrect number of values, (act... | Add a row to the table
Arguments:
row - row of data, should be a list with as many elements as the table
has fields |
def callback(self, callback, *args, **kwds):
""" Registers an arbitrary callback and arguments.
Cannot suppress exceptions.
"""
return self << _CloseDummy(callback, args, kwds) | Registers an arbitrary callback and arguments.
Cannot suppress exceptions. |
def _fix_syscall_ip(state):
"""
Resolve syscall information from the state, get the IP address of the syscall SimProcedure, and set the IP of
the state accordingly. Don't do anything if the resolution fails.
:param SimState state: the program state.
:return: None
"""
... | Resolve syscall information from the state, get the IP address of the syscall SimProcedure, and set the IP of
the state accordingly. Don't do anything if the resolution fails.
:param SimState state: the program state.
:return: None |
def enforce_versioning(force=False):
"""Install versioning on the db."""
connect_str, repo_url = get_version_data()
LOG.warning("Your database uses an unversioned benchbuild schema.")
if not force and not ui.ask(
"Should I enforce version control on your schema?"):
LOG.error("User de... | Install versioning on the db. |
def configureLastWill(self, topic, payload, QoS):
"""
**Description**
Used to configure the last will topic, payload and QoS of the client. Should be called before connect. This is a public
facing API inherited by application level public clients.
**Syntax**
.. code:: ... | **Description**
Used to configure the last will topic, payload and QoS of the client. Should be called before connect. This is a public
facing API inherited by application level public clients.
**Syntax**
.. code:: python
myShadowClient.configureLastWill("last/Will/Topic", ... |
def validate_member_id_params_for_group_type(group_type, params, member_group_ids, member_entity_ids):
"""Determine whether member ID parameters can be sent with a group create / update request.
These parameters are only allowed for the internal group type. If they're set for an external group type, Va... | Determine whether member ID parameters can be sent with a group create / update request.
These parameters are only allowed for the internal group type. If they're set for an external group type, Vault
returns a "error" response.
:param group_type: Type of the group, internal or external
... |
def copy_logstore(from_client, from_project, from_logstore, to_logstore, to_project=None, to_client=None):
"""
copy logstore, index, logtail config to target logstore, machine group are not included yet.
the target logstore will be crated if not existing
:type from_client: LogClient
:param from_cli... | copy logstore, index, logtail config to target logstore, machine group are not included yet.
the target logstore will be crated if not existing
:type from_client: LogClient
:param from_client: logclient instance
:type from_project: string
:param from_project: project name
:type from_logstore:... |
def point_translate(point_in, vector_in):
""" Translates the input points using the input vector.
:param point_in: input point
:type point_in: list, tuple
:param vector_in: input vector
:type vector_in: list, tuple
:return: translated point
:rtype: list
"""
try:
if point_in ... | Translates the input points using the input vector.
:param point_in: input point
:type point_in: list, tuple
:param vector_in: input vector
:type vector_in: list, tuple
:return: translated point
:rtype: list |
def create_index(self, index):
"""Creates and opens index folder for given index.
If the index already exists, it just opens it, otherwise it creates it first.
"""
index._path = os.path.join(self.indexes_path, index._name)
if whoosh.index.exists_in(index._path):
_whoosh = whoosh.index.open_d... | Creates and opens index folder for given index.
If the index already exists, it just opens it, otherwise it creates it first. |
def relabel(self, qubits: Qubits) -> 'State':
"""Return a copy of this state with new qubits"""
return State(self.vec.tensor, qubits, self._memory) | Return a copy of this state with new qubits |
def get_variant_genotypes(self, variant):
"""Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes... | Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes. |
def _residual(self, x, in_filter, out_filter, stride,
activate_before_residual=False):
"""Residual unit with 2 sub layers."""
if activate_before_residual:
with tf.variable_scope('shared_activation'):
x = self._layer_norm('init_bn', x)
x = self._relu(x, self.hps.relu_leakine... | Residual unit with 2 sub layers. |
def get_file(fn):
"""Returns file contents in unicode as list."""
fn = os.path.join(os.path.dirname(__file__), 'data', fn)
f = open(fn, 'rb')
lines = [line.decode('utf-8').strip() for line in f.readlines()]
return lines | Returns file contents in unicode as list. |
def catalogAdd(type, orig, replace):
"""Add an entry in the catalog, it may overwrite existing but
different entries. If called before any other catalog
routine, allows to override the default shared catalog put
in place by xmlInitializeCatalog(); """
ret = libxml2mod.xmlCatalogAdd(type, orig... | Add an entry in the catalog, it may overwrite existing but
different entries. If called before any other catalog
routine, allows to override the default shared catalog put
in place by xmlInitializeCatalog(); |
def radial_density(im, bins=10, voxel_size=1):
r"""
Computes radial density function by analyzing the histogram of voxel
values in the distance transform. This function is defined by
Torquato [1] as:
.. math::
\int_0^\infty P(r)dr = 1.0
where *P(r)dr* is the probability of fi... | r"""
Computes radial density function by analyzing the histogram of voxel
values in the distance transform. This function is defined by
Torquato [1] as:
.. math::
\int_0^\infty P(r)dr = 1.0
where *P(r)dr* is the probability of finding a voxel at a lying at a radial
distance b... |
def start(self):
"""If we have a set of plugins that provide our expected listeners and
messengers, tell our dispatcher to start up. Otherwise, raise
InvalidApplication
"""
if not self.valid:
err = ("\nMessengers and listeners that still need set:\n\n"
... | If we have a set of plugins that provide our expected listeners and
messengers, tell our dispatcher to start up. Otherwise, raise
InvalidApplication |
def to_output(self, value):
"""Convert value to process output format."""
return json.loads(resolwe_runtime_utils.save_file(self.name, value.path, *value.refs)) | Convert value to process output format. |
def save(self, path, name, save_meta=True):
'''Saves model as a sequence of files in the format:
{path}/{name}_{'dec', 'disc', 'dec_opt',
'disc_opt', 'meta'}.h5
Parameters
----------
path : str
The directory of the file you wish to save the model to.
... | Saves model as a sequence of files in the format:
{path}/{name}_{'dec', 'disc', 'dec_opt',
'disc_opt', 'meta'}.h5
Parameters
----------
path : str
The directory of the file you wish to save the model to.
name : str
The name prefix of the m... |
def by_coordinates(self,
lat,
lng,
radius=25.0,
zipcode_type=ZipcodeType.Standard,
sort_by=SORT_BY_DIST,
ascending=True,
returns=DEFAULT_LIMIT):
"""
... | Search zipcode information near a coordinates on a map.
Returns multiple results.
:param lat: center latitude.
:param lng: center longitude.
:param radius: only returns zipcode within X miles from ``lat``, ``lng``.
**中文文档**
1. 计算出在中心坐标处, 每一经度和纬度分别代表多少miles.
2.... |
def render_next_step(self, form, **kwargs):
"""
When using the NamedUrlFormWizard, we have to redirect to update the
browser's URL to match the shown step.
"""
next_step = self.get_next_step()
self.storage.current_step = next_step
return redirect(self.url_name, st... | When using the NamedUrlFormWizard, we have to redirect to update the
browser's URL to match the shown step. |
def cli_execute(self, cmd):
""" sends the command to the CLI to be executed """
try:
args = parse_quotes(cmd)
if args and args[0] == 'feedback':
self.config.set_feedback('yes')
self.user_feedback = False
azure_folder = get_config_dir... | sends the command to the CLI to be executed |
def append_docstring_attributes(docstring, locals):
"""Manually appends class' ``docstring`` with its attribute docstrings.
For example::
class Entity(object):
# ...
__doc__ = append_docstring_attributes(
__doc__,
dict((k, v) for k, v in locals()... | Manually appends class' ``docstring`` with its attribute docstrings.
For example::
class Entity(object):
# ...
__doc__ = append_docstring_attributes(
__doc__,
dict((k, v) for k, v in locals()
if isinstance(v, MyDescriptor)... |
def delete(self):
"""
Destroys a previously constructed :class:`ITotalizer` object.
Internal variables ``self.cnf`` and ``self.rhs`` get cleaned.
"""
if self.tobj:
if not self._merged:
pycard.itot_del(self.tobj)
# otherwise, t... | Destroys a previously constructed :class:`ITotalizer` object.
Internal variables ``self.cnf`` and ``self.rhs`` get cleaned. |
def get_index_text(self, modname, name_cls):
"""Return text for index entry based on object type."""
if self.objtype.endswith('function'):
if not modname:
return _('%s() (built-in %s)') % \
(name_cls[0], self.chpl_type_name)
return _('%s() (in ... | Return text for index entry based on object type. |
def tranz(parser, token, is_transchoice=False):
"""
Templatetagish wrapper for Translator.trans()
:param parser:
:param token:
:param is_transchoice:
:return:
"""
tokens = token.split_contents()
id = tokens[1]
number = domain = locale = None
parameters = {}
if len(tokens... | Templatetagish wrapper for Translator.trans()
:param parser:
:param token:
:param is_transchoice:
:return: |
def build_output_map(protomap, get_tensor_by_name):
"""Builds a map of tensors from `protomap` using `get_tensor_by_name`.
Args:
protomap: A proto map<string,TensorInfo>.
get_tensor_by_name: A lambda that receives a tensor name and returns a
Tensor instance.
Returns:
A map from string to Tenso... | Builds a map of tensors from `protomap` using `get_tensor_by_name`.
Args:
protomap: A proto map<string,TensorInfo>.
get_tensor_by_name: A lambda that receives a tensor name and returns a
Tensor instance.
Returns:
A map from string to Tensor or SparseTensor instances built from `protomap`
and... |
def combine_intersections(
intersections, nodes1, degree1, nodes2, degree2, all_types
):
r"""Combine curve-curve intersections into curved polygon(s).
.. note::
This is a helper used only by :meth:`.Surface.intersect`.
Does so assuming each intersection lies on an edge of one of
two :class... | r"""Combine curve-curve intersections into curved polygon(s).
.. note::
This is a helper used only by :meth:`.Surface.intersect`.
Does so assuming each intersection lies on an edge of one of
two :class:`.Surface`-s.
.. note ::
This assumes that each ``intersection`` has been classifie... |
def generate_key(self, force=False):
"""
Creates a key file for this TaxPayer
Creates a key file for this TaxPayer if it does not have one, and
immediately saves it.
Returns True if and only if a key was created.
"""
if self.key and not force:
logger... | Creates a key file for this TaxPayer
Creates a key file for this TaxPayer if it does not have one, and
immediately saves it.
Returns True if and only if a key was created. |
def AREA(a, b):
"""area: Sort pack by area"""
return cmp(b[0] * b[1], a[0] * a[1]) or cmp(b[1], a[1]) or cmp(b[0], a[0]) | area: Sort pack by area |
def _destroy(self):
"""Destruction code to decrement counters"""
self.unuse_region()
if self._rlist is not None:
# Actual client count, which doesn't include the reference kept by the manager, nor ours
# as we are about to be deleted
try:
if l... | Destruction code to decrement counters |
def recreate_grams(self):
"""Re-create grams for database.
In normal situations, you never need to call this method.
But after migrate DB, this method is useful.
:param session: DB session
:type session: :class:`sqlalchemt.orm.Session`
"""
session = self.Sessi... | Re-create grams for database.
In normal situations, you never need to call this method.
But after migrate DB, this method is useful.
:param session: DB session
:type session: :class:`sqlalchemt.orm.Session` |
def create_multiple_replace_func(*args, **kwds):
"""
You can call this function and pass it a dictionary, or any other
combination of arguments you could pass to built-in dict in order to
construct a dictionary. The function will return a xlat closure that
takes as its only argument text the string ... | You can call this function and pass it a dictionary, or any other
combination of arguments you could pass to built-in dict in order to
construct a dictionary. The function will return a xlat closure that
takes as its only argument text the string on which the substitutions
are desired and returns a copy... |
def init_from_wave_file(wavpath):
"""Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile
"""
try:
samplerate, data = SW.read(... | Init a sonic visualiser environment structure based the analysis
of the main audio file. The audio file have to be encoded in wave
Args:
wavpath(str): the full path to the wavfile |
def clear_description(self):
"""Clears the description.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
if (self.get_description_metadata().is_read_only() or
... | Clears the description.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
def __cancel_timer(self):
"""
Cancels the timer, and calls its target method immediately
"""
if self.__timer is not None:
self.__timer.cancel()
self.__unbind_call(True)
self.__timer_args = None
self.__timer = None | Cancels the timer, and calls its target method immediately |
def generic_div(a, b):
"""Simple function to divide two numbers"""
logger.debug('Called generic_div({}, {})'.format(a, b))
return a / b | Simple function to divide two numbers |
def connect(self, *args, **kwargs):
""" Proxy to DynamoDBConnection.connect. """
self.connection = DynamoDBConnection.connect(*args, **kwargs)
self._session = kwargs.get("session")
if self._session is None:
self._session = botocore.session.get_session() | Proxy to DynamoDBConnection.connect. |
def xeval(source, optimize=True):
"""Compiles to native Python bytecode and runs program, returning the
topmost value on the stack.
Args:
optimize: Whether to optimize the code after parsing it.
Returns:
None: If the stack is empty
obj: If the stack contains a single value
... | Compiles to native Python bytecode and runs program, returning the
topmost value on the stack.
Args:
optimize: Whether to optimize the code after parsing it.
Returns:
None: If the stack is empty
obj: If the stack contains a single value
[obj, obj, ...]: If the stack contain... |
def render_import_image(self, use_auth=None):
"""
Configure the import_image plugin
"""
# import_image is a multi-phase plugin
if self.user_params.imagestream_name.value is None:
self.pt.remove_plugin('exit_plugins', 'import_image',
'... | Configure the import_image plugin |
def unpack_pargs(positional_args, param_kwargs, gnu=False):
"""Unpack multidict and positional args into a
list appropriate for subprocess.
:param param_kwargs:
``ParamDict`` storing '--param' style data.
:param positional_args: flags
:param gnu:
if True... | Unpack multidict and positional args into a
list appropriate for subprocess.
:param param_kwargs:
``ParamDict`` storing '--param' style data.
:param positional_args: flags
:param gnu:
if True, long-name args are unpacked as:
--parameter=argument
... |
def name(self, name=None):
'''api name, default is module.__name__'''
if name:
self._name = name
return self
return self._name | api name, default is module.__name__ |
def main():
'''
:param argv:
:return:
'''
log.configure(logging.DEBUG)
tornado.log.enable_pretty_logging()
# create the parser and parse the arguments
(parser, child_parser) = args.create_parsers()
(parsed_args, remaining) = parser.parse_known_args()
if remaining:
r = child_parser.parse_args(a... | :param argv:
:return: |
def as_dict(self):
"""
Returns a dictionary representation of the ChemicalEnvironments object
:return:
"""
return {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"coord_geoms": jsanitize(self.coord_geoms)} | Returns a dictionary representation of the ChemicalEnvironments object
:return: |
def _get_param_iterator(self):
"""Return ParameterSampler instance for the given distributions"""
return model_selection.ParameterSampler(
self.param_distributions, self.n_iter, random_state=self.random_state
) | Return ParameterSampler instance for the given distributions |
def main():
"""Create an identical user account on a pair of satellites."""
server_configs = (
{'url': url, 'auth': ('admin', 'changeme'), 'verify': False}
for url
in ('https://sat1.example.com', 'https://sat2.example.com')
)
for server_config in server_configs:
response ... | Create an identical user account on a pair of satellites. |
def push_to_remote(self, base_branch, head_branch, commit_message=""):
""" git push <origin> <branchname> """
set_state(WORKFLOW_STATES.PUSHING_TO_REMOTE)
cmd = ["git", "push", self.pr_remote, f"{head_branch}:{head_branch}"]
try:
self.run_cmd(cmd)
set_state(WORKF... | git push <origin> <branchname> |
def generate_resource(config, raml_resource, parent_resource):
""" Perform complete one resource configuration process
This function generates: ACL, view, route, resource, database
model for a given `raml_resource`. New nefertari resource is
attached to `parent_resource` class which is an instance of
... | Perform complete one resource configuration process
This function generates: ACL, view, route, resource, database
model for a given `raml_resource`. New nefertari resource is
attached to `parent_resource` class which is an instance of
`nefertari.resource.Resource`.
Things to consider:
* Top-... |
def get_versioned_files(cls):
"""List all files versioned by git in the current directory."""
files = cls._git_ls_files()
submodules = cls._list_submodules()
for subdir in submodules:
subdir = os.path.relpath(subdir).replace(os.path.sep, '/')
files += add_prefix_t... | List all files versioned by git in the current directory. |
def _SMOTE(T, N, k, h = 1.0):
"""
Returns (N/100) * n_minority_samples synthetic minority samples.
Parameters
----------
T : array-like, shape = [n_minority_samples, n_features]
Holds the minority samples
N : percetange of new synthetic samples:
n_synthetic_samples = N/100 * n_m... | Returns (N/100) * n_minority_samples synthetic minority samples.
Parameters
----------
T : array-like, shape = [n_minority_samples, n_features]
Holds the minority samples
N : percetange of new synthetic samples:
n_synthetic_samples = N/100 * n_minority_samples. Can be < 100.
k : int... |
def middleware(self, *args, **kwargs):
"""
Create a blueprint middleware from a decorated function.
:param args: Positional arguments to be used while invoking the
middleware
:param kwargs: optional keyword args that can be used with the
middleware.
"""
... | Create a blueprint middleware from a decorated function.
:param args: Positional arguments to be used while invoking the
middleware
:param kwargs: optional keyword args that can be used with the
middleware. |
def is_consistent(self) -> bool:
"""
Returns True if number of nodes are consistent with number of leaves
"""
from ledger.compact_merkle_tree import CompactMerkleTree
return self.nodeCount == CompactMerkleTree.get_expected_node_count(
self.leafCount) | Returns True if number of nodes are consistent with number of leaves |
def save(self):
""" Save any outstanding settnig changes to the :class:`~plexapi.server.PlexServer`. This
performs a full reload() of Settings after complete.
"""
params = {}
for setting in self.all():
if setting._setValue:
log.info('Saving PlexSer... | Save any outstanding settnig changes to the :class:`~plexapi.server.PlexServer`. This
performs a full reload() of Settings after complete. |
def list_incidents(self, update_keys, session=None, lightweight=None):
"""
Returns a list of incidents for the given events.
:param dict update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastU... | Returns a list of incidents for the given events.
:param dict update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session obje... |
def format_prettytable(table):
"""Converts SoftLayer.CLI.formatting.Table instance to a prettytable."""
for i, row in enumerate(table.rows):
for j, item in enumerate(row):
table.rows[i][j] = format_output(item)
ptable = table.prettytable()
ptable.hrules = prettytable.FRAME
ptabl... | Converts SoftLayer.CLI.formatting.Table instance to a prettytable. |
def start(self):
"""
Starts this bot in a separate thread. Therefore, this call is non-blocking.
It will listen to all new comments created in the :attr:`~subreddits` list.
"""
super().start()
comments_thread = BotThread(name='{}-comments-stream-thread'.format(self._name... | Starts this bot in a separate thread. Therefore, this call is non-blocking.
It will listen to all new comments created in the :attr:`~subreddits` list. |
def load_rule_definitions(self, ruleset_generator = False, rule_dirs = []):
"""
Load definition of rules declared in the ruleset
:param services:
:param ip_ranges:
:param aws_account_id:
:param generator:
:return:
"""
# Load rules from JSON files... | Load definition of rules declared in the ruleset
:param services:
:param ip_ranges:
:param aws_account_id:
:param generator:
:return: |
def get_old(dataset_label, data_id, destination_dir=None):
"""Get the 3D data from specified dataset with specified id.
Download data if necessary.
:param dataset_label:
:param data_id: integer or wildcards file pattern
:param destination_dir:
:return:
"""
# TODO implement
if desti... | Get the 3D data from specified dataset with specified id.
Download data if necessary.
:param dataset_label:
:param data_id: integer or wildcards file pattern
:param destination_dir:
:return: |
def write_to_screen(self, screen, mouse_handlers, write_position,
parent_style, erase_bg, z_index):
" Fill the whole area of write_position with dots. "
default_char = Char(' ', 'class:background')
dot = Char('.', 'class:background')
ypos = write_position.ypos
... | Fill the whole area of write_position with dots. |
def run_checker(cls, ds_loc, checker_names, verbose, criteria,
skip_checks=None, output_filename='-',
output_format=['text']):
"""
Static check runner.
@param ds_loc Dataset location (url or file)
@param checker_names List of string n... | Static check runner.
@param ds_loc Dataset location (url or file)
@param checker_names List of string names to run, should match keys of checkers dict (empty list means run all)
@param verbose Verbosity of the output (0, 1, 2)
@param criteria Determines fai... |
def complex_fault_node(edges):
"""
:param edges: a list of lists of points
:returns: a Node of kind complexFaultGeometry
"""
node = Node('complexFaultGeometry')
node.append(edge_node('faultTopEdge', edges[0]))
for edge in edges[1:-1]:
node.append(edge_node('intermediateEdge', edge))
... | :param edges: a list of lists of points
:returns: a Node of kind complexFaultGeometry |
def remove_option(self, section, option):
"""Remove an option."""
if not section or section == DEFAULTSECT:
sectdict = self._defaults
else:
try:
sectdict = self._sections[section]
except KeyError:
raise NoSectionError(section)
... | Remove an option. |
def to_vars_dict(self):
"""
Return local state which is relevant for the cluster setup process.
"""
return {
'azure_client_id': self.client_id,
'azure_location': self.location,
'azure_secret': self.secret,
'azure_su... | Return local state which is relevant for the cluster setup process. |
def collect_pac_urls(from_os_settings=True, from_dns=True, **kwargs):
"""
Get all the URLs that potentially yield a PAC file.
:param bool from_os_settings: Look for a PAC URL from the OS settings.
If a value is found and is a URL, it comes first in the returned list.
Doesn't do anythi... | Get all the URLs that potentially yield a PAC file.
:param bool from_os_settings: Look for a PAC URL from the OS settings.
If a value is found and is a URL, it comes first in the returned list.
Doesn't do anything on non-Windows or non-macOS/OSX platforms.
:param bool from_dns: Assemble a ... |
def pc_anova(self, covariates, num_pc=5):
"""
Calculate one-way ANOVA between the first num_pc prinicipal components
and known covariates. The size and index of covariates determines
whether u or v is used.
Parameters
----------
covariates : pandas.DataFrame... | Calculate one-way ANOVA between the first num_pc prinicipal components
and known covariates. The size and index of covariates determines
whether u or v is used.
Parameters
----------
covariates : pandas.DataFrame
Dataframe of covariates whose index corresponds to... |
def count_mnemonic(self, mnemonic, uwis=uwis, alias=None):
"""
Counts the wells that have a given curve, given the mnemonic and an
alias dict.
"""
all_mnemonics = self.get_mnemonics([mnemonic], uwis=uwis, alias=alias)
return len(list(filter(None, utils.flatten_list(all_mn... | Counts the wells that have a given curve, given the mnemonic and an
alias dict. |
def load_exons(self, exons, genes=None, build='37'):
"""Create exon objects and insert them into the database
Args:
exons(iterable(dict))
"""
genes = genes or self.ensembl_genes(build)
for exon in exons:
exon_obj = build_exon(exon, genes)
... | Create exon objects and insert them into the database
Args:
exons(iterable(dict)) |
def standard_input():
"""Generator that yields lines from standard input."""
with click.get_text_stream("stdin") as stdin:
while stdin.readable():
line = stdin.readline()
if line:
yield line.strip().encode("utf-8") | Generator that yields lines from standard input. |
def modify(db=None, sql=None):
'''
Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);'
'''... | Issue an SQL query to sqlite3 (with no return data), usually used
to modify the database in some way (insert, delete, create, etc)
CLI Example:
.. code-block:: bash
salt '*' sqlite3.modify /root/test.db 'CREATE TABLE test(id INT, testdata TEXT);' |
def _update(self):
"""compute/update all derived data
Can be called without harm and is idem-potent.
Updates these attributes and methods:
:attr:`origin`
the center of the cell with index 0,0,0
:attr:`midpoints`
centre coordinate of each grid c... | compute/update all derived data
Can be called without harm and is idem-potent.
Updates these attributes and methods:
:attr:`origin`
the center of the cell with index 0,0,0
:attr:`midpoints`
centre coordinate of each grid cell
:meth:`interpol... |
def save_direction(self, rootpath, raw=False, as_int=False):
""" Saves the direction of the slope to a file
"""
self.save_array(self.direction, None, 'ang', rootpath, raw, as_int=as_int) | Saves the direction of the slope to a file |
def AAS(cpu):
"""
ASCII Adjust AL after subtraction.
Adjusts the result of the subtraction of two unpacked BCD values to create a unpacked
BCD result. The AL register is the implied source and destination operand for this instruction.
The AAS instruction is only useful when it ... | ASCII Adjust AL after subtraction.
Adjusts the result of the subtraction of two unpacked BCD values to create a unpacked
BCD result. The AL register is the implied source and destination operand for this instruction.
The AAS instruction is only useful when it follows a SUB instruction that sub... |
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString):
"""Helper method for defining nested lists enclosed in opening and closing
delimiters ("(" and ")" are the default).
Parameters:
- opener - opening character for a nested list (default="("); can also be a pyparsing... | Helper method for defining nested lists enclosed in opening and closing
delimiters ("(" and ")" are the default).
Parameters:
- opener - opening character for a nested list (default="("); can also be a pyparsing expression
- closer - closing character for a nested list (default=")"); can ... |
def page(self, date_created_before=values.unset, date_created=values.unset,
date_created_after=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of RecordingInstance records from the API.
Request is exec... | Retrieve a single page of RecordingInstance records from the API.
Request is executed immediately
:param date date_created_before: The `YYYY-MM-DD` value of the resources to read
:param date date_created: The `YYYY-MM-DD` value of the resources to read
:param date date_created_after: Th... |
def _updateViewer(self, force=False):
"""Updates the viewer dialog.
If dialog is not visible and force=False, does nothing.
Otherwise, checks the mtime of the current purrer index.html file against self._viewer_timestamp.
If it is newer, reloads it.
"""
if not force and n... | Updates the viewer dialog.
If dialog is not visible and force=False, does nothing.
Otherwise, checks the mtime of the current purrer index.html file against self._viewer_timestamp.
If it is newer, reloads it. |
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders `data` into serialized XML.
"""
if data is None:
return ''
stream = StringIO()
xml = SimplerXMLGenerator(stream, self.charset)
xml.startDocument()
xml.startE... | Renders `data` into serialized XML. |
def get_inasafe_default_value_qsetting(
qsetting, category, inasafe_field_key):
"""Helper method to get the inasafe default value from qsetting.
:param qsetting: QSetting.
:type qsetting: QSetting
:param category: Category of the default value. It can be global or
recent. Global means ... | Helper method to get the inasafe default value from qsetting.
:param qsetting: QSetting.
:type qsetting: QSetting
:param category: Category of the default value. It can be global or
recent. Global means the global setting for default value. Recent
means the last set custom for default valu... |
def subvolume_get_default(path):
'''
Get the default subvolume of the filesystem path
path
Mount point for the subvolume
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_get_default /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'get-default', path]
res... | Get the default subvolume of the filesystem path
path
Mount point for the subvolume
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_get_default /var/volumes/tmp |
def clean_proced(self, proced):
"""Small helper function to delete the features from the final dictionary.
These features are mostly interesting for debugging but won't be relevant for most users.
"""
for loc in proced:
try:
del loc['all_countries']
... | Small helper function to delete the features from the final dictionary.
These features are mostly interesting for debugging but won't be relevant for most users. |
def assemble(self, ops, target=None):
"""
Assemble a series of operations and labels into bytecode, analyse its
stack usage and replace the bytecode and stack size of this code
object. Can also (optionally) change the target python version.
Arguments:
ops(list): The ... | Assemble a series of operations and labels into bytecode, analyse its
stack usage and replace the bytecode and stack size of this code
object. Can also (optionally) change the target python version.
Arguments:
ops(list): The opcodes (and labels) to assemble into bytecode.
... |
def write_dfile(self):
"""
Write the generated d_file to a temporary file.
"""
f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)")
with open(f_in, "w") as f:
f.write(self.as_dfile())
return f_in | Write the generated d_file to a temporary file. |
def _get_unknown_value(self):
""" Finds the smallest integer value >=0 that is not in `labels`
:return: Value that is not in the labels
:rtype: int
"""
label_set = set(self.labels)
value = 0
while value in label_set:
value += 1
return value | Finds the smallest integer value >=0 that is not in `labels`
:return: Value that is not in the labels
:rtype: int |
def normalize_paths(value, parent=os.curdir):
"""Parse a comma-separated list of paths.
Return a list of absolute paths.
"""
if not value:
return []
if isinstance(value, list):
return value
paths = []
for path in value.split(','):
path = path.strip()
if '/' i... | Parse a comma-separated list of paths.
Return a list of absolute paths. |
def inv(z: int) -> int:
"""$= z^{-1} mod q$, for z != 0"""
# Adapted from curve25519_athlon.c in djb's Curve25519.
z2 = z * z % q # 2
z9 = pow2(z2, 2) * z % q # 9
z11 = z9 * z2 % q # 11
z2_5_0 = (z11 * z11) % q * z9 % q # 31 == 2^5 - 2^0
z2_10_0 = pow2(z2_5_0, 5) * z2_5_0 % q # 2^10 - 2... | $= z^{-1} mod q$, for z != 0 |
def describe(cwd,
rev='HEAD',
user=None,
password=None,
ignore_retcode=False,
output_encoding=None):
'''
Returns the `git-describe(1)`_ string (or the SHA1 hash if there are no
tags) for the given revision.
cwd
The path to the git... | Returns the `git-describe(1)`_ string (or the SHA1 hash if there are no
tags) for the given revision.
cwd
The path to the git checkout
rev : HEAD
The revision to describe
user
User under which to run the git command. By default, the command is run
by the user under whi... |
def get_list_store(data_frame):
'''
Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame` and a `gtk.ListStore` matching the contents of the
data frame.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
... | Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame` and a `gtk.ListStore` matching the contents of the
data frame.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
(tuple) : The first element is a data frame... |
def GenerateDateTripsDeparturesList(self, date_start, date_end):
"""Return a list of (date object, number of trips, number of departures).
The list is generated for dates in the range [date_start, date_end).
Args:
date_start: The first date in the list, a date object
date_end: The first date a... | Return a list of (date object, number of trips, number of departures).
The list is generated for dates in the range [date_start, date_end).
Args:
date_start: The first date in the list, a date object
date_end: The first date after the list, a date object
Returns:
a list of (date object,... |
def reset(self):
'''Reset stream.'''
self._text = None
self._markdown = False
self._channel = Incoming.DEFAULT_CHANNEL
self._attachments = []
return self | Reset stream. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'limit') and self.limit is not None:
_dict['limit'] = self.limit
return _d... | Return a json dictionary representing this model. |
def _is_json_serialized_jws(self, json_jws):
"""
Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False
"""
json_ser_keys = {"payload", "signatures"}
flattened_json_ser_keys = {"payload", "signature"}
if not json... | Check if we've got a JSON serialized signed JWT.
:param json_jws: The message
:return: True/False |
def _trace_summary(self):
"""
Summarizes the trace of values used to update the DynamicArgs
and the arguments subsequently returned. May be used to
implement the summary method.
"""
for (i, (val, args)) in enumerate(self.trace):
if args is StopIteration:
... | Summarizes the trace of values used to update the DynamicArgs
and the arguments subsequently returned. May be used to
implement the summary method. |
def add_network_profile(self, obj, params):
"""Add an AP profile for connecting to afterward."""
network_id = self._send_cmd_to_wpas(obj['name'], 'ADD_NETWORK', True)
network_id = network_id.strip()
params.process_akm()
self._send_cmd_to_wpas(
obj['name'],
... | Add an AP profile for connecting to afterward. |
def reject_sender(self, link_handle, pn_condition=None):
"""Rejects the SenderLink, and destroys the handle."""
link = self._sender_links.get(link_handle)
if not link:
raise Exception("Invalid link_handle: %s" % link_handle)
link.reject(pn_condition)
# note: normally,... | Rejects the SenderLink, and destroys the handle. |
def boundaries(self, boundaryEdges=True, featureAngle=65, nonManifoldEdges=True):
"""
Return an ``Actor`` that shows the boundary lines of an input mesh.
:param bool boundaryEdges: Turn on/off the extraction of boundary edges.
:param float featureAngle: Specify the feature angle... | Return an ``Actor`` that shows the boundary lines of an input mesh.
:param bool boundaryEdges: Turn on/off the extraction of boundary edges.
:param float featureAngle: Specify the feature angle for extracting feature edges.
:param bool nonManifoldEdges: Turn on/off the extraction of non... |
def get(self, flex_sched_rule_id):
"""Retrieve the information for a flexscheduleRule entity."""
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | Retrieve the information for a flexscheduleRule entity. |
def _get_network_vswitch_map_by_port_id(self, port_id):
"""Get the vswitch name for the received port id."""
for network_id, vswitch in six.iteritems(self._network_vswitch_map):
if port_id in vswitch['ports']:
return (network_id, vswitch)
# If the port was not found,... | Get the vswitch name for the received port id. |
def guess_export_format(filename, data, **kwargs):
'''
guess_export_format(filename, data) attempts to guess the export file format for the given
filename and data (to be exported); it does this guessing by looking at the file extension and
using registered sniff-tests from exporters. It will not a... | guess_export_format(filename, data) attempts to guess the export file format for the given
filename and data (to be exported); it does this guessing by looking at the file extension and
using registered sniff-tests from exporters. It will not attempt to save the file, so if the
extension of the filen... |
def _run_lint_on_file(file_path,
linter_functions,
tool_options,
fix_what_you_can):
"""Run each function in linter_functions on filename.
If fix_what_you_can is specified, then the first error that has a
possible replacement will be automati... | Run each function in linter_functions on filename.
If fix_what_you_can is specified, then the first error that has a
possible replacement will be automatically fixed on this file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.