code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def exists(name, attributes):
'''
Make sure the given attributes exist on the file/directory
name
The path to the file/directory
attributes
The attributes that should exist on the file/directory, this is accepted as
an array, with key and value split with an equals sign, if you... | Make sure the given attributes exist on the file/directory
name
The path to the file/directory
attributes
The attributes that should exist on the file/directory, this is accepted as
an array, with key and value split with an equals sign, if you want to specify
a hex value then ... |
def view_isometric(self):
"""
Resets the camera to a default isometric view showing all the
actors in the scene.
"""
self.camera_position = self.get_default_cam_pos()
self.camera_set = False
return self.reset_camera() | Resets the camera to a default isometric view showing all the
actors in the scene. |
def get_files_to_remove(self):
"""
Returns orphaned media files to be removed grouped by resource type.
All files which paths start with any of exclude paths are ignored.
"""
files_to_remove = {}
needful_files = self.get_needful_files()
for resources_type, resourc... | Returns orphaned media files to be removed grouped by resource type.
All files which paths start with any of exclude paths are ignored. |
def parse_slab_stats(slab_stats):
"""Convert output from memcached's `stats slabs` into a Python dict.
Newlines are returned by memcached along with carriage returns
(i.e. '\r\n').
>>> parse_slab_stats(
"STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT "
"active_sla... | Convert output from memcached's `stats slabs` into a Python dict.
Newlines are returned by memcached along with carriage returns
(i.e. '\r\n').
>>> parse_slab_stats(
"STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT "
"active_slabs 1\r\nSTAT total_malloced 1048512\r\nEN... |
def stack_frames(
sig,
sampling_frequency,
frame_length=0.020,
frame_stride=0.020,
filter=lambda x: np.ones(
(x,
)),
zero_padding=True):
"""Frame a signal into overlapping frames.
Args:
sig (array): The audio signal to frame of si... | Frame a signal into overlapping frames.
Args:
sig (array): The audio signal to frame of size (N,).
sampling_frequency (int): The sampling frequency of the signal.
frame_length (float): The length of the frame in second.
frame_stride (float): The stride between frames.
filter... |
def from_args(cls: Type[ConfigT], args: Namespace) -> ConfigT:
"""Build and return a new :class:`IMAPConfig` using command-line
arguments.
Args:
args: The arguments parsed from the command-line.
"""
parsed_args = cls.parse_args(args)
return cls(args, host=ar... | Build and return a new :class:`IMAPConfig` using command-line
arguments.
Args:
args: The arguments parsed from the command-line. |
def main():
"""Main method."""
args = parse_cmd_arguments()
html_file = args.file
try:
json.loads(args.add_tags or '{}')
json.loads(args.exc_tags or '{}')
except ValueError:
print('\033[91m' + 'Invalid json string: please provide a valid json '
'string e.g {}'.... | Main method. |
def _ldtpize_accessible(self, acc):
"""
Get LDTP format accessibile name
@param acc: Accessible handle
@type acc: object
@return: object type, stripped object name (associated / direct),
associated label
@rtype: tuple
"""
actual_r... | Get LDTP format accessibile name
@param acc: Accessible handle
@type acc: object
@return: object type, stripped object name (associated / direct),
associated label
@rtype: tuple |
def numBlast_sort(blast, numHits, evalueT, bitT):
"""
parse b6 output with sorting
"""
header = ['#query', 'target', 'pident', 'alen', 'mismatch', 'gapopen',
'qstart', 'qend', 'tstart', 'tend', 'evalue', 'bitscore']
yield header
hmm = {h:[] for h in header}
for line in blast:
... | parse b6 output with sorting |
def gaps(args):
"""
%prog gaps agpfile
Print out the distribution of gapsizes. Option --merge allows merging of
adjacent gaps which is used by tidy().
"""
from jcvi.graphics.histogram import loghistogram
p = OptionParser(gaps.__doc__)
p.add_option("--merge", dest="merge", default=False... | %prog gaps agpfile
Print out the distribution of gapsizes. Option --merge allows merging of
adjacent gaps which is used by tidy(). |
def generate_doxygen_xml(app):
"""Run the doxygen make commands if we're on the ReadTheDocs server"""
read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True'
if read_the_docs_build:
run_doxygen('..')
sys.stderr.write('Check if shared lib exists\n')
run_build_lib('..')
... | Run the doxygen make commands if we're on the ReadTheDocs server |
def _parse_modes(mode_string, unary_modes=""):
"""
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _pa... | Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _parse_modes('+a foo bar baz')
[['+', 'a', None]]
Ret... |
def newAddress(self, currency='btc', label=''):
"""
Send a request for a new cryptocurrency deposit address
with an optional label. Return the response.
Arguements:
currency -- a Gemini supported cryptocurrency (btc, eth)
label -- optional label for the deposit address
... | Send a request for a new cryptocurrency deposit address
with an optional label. Return the response.
Arguements:
currency -- a Gemini supported cryptocurrency (btc, eth)
label -- optional label for the deposit address |
def stop(self, signal=None):
"""Stop the heroku local subprocess and all of its children.
"""
signal = signal or self.int_signal
self.out.log("Cleaning up local Heroku process...")
if self._process is None:
self.out.log("No local Heroku process was running.")
... | Stop the heroku local subprocess and all of its children. |
def get_submission(submission_uuid, read_replica=False):
"""Retrieves a single submission by uuid.
Args:
submission_uuid (str): Identifier for the submission.
Kwargs:
read_replica (bool): If true, attempt to use the read replica database.
If no read replica is available, use th... | Retrieves a single submission by uuid.
Args:
submission_uuid (str): Identifier for the submission.
Kwargs:
read_replica (bool): If true, attempt to use the read replica database.
If no read replica is available, use the default database.
Raises:
SubmissionNotFoundError... |
def _disc_kn(clearness_index, airmass, max_airmass=12):
"""
Calculate Kn for `disc`
Parameters
----------
clearness_index : numeric
airmass : numeric
max_airmass : float
airmass > max_airmass is set to max_airmass before being used
in calculating Kn.
Returns
-------... | Calculate Kn for `disc`
Parameters
----------
clearness_index : numeric
airmass : numeric
max_airmass : float
airmass > max_airmass is set to max_airmass before being used
in calculating Kn.
Returns
-------
Kn : numeric
am : numeric
airmass used in the calcu... |
def get_hash(key: str) -> int:
"""Gets a hash of the provided key.
Parameters
----------
key :
A string used to create a seed for the random number generator.
Returns
-------
int
A hash of the provided key.
"""
# 4294967295 == 2**32 - 1 which is the maximum allowabl... | Gets a hash of the provided key.
Parameters
----------
key :
A string used to create a seed for the random number generator.
Returns
-------
int
A hash of the provided key. |
def GetErrorText(
self,
Error,
Language = 0):
"""
Configures or sets a PCAN Channel value
Remarks:
The current languages available for translation are:
Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A),
Italian (0x10) and Fre... | Configures or sets a PCAN Channel value
Remarks:
The current languages available for translation are:
Neutral (0x00), German (0x07), English (0x09), Spanish (0x0A),
Italian (0x10) and French (0x0C)
The return value of this method is a 2-touple, where
the firs... |
def read_elements(fd, endian, mtps, is_name=False):
"""Read elements from the file.
If list of possible matrix data types mtps is provided, the data type
of the elements are verified.
"""
mtpn, num_bytes, data = read_element_tag(fd, endian)
if mtps and mtpn not in [etypes[mtp]['n'] for mtp in m... | Read elements from the file.
If list of possible matrix data types mtps is provided, the data type
of the elements are verified. |
def delete_validating_webhook_configuration(self, name, **kwargs):
"""
delete a ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_validating_webhook_conf... | delete a ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_validating_webhook_configuration(name, async_req=True)
>>> result = thread.get()
:param async... |
def enrich_rnas_with_genes(graph):
"""Add the corresponding gene node for each RNA/miRNA node and connect them with a transcription edge.
:param pybel.BELGraph graph: A BEL graph
"""
for rna_node in list(graph):
if rna_node[FUNCTION] not in {MIRNA, RNA} or FUSION in rna_node or VARIANTS in rna_... | Add the corresponding gene node for each RNA/miRNA node and connect them with a transcription edge.
:param pybel.BELGraph graph: A BEL graph |
def calc_requiredremotesupply_v1(self):
"""Calculate the required maximum supply from another location
that can be discharged into the dam.
Required control parameters:
|HighestRemoteSupply|
|WaterLevelSupplyThreshold|
Required derived parameter:
|WaterLevelSupplySmoothPar|
Requ... | Calculate the required maximum supply from another location
that can be discharged into the dam.
Required control parameters:
|HighestRemoteSupply|
|WaterLevelSupplyThreshold|
Required derived parameter:
|WaterLevelSupplySmoothPar|
Required aide sequence:
|WaterLevel|
Cal... |
def image_question_encoder(encoder_inputs,
encoder_self_attention_bias,
hparams,
query=None,
name="image_question_encoder",
save_weights_to=None,
make_image_s... | A stack of self attention layers. |
def new_file(self, path: str, checksum: str=None, to_archive: bool=False,
tags: List[models.Tag]=None) -> models.File:
"""Create a new file."""
new_file = self.File(path=path, checksum=checksum, to_archive=to_archive, tags=tags)
return new_file | Create a new file. |
def get_lib_name(self):
""" Parse Cargo.toml to get the name of the shared library. """
# We import in here to make sure the the setup_requires are already installed
import toml
cfg = toml.load(self.path)
name = cfg.get("lib", {}).get("name")
if name is None:
... | Parse Cargo.toml to get the name of the shared library. |
def score(self, obs, pstates):
"""
Compute the log probability under the model.
"""
pstates_idx = np.array([self.e[p] for p in pstates])
framelogprob = self._compute_log_likelihood(obs, pstates_idx)
logprob, _ = self._do_forward_pass(framelogprob, pstates_idx)
ret... | Compute the log probability under the model. |
def request(self, url, params={}, headers={}):
"""
Retrieve SDMX messages.
If needed, override in subclasses to support other data providers.
:param url: The URL of the message.
:type url: str
:return: the xml data as file-like object
"""
# Gener... | Retrieve SDMX messages.
If needed, override in subclasses to support other data providers.
:param url: The URL of the message.
:type url: str
:return: the xml data as file-like object |
def __assert_equal(expected, returned, assert_print_result=True):
'''
Test if two objects are equal
'''
result = "Pass"
try:
if assert_print_result:
assert (expected == returned), "{0} is not equal to {1}".format(expected, returned)
else:
... | Test if two objects are equal |
def resolve_local(self, uri, base_uri, ref):
"""
Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document
"""
# read it from the filesystem
file_path = None
# make the refe... | Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document |
def features(self, expand=False):
"""Return the list of feature-value pairs in the conjunction."""
featvals = []
for term in self._terms:
if isinstance(term, AVM):
featvals.extend(term.features(expand=expand))
return featvals | Return the list of feature-value pairs in the conjunction. |
def get_snapshot_command_history(self, name, limit=20, offset=0, view=None):
"""
Retrieve a list of commands triggered by a snapshot policy.
@param name: The name of the snapshot policy.
@param limit: Maximum number of commands to retrieve.
@param offset: Index of first command to retrieve.
@pa... | Retrieve a list of commands triggered by a snapshot policy.
@param name: The name of the snapshot policy.
@param limit: Maximum number of commands to retrieve.
@param offset: Index of first command to retrieve.
@param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_reda... |
def _signed_add_overflow(state, a, b):
"""
Sign extend the value to 512 bits and check the result can be represented
in 256. Following there is a 32 bit excerpt of this condition:
a + b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff
+80000000 True... | Sign extend the value to 512 bits and check the result can be represented
in 256. Following there is a 32 bit excerpt of this condition:
a + b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff
+80000000 True True True False False False False
... |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
# check for any closed graphs
for i in range(len(self.graphs) - 1, -1, -1):
if not self.graphs[i].is_alive():
self.graphs[i].close()
self.graphs.pop(i)
# add data to the r... | handle an incoming mavlink packet |
def get(self, chargeback_id, **params):
"""Verify the chargeback ID and retrieve the chargeback from the API."""
if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid chargeback ID: '{id}'. A chargeback ID should start ... | Verify the chargeback ID and retrieve the chargeback from the API. |
def datatype2schemacls(
_datatype, _registry=None, _factory=None, _force=True,
_besteffort=True, **kwargs
):
"""Get a schema class which has been associated to input data type by the
registry or the factory in this order.
:param type datatype: data type from where get associated schema.
... | Get a schema class which has been associated to input data type by the
registry or the factory in this order.
:param type datatype: data type from where get associated schema.
:param SchemaRegisgry _registry: registry from where call the getbydatatype
. Default is the global registry.
:param Sc... |
def _print_header(data):
"""
Create vcf header to make
a valid vcf.
"""
print("##fileformat=VCFv4.2", file=STDOUT, end="")
print("##source=seqbuster2.3", file=STDOUT, end="")
print("##reference=mirbase", file=STDOUT, end="")
for pos in data:
print("##contig=<ID=%s>" % pos["chrom"... | Create vcf header to make
a valid vcf. |
def generate(self, api):
"""
Generates a module for each namespace.
Each namespace will have Python classes to represent data types and
routes in the Stone spec.
"""
rsrc_folder = os.path.join(os.path.dirname(__file__), 'python_rsrc')
self.logger.info('Copying st... | Generates a module for each namespace.
Each namespace will have Python classes to represent data types and
routes in the Stone spec. |
def order_by(self, column, direction="asc"):
"""
Add a "order by" clause to the query
:param column: The order by column
:type column: str
:param direction: The direction of the order
:type direction: str
:return: The current QueryBuilder instance
:rtyp... | Add a "order by" clause to the query
:param column: The order by column
:type column: str
:param direction: The direction of the order
:type direction: str
:return: The current QueryBuilder instance
:rtype: QueryBuilder |
def _main(self):
"""module "main" method. Only used by external modules.
:return: None
"""
self.set_proctitle(self.name)
self.set_signal_handler()
logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid())
# Will block here!
tr... | module "main" method. Only used by external modules.
:return: None |
def user_provenance(self, document): # type: (ProvDocument) -> None
"""Add the user provenance."""
self.self_check()
(username, fullname) = _whoami()
if not self.full_name:
self.full_name = fullname
document.add_namespace(UUID)
document.add_namespace(ORCID)... | Add the user provenance. |
def validate(spec, data):
"""Validates the data and creates the config objects"""
data = copy.deepcopy(data)
validated_data = {}
def validate_keys(section, config, section_data):
if not isinstance(section_data, dict) or section == spec.MODEL:
return
extra_args = [key for ke... | Validates the data and creates the config objects |
def operands(self):
"""
Return an iterator over this instruction's operands.
The iterator will yield a ValueRef for each operand.
"""
if not self.is_instruction:
raise ValueError('expected instruction value, got %s'
% (self._kind,))
... | Return an iterator over this instruction's operands.
The iterator will yield a ValueRef for each operand. |
def get_next_action(self, request, application, label, roles):
""" Process the get_next_action request at the current step. """
# if user is logged and and not applicant, steal the
# application
if 'is_applicant' in roles:
# if we got this far, then we either we are logged i... | Process the get_next_action request at the current step. |
def invalid_index(self, name):
"""Show an invalid index error message."""
self.stderr.write("Unknown index: {}".format(name))
self.stderr.write("Supported indices are:")
for index in index_builder.indexes:
self.stderr.write(" * {}".format(index.__class__.__name__)) | Show an invalid index error message. |
def _walk_modules(modules, class_name, path, ignored_formats, args):
"""
Helper generator that traverses modules in returns a flattened
iterator.
"""
for module in _iter_modules(modules=modules,
class_name=class_name,
path=path,
... | Helper generator that traverses modules in returns a flattened
iterator. |
def tunnel_settings_system_tunnel_replicator_load_balance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
tunnel_settings = ET.SubElement(config, "tunnel-settings", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
system = ET.SubElement(tunnel_settings, "sy... | Auto Generated Code |
def system_methodHelp(self, method_name: str)->str:
"""将docstring返回.
system.methodHelp('add') => "Adds two integers together"
Return:
(str): - 函数的帮助文本
"""
method = None
if method_name in self.funcs:
method = self.funcs[method_name]
elif ... | 将docstring返回.
system.methodHelp('add') => "Adds two integers together"
Return:
(str): - 函数的帮助文本 |
def ReadBytes(self, address, num_bytes):
"""Reads at most num_bytes starting from offset <address>."""
address = int(address)
buf = ctypes.create_string_buffer(num_bytes)
bytesread = ctypes.c_size_t(0)
res = ReadProcessMemory(self.h_process, address, buf, num_bytes,
ctype... | Reads at most num_bytes starting from offset <address>. |
def ReleaseFileSystem(self, file_system):
"""Releases a cached file system object.
Args:
file_system (FileSystem): file system object.
Returns:
bool: True if the file system object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if t... | Releases a cached file system object.
Args:
file_system (FileSystem): file system object.
Returns:
bool: True if the file system object can be closed.
Raises:
PathSpecError: if the path specification is incorrect.
RuntimeError: if the file system object is not cached or an inconsi... |
def servicenames(self):
"Give the list of services available in this folder."
return set([service['name'].rstrip('/').split('/')[-1]
for service in self._json_struct.get('services', [])]) | Give the list of services available in this folder. |
def process_tree(self, channel_node):
"""
Returns a list of all file names associated with a tree. Profiling suggests using a global list with `extend`
is faster than using a global set or deque.
:param channel_node: Root node of the channel being processed
:return: The list of u... | Returns a list of all file names associated with a tree. Profiling suggests using a global list with `extend`
is faster than using a global set or deque.
:param channel_node: Root node of the channel being processed
:return: The list of unique file names in `channel_node`. |
def select(self, **kws):
'''
Find all servers with indicated protocol support. Shuffled.
Filter by TOR support, and pruning level.
'''
lst = [i for i in self.values() if i.select(**kws)]
random.shuffle(lst)
return lst | Find all servers with indicated protocol support. Shuffled.
Filter by TOR support, and pruning level. |
def calculate_bidirectional_lstm_output_shapes(operator):
'''
See bidirectional LSTM's conversion function for its output shapes.
'''
check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5])
check_input_and_output_types(operator, good_input_types=[FloatTensorType... | See bidirectional LSTM's conversion function for its output shapes. |
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in e... | Read in the __exclude__ list and remove all excluded objects from the
high data |
def send(token, title, **kwargs):
"""
Site: https://boxcar.io/
API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
Desc: Best app for system administrators
"""
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "DBMail/%s" % get_version(),... | Site: https://boxcar.io/
API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
Desc: Best app for system administrators |
def _has_expired(self):
""" Has this HIT expired yet? """
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else... | Has this HIT expired yet? |
def parse_args():
"""Return parsed command-line arguments."""
threshold_choices = docutils.frontend.OptionParser.threshold_choices
parser = argparse.ArgumentParser(
description=__doc__ + (' Sphinx is enabled.'
if SPHINX_INSTALLED else ''),
prog='rstcheck')
... | Return parsed command-line arguments. |
def exec_python(attr, src, executable="python"):
"""Runs a python subproc to calculate a package attribute.
Args:
attr (str): Name of package attribute being created.
src (list of str): Python code to execute, will be converted into
semicolon-delimited single line of code.
Retu... | Runs a python subproc to calculate a package attribute.
Args:
attr (str): Name of package attribute being created.
src (list of str): Python code to execute, will be converted into
semicolon-delimited single line of code.
Returns:
str: Output of python process. |
def get(self, idx, default=None):
"""
Return the first placeholder shape with matching *idx* value, or
*default* if not found.
"""
for placeholder in self:
if placeholder.element.ph_idx == idx:
return placeholder
return default | Return the first placeholder shape with matching *idx* value, or
*default* if not found. |
def build(self, builder):
"""
Build XML by appending to builder
"""
builder.start("SourceID", {})
builder.data(self.source_id)
builder.end("SourceID") | Build XML by appending to builder |
def __nn_filter_helper(R_data, R_indices, R_ptr, S, aggregate):
'''Nearest-neighbor filter helper function.
This is an internal function, not for use outside of the decompose module.
It applies the nearest-neighbor filter to S, assuming that the first index
corresponds to observations.
Parameters... | Nearest-neighbor filter helper function.
This is an internal function, not for use outside of the decompose module.
It applies the nearest-neighbor filter to S, assuming that the first index
corresponds to observations.
Parameters
----------
R_data, R_indices, R_ptr : np.ndarrays
The ... |
def validate_is_non_abstract_vertex_type(self, vertex_classname):
"""Validate that a vertex classname corresponds to a non-abstract vertex class."""
element = self.get_vertex_schema_element_or_raise(vertex_classname)
if element.abstract:
raise InvalidClassError(u'Expected a non-abst... | Validate that a vertex classname corresponds to a non-abstract vertex class. |
def docker_version(host=None, component='server'):
""" Return the version of Docker [Server]
:param host: host or IP of the machine Docker is running on
:type host: str
:param component: Docker component
:type component: str
:return: Docker version
:rtype: str
""... | Return the version of Docker [Server]
:param host: host or IP of the machine Docker is running on
:type host: str
:param component: Docker component
:type component: str
:return: Docker version
:rtype: str |
def relation_types():
"""Get a list of relation types supported by this charm"""
rel_types = []
md = metadata()
for key in ('provides', 'requires', 'peers'):
section = md.get(key)
if section:
rel_types.extend(section.keys())
return rel_types | Get a list of relation types supported by this charm |
def get_last_result(self):
"""Read the last conversion result when in continuous conversion mode.
Will return a signed integer value.
"""
# Retrieve the conversion register value, convert to a signed int, and
# return it.
result = self._device.readList(ADS1x15_POINTER_CON... | Read the last conversion result when in continuous conversion mode.
Will return a signed integer value. |
def copy_value(self, orig_key, new_key):
"""Copy value"""
data = self.model.get_data()
if isinstance(data, list):
data.append(data[orig_key])
if isinstance(data, set):
data.add(data[orig_key])
else:
data[new_key] = data[orig_key]
... | Copy value |
def beacon(config):
'''
Scan for the configured services and fire events
Example Config
.. code-block:: yaml
beacons:
service:
- services:
salt-master: {}
mysql: {}
The config above sets up beacons to check for
the salt-master and... | Scan for the configured services and fire events
Example Config
.. code-block:: yaml
beacons:
service:
- services:
salt-master: {}
mysql: {}
The config above sets up beacons to check for
the salt-master and mysql services.
The config... |
def sort_values(self, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
"""
Sort by the values.
Sort a Series in ascending or descending order by some
criterion.
Parameters
----------
axis : {0 or 'index'}, default... | Sort by the values.
Sort a Series in ascending or descending order by some
criterion.
Parameters
----------
axis : {0 or 'index'}, default 0
Axis to direct sorting. The value 'index' is accepted for
compatibility with DataFrame.sort_values.
ascen... |
def has_noquorum(self):
"""
less than 1/3 of the known votes are on the same block
"""
assert self.is_valid
bhs = self.blockhashes()
if not bhs or bhs[0][1] <= 1 / 3. * self.num_eligible_votes:
assert not self.has_quorum_possible
return True | less than 1/3 of the known votes are on the same block |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients (for soil amplification)
... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def _set_command_line_arguments(self, args):
"""
Set internal configuration variables according to
the input parameters
"""
Global.LOGGER.debug("setting command line arguments")
if args.VERBOSE:
Global.LOGGER.debug("verbose mode active")
Global.C... | Set internal configuration variables according to
the input parameters |
def clearReqVars(self):
""" Function clearHistVars
Clear the variables used to get history of all vars
@return RETURN: None
"""
self.errorMsg = None
self.payload = None
self.url = None
self.resp = None
self.res = None
self.method = None
... | Function clearHistVars
Clear the variables used to get history of all vars
@return RETURN: None |
def set_maxrad(self,newrad):
"""
Sets max allowed radius in populations.
Doesn't operate via the :class:`stars.Constraint`
protocol; rather just rescales the sky positions
for the background objects and recalculates
sky area, etc.
"""
if not isinstance(n... | Sets max allowed radius in populations.
Doesn't operate via the :class:`stars.Constraint`
protocol; rather just rescales the sky positions
for the background objects and recalculates
sky area, etc. |
def _cl_int_from_learner(cls, learn:Learner, ds_type:DatasetType=DatasetType.Valid, tta=False):
"Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation."
preds = learn.TTA(ds_type=ds_type, with_loss=True) if tta else learn.get_preds(ds_type=ds_type, with_l... | Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation. |
def _delete_node(self, tree, node):
""" Private function that eliminate node from tree.
Parameters
----------
tree : object
node : int
node to be eliminated from tree
Returns
-------
pruned_tree : object
"""
# Calculate gai... | Private function that eliminate node from tree.
Parameters
----------
tree : object
node : int
node to be eliminated from tree
Returns
-------
pruned_tree : object |
def running_jobs(self, exit_on_error=True):
"""Initialize multiprocessing."""
with self.handling_exceptions():
if self.using_jobs:
from concurrent.futures import ProcessPoolExecutor
try:
with ProcessPoolExecutor(self.jobs) as self.executor:... | Initialize multiprocessing. |
def datetime_to_knx(datetimeval, clock_synced_external=1):
"""Convert a Python timestamp to an 8 byte KNX time and date object"""
res = [0, 0, 0, 0, 0, 0, 0, 0]
year = datetimeval.year
if (year < 1900) or (year > 2155):
raise KNXException("Only years between 1900 and 2155 supported")
res[0]... | Convert a Python timestamp to an 8 byte KNX time and date object |
def unix(value):
"""
Convert a date, or datetime to unix timestamp
:param value:
:return:
"""
if isinstance(value, (date, builtin_datetime)):
pass
elif value < 10000000000:
value = unix2datetime(value)
else:
value = milli2datetime(value)
return str(datetime2u... | Convert a date, or datetime to unix timestamp
:param value:
:return: |
def _extract_clublog_header(self, cty_xml_filename):
"""
Extract the header of the Clublog XML File
"""
cty_header = {}
try:
with open(cty_xml_filename, "r") as cty:
raw_header = cty.readline()
cty_date = re.search("date='.+'", raw_heade... | Extract the header of the Clublog XML File |
def get_yeast_sequence(chromosome, start, end, reverse_complement=False):
'''Acquire a sequence from SGD http://www.yeastgenome.org
:param chromosome: Yeast chromosome.
:type chromosome: int
:param start: A biostart.
:type start: int
:param end: A bioend.
:type end: int
:param reverse_co... | Acquire a sequence from SGD http://www.yeastgenome.org
:param chromosome: Yeast chromosome.
:type chromosome: int
:param start: A biostart.
:type start: int
:param end: A bioend.
:type end: int
:param reverse_complement: Get the reverse complement.
:type revervse_complement: bool
:re... |
def _update_font_weight(self, font_weight):
"""Updates font weight widget
Parameters
----------
font_weight: Integer
\tButton down iif font_weight == wx.FONTWEIGHT_BOLD
"""
toggle_state = font_weight & wx.FONTWEIGHT_BOLD == wx.FONTWEIGHT_BOLD
self.Tog... | Updates font weight widget
Parameters
----------
font_weight: Integer
\tButton down iif font_weight == wx.FONTWEIGHT_BOLD |
def resolve_absolute_name(self, name):
'''
Resolve a field from an absolute name.
An absolute name is just like unix absolute path,
starts with '/' and each name component is separated by '/'.
:param name: absolute name, e.g. "/container/subcontainer/field"
:return: fiel... | Resolve a field from an absolute name.
An absolute name is just like unix absolute path,
starts with '/' and each name component is separated by '/'.
:param name: absolute name, e.g. "/container/subcontainer/field"
:return: field with this absolute name
:raises: KittyException i... |
def _clean_doc(self, doc=None):
"""Clean the doc before writing it, removing unnecessary properties and doing other operations."""
if doc is None:
doc = self.doc
resources = doc['Resources']
# We don't need these anymore because all of the data written into the package is ... | Clean the doc before writing it, removing unnecessary properties and doing other operations. |
def regrep(filename, patterns, reverse=False, terminate_on_match=False,
postprocess=str):
"""
A powerful regular expression version of grep.
Args:
filename (str): Filename to grep.
patterns (dict): A dict of patterns, e.g.,
{"energy": "energy\(sigma->0\)\s+=\s+([\d\-\... | A powerful regular expression version of grep.
Args:
filename (str): Filename to grep.
patterns (dict): A dict of patterns, e.g.,
{"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}.
reverse (bool): Read files in reverse. Defaults to false. Useful for
large files, esp... |
def convert(cls, style_dict, num_format_str=None):
"""
converts a style_dict to an xlsxwriter format dict
Parameters
----------
style_dict : style dictionary to convert
num_format_str : optional number format string
"""
# Create a XlsxWriter format objec... | converts a style_dict to an xlsxwriter format dict
Parameters
----------
style_dict : style dictionary to convert
num_format_str : optional number format string |
def get_workflow_actions_for(brain_or_object):
"""Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions.
"""
portal_type = api.get_portal_t... | Returns a list with the actions (transitions) supported by the workflows
the object pass in is bound to. Note it returns all actions, not only those
allowed for the object based on its current state and permissions. |
def is_siemens(dicom_input):
"""
Use this function to detect if a dicom series is a siemens dataset
:param dicom_input: directory with dicom files for 1 scan
"""
# read dicom header
header = dicom_input[0]
# check if manufacturer is Siemens
if 'Manufacturer' not in header or 'Modality'... | Use this function to detect if a dicom series is a siemens dataset
:param dicom_input: directory with dicom files for 1 scan |
def load_weights(self, weight_file: str) -> None:
"""
Load the pre-trained weights from the file.
"""
requires_grad = self.requires_grad
with h5py.File(cached_path(weight_file), 'r') as fin:
for i_layer, lstms in enumerate(
zip(self.forward_layers... | Load the pre-trained weights from the file. |
def get_group(self, name):
"""Get contact group by name
:param name: name of group
:type name: ``str``, ``unicode``
:rtype: ``dict`` with group data
"""
groups = self.get_groups()
for group in groups:
if group['contactgroupname'] == name:
... | Get contact group by name
:param name: name of group
:type name: ``str``, ``unicode``
:rtype: ``dict`` with group data |
def get_depth(self, update=False):
"""
:returns: the depth (level) of the node
Caches the result in the object itself to help in loops.
:param update: Updates the cached value.
"""
if self.parent_id is None:
return 1
try:
if update:
... | :returns: the depth (level) of the node
Caches the result in the object itself to help in loops.
:param update: Updates the cached value. |
def header_match(cls, header):
'''
Parse the 4-line (320-byte) library member header.
'''
mo = cls.header_re.match(header)
if mo is None:
msg = f'Expected {cls.header_re.pattern!r}, got {header!r}'
raise ValueError(msg)
return {
'name':... | Parse the 4-line (320-byte) library member header. |
def _handle_userInfo(self, data):
"""Handle user information"""
for k, v in data.items():
if k == "nick":
if v == "None":
v = "Volaphile"
setattr(self.room.user, k, v)
self.conn.enqueue_data(k, self.room.user.nick)
... | Handle user information |
def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR,
suffix='ast',
no_nt_and_u=False,
single_object=None,
all_objects=True,
data_release=None,
):
"""
Returns a list of obje... | Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field.
Default is to return only the objects corresponding to the current Data Release. |
def to_json(self):
"""
Returns the JSON representation of the space membership.
"""
result = super(SpaceMembership, self).to_json()
result.update({
'admin': self.admin,
'roles': self.roles
})
return result | Returns the JSON representation of the space membership. |
def get_revoked(self):
"""
Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tup... | Return the revocations in this certificate revocation list.
These revocations will be provided by value, not by reference.
That means it's okay to mutate them: it won't affect this CRL.
:return: The revocations in this CRL.
:rtype: :class:`tuple` of :class:`Revocation` |
def partition(pred, iterable, tolist=False):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = itertools.tee(iterable)
ifalse = six.moves.filterfalse(pred, t1)
itrue = six.moves.filter(pred, t2)
if to... | Use a predicate to partition entries into false entries and true entries |
def raw_data(self, filename):
"""Return the raw pickled data from `filename`."""
if self.debug and self.debug.should('dataio'):
self.debug.write("Reading data from %r" % (filename,))
fdata = open(filename, 'rb')
try:
data = pickle.load(fdata)
finally:
... | Return the raw pickled data from `filename`. |
def _set_fcoeport(self, v, load=False):
"""
Setter method for fcoeport, mapped from YANG variable /interface/port_channel/fcoeport (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoeport is considered as a private
method. Backends looking to populate thi... | Setter method for fcoeport, mapped from YANG variable /interface/port_channel/fcoeport (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoeport is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set... |
def getMaxPacketSize(self, endpoint):
"""
Get device's max packet size for given endpoint.
Warning: this function will not always give you the expected result.
See https://libusb.org/ticket/77 . You should instead consult the
endpoint descriptor of current configuration and alte... | Get device's max packet size for given endpoint.
Warning: this function will not always give you the expected result.
See https://libusb.org/ticket/77 . You should instead consult the
endpoint descriptor of current configuration and alternate setting. |
def and_(self, other):
"""
Creates a new compound query using the
<orb.QueryCompound.Op.And> type.
:param other <Query> || <orb.QueryCompound>
:return <orb.QueryCompound>
:sa __and__
:usage |>>> from orb... | Creates a new compound query using the
<orb.QueryCompound.Op.And> type.
:param other <Query> || <orb.QueryCompound>
:return <orb.QueryCompound>
:sa __and__
:usage |>>> from orb import Query as Q
|>>>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.