code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def room_exists(jid):
"""Checks if a MUC room exists on the server."""
def _room_exists(xmpp):
disco = xmpp.plugin['xep_0030']
try:
disco.get_info(jid)
except IqError as e:
if e.condition == 'item-not-found':
return False
raise
... | Checks if a MUC room exists on the server. |
def _fulfills_version_spec(versions, oper, desired_version,
ignore_epoch=False):
'''
Returns True if any of the installed versions match the specified version,
otherwise returns False
'''
cmp_func = __salt__.get('pkg.version_cmp')
# stripping "with_origin" dict wrapper... | Returns True if any of the installed versions match the specified version,
otherwise returns False |
def AddToFileNameTable(self, fileName, showID):
"""
Add entry to FileName table. If the file name and show id combination
already exists in the table a fatal error is raised.
Parameters
----------
fileName : string
File name.
showID : int
Show id.
"""
goodloggin... | Add entry to FileName table. If the file name and show id combination
already exists in the table a fatal error is raised.
Parameters
----------
fileName : string
File name.
showID : int
Show id. |
def _browse_body(self, search_id):
"""Return the browse XML body.
The XML is formed by adding, to the envelope of the XML returned by
``self._base_body``, the following ``Body`` part:
.. code :: xml
<s:Body>
<getMetadata xmlns="http://www.sonos.com/Services/1.1">
... | Return the browse XML body.
The XML is formed by adding, to the envelope of the XML returned by
``self._base_body``, the following ``Body`` part:
.. code :: xml
<s:Body>
<getMetadata xmlns="http://www.sonos.com/Services/1.1">
<id>root</id>
<index>... |
def parent(self):
"""
Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for
more details about the selectors.
Warnings:
Experimental method, may not be available for all drivers.
Returns:
:py:class:... | Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for
more details about the selectors.
Warnings:
Experimental method, may not be available for all drivers.
Returns:
:py:class:`UIObjectProxy <poco.proxy.UIObjectPro... |
def get_suggested_field_names(schema, graphql_type, field_name):
"""For the field name provided, determine if there are any similar field names
that may be the result of a typo."""
if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLObjectType)):
possible_field_names = list(graphql_type.field... | For the field name provided, determine if there are any similar field names
that may be the result of a typo. |
def batch_split_sentences(self, texts: List[str]) -> List[List[str]]:
"""
This method lets you take advantage of spacy's batch processing.
Default implementation is to just iterate over the texts and call ``split_sentences``.
"""
return [self.split_sentences(text) for text in tex... | This method lets you take advantage of spacy's batch processing.
Default implementation is to just iterate over the texts and call ``split_sentences``. |
def set_arg(
self, name: str,
value: str,
positional: bool = None,
before: str = None,
after: str = None,
preserve_spacing: bool = True
) -> None:
"""Set the value for `name` argument. Add it if it doesn't exist.
- Use `positional`, `before` and `afte... | Set the value for `name` argument. Add it if it doesn't exist.
- Use `positional`, `before` and `after` keyword arguments only when
adding a new argument.
- If `before` is given, ignore `after`.
- If neither `before` nor `after` are given and it's needed to add a
new argumen... |
def create(self, master_course_id, coach_email, max_students_allowed, title, modules=None):
"""
Creates a CCX
Args:
master_course_id (str): edx course id of the master course
coach_email (str): email of the user to make a coach. This user must exist on edx.
m... | Creates a CCX
Args:
master_course_id (str): edx course id of the master course
coach_email (str): email of the user to make a coach. This user must exist on edx.
max_students_allowed (int): Maximum number of students to allow in this ccx.
title (str): Title of th... |
def execute(self, eopatch):
"""
Add requested feature to this existing EOPatch.
"""
data_arr = eopatch[FeatureType.MASK]['IS_DATA']
_, height, width, _ = data_arr.shape
request = self._get_wms_request(eopatch.bbox, width, height)
request_data, = np.asarray(reque... | Add requested feature to this existing EOPatch. |
def variants(case_id):
"""Show all variants for a case."""
filters = parse_filters()
values = [value for key, value in iteritems(filters)
if not isinstance(value, dict) and key != 'skip']
is_active = any(values)
variants, nr_of_variants = app.db.variants(
case_id,
skip=... | Show all variants for a case. |
def ReadClientStartupInfo(self, client_id):
"""Reads the latest client startup record for a single client."""
history = self.startup_history.get(client_id, None)
if not history:
return None
ts = max(history)
res = rdf_client.StartupInfo.FromSerializedString(history[ts])
res.timestamp = ts... | Reads the latest client startup record for a single client. |
def wait_turns(self, turns, dt=None, *, cb=None):
"""Call ``self.engine.next_turn()`` ``n`` times, waiting ``self.turn_length`` in between
If provided, call ``cb`` when done.
:param turns: number of turns to wait
:param dt: unused, just satisfies the clock
:param cb: callback f... | Call ``self.engine.next_turn()`` ``n`` times, waiting ``self.turn_length`` in between
If provided, call ``cb`` when done.
:param turns: number of turns to wait
:param dt: unused, just satisfies the clock
:param cb: callback function to call when done, optional
:return: ``None`` |
def update_intervals(self, back=None):
'''
Return the update intervals for all of the enabled fileserver backends
which support variable update intervals.
'''
back = self.backends(back)
ret = {}
for fsb in back:
fstr = '{0}.update_intervals'.format(fsb... | Return the update intervals for all of the enabled fileserver backends
which support variable update intervals. |
def expect_column_values_to_be_decreasing(self,
column,
strictly=None,
parse_strings_as_datetimes=None,
mostly=None,
... | Expect column values to be decreasing.
By default, this expectation only works for numeric or datetime data.
When `parse_strings_as_datetimes=True`, it can also parse strings to datetimes.
If `strictly=True`, then this expectation is only satisfied if each consecutive value
is strictly... |
def collection_get_options(collection_name, **kwargs):
'''
Get collection options
Additional parameters (kwargs) may be passed, they will be proxied to http.query
CLI Example:
.. code-block:: bash
salt '*' solrcloud.collection_get_options collection_name
'''
cluster = cluster_st... | Get collection options
Additional parameters (kwargs) may be passed, they will be proxied to http.query
CLI Example:
.. code-block:: bash
salt '*' solrcloud.collection_get_options collection_name |
def length_hint(obj, default=0):
"""
Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable.
If the object supports len(), the result will be exact. Otherwise, it may
over- or under-estimate by an arbitrary amount. The result will be ... | Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an iterable.
If the object supports len(), the result will be exact. Otherwise, it may
over- or under-estimate by an arbitrary amount. The result will be an
integer >= 0. |
def _read_tags(self):
"""
Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist.
"""
tags = self._co... | Fill in the _tags dict from the tags file.
Args:
None
Returns:
True
Todo:
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist. |
def _maybe_assert_valid_sample(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return counts
counts = distribution_util.embed_check_nonnegative_integer_form(counts)
return distribution_util.with_dependencies([
assert_util.a... | Check counts for proper shape, values, then return tensor version. |
def _finalize_sv(solution_file, data):
"""Add output files from TitanCNA calling optional solution.
"""
out = {"variantcaller": "titancna"}
with open(solution_file) as in_handle:
solution = dict(zip(in_handle.readline().strip("\r\n").split("\t"),
in_handle.readline().... | Add output files from TitanCNA calling optional solution. |
def background(im, size, background=None, **kwargs):
"""
Add borders of a certain color to make the resized image fit exactly within
the dimensions given.
background
Background color to use
"""
if not background:
# Primary option not given, nothing to do.
return im
i... | Add borders of a certain color to make the resized image fit exactly within
the dimensions given.
background
Background color to use |
def gradient(self, mu, dist):
"""
derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n
"""
return dist.levels/(mu*(dist.le... | derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n |
def char_groups(self, t, i):
"""Handle character groups."""
current = []
pos = i.index - 1
found = False
escaped = False
first = None
found_property = False
self.found_property = False
self.found_named_unicode = False
try:
whi... | Handle character groups. |
def waitOrTerminate(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL, terminateToKillSeconds=SUBPROCESS2_DEFAULT_TERMINATE_TO_KILL_SECONDS):
'''
waitOrTerminate - Wait up to a certain number of seconds for the process to end.
If the process is running after the timeout has been exceeded... | waitOrTerminate - Wait up to a certain number of seconds for the process to end.
If the process is running after the timeout has been exceeded, a SIGTERM will be sent.
Optionally, an additional SIGKILL can be sent after some configurable interval. See #terminateToKillSeconds doc below
... |
def html_body(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=1, initial_header_level=1):
"""
Given an input string, returns an HTML fragment as a string.
The return value is the contents of the <body> element.
Parameters (see `html_parts()` for ... | Given an input string, returns an HTML fragment as a string.
The return value is the contents of the <body> element.
Parameters (see `html_parts()` for the remainder):
- `output_encoding`: The desired encoding of the output. If a Unicode
string is desired, use the default value of "unicode" . |
def get(self, file_id: Union[str, bson.ObjectId]) -> [typing.BinaryIO, str, datetime.datetime]:
"""
Return the file identified by a file_id string.
The return value is a file-like object which also has the following attributes:
filename: str
upload_date: datetime
"""
... | Return the file identified by a file_id string.
The return value is a file-like object which also has the following attributes:
filename: str
upload_date: datetime |
def get_active_clients():
"""Get a list of all active clients and their status"""
global drivers
if not drivers:
return jsonify([])
result = {client: get_client_info(client) for client in drivers}
return jsonify(result) | Get a list of all active clients and their status |
def cmd_string(name, cmd):
# type: (AName, ACmd) -> ADefine
"""Define a string parameter coming from a shell command to be used within
this YAML file. Trailing newlines will be stripped."""
value = subprocess.check_output(cmd, shell=True).rstrip("\n")
return Define(name, value) | Define a string parameter coming from a shell command to be used within
this YAML file. Trailing newlines will be stripped. |
def parse_datetime(datetime_input):
"""The arrow library is sadly not good enough to parse
certain date strings. It even gives unexpected results for partial
date strings such as '2015-01' or just '2015', which I think
should be seen as 'the first moment of 2014'.
This function should overcome those... | The arrow library is sadly not good enough to parse
certain date strings. It even gives unexpected results for partial
date strings such as '2015-01' or just '2015', which I think
should be seen as 'the first moment of 2014'.
This function should overcome those limitations. |
def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF File Entry.
Parameters:
None.
Returns:
A string representing this UDF File Entry.
'''
if not self._initialized:
raise pycdlibexception.Py... | A method to generate the string representing this UDF File Entry.
Parameters:
None.
Returns:
A string representing this UDF File Entry. |
def get_image_dimension(bbox, width=None, height=None):
""" Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height ... | Given bounding box and one of the parameters width or height it will return the other parameter that will best
fit the bounding box dimensions
:param bbox: bounding box
:type bbox: geometry.BBox
:param width: image width or None if height is unknown
:type width: int or None
:param height: image... |
def download_annotation(genomebuild, gene_file):
"""
Download gene annotation from UCSC based on genomebuild.
Will check UCSC, Ensembl and RefSeq annotation.
Parameters
----------
genomebuild : str
UCSC genome name.
gene_file : str
Output file name.
"""
pred_bin = ... | Download gene annotation from UCSC based on genomebuild.
Will check UCSC, Ensembl and RefSeq annotation.
Parameters
----------
genomebuild : str
UCSC genome name.
gene_file : str
Output file name. |
def files_in_to_out(self, in_path, out_path=None):
"""Write in files to out, calling the line_handler on each line.
Calls file_in_to_out under the hood to format the in_path payload. The
formatting processing is done by the self.formatter instance.
Args:
in_path: str, path-... | Write in files to out, calling the line_handler on each line.
Calls file_in_to_out under the hood to format the in_path payload. The
formatting processing is done by the self.formatter instance.
Args:
in_path: str, path-like, or an iterable (list/tuple) of
stri... |
def warning(self, message, *args, **kwargs):
"""
Specialized warnings system. If a warning subclass is passed into
the keyword arguments and raise_warnings is True - the warnning will
be passed to the warnings module.
"""
warncls = kwargs.pop('warning', None)
if w... | Specialized warnings system. If a warning subclass is passed into
the keyword arguments and raise_warnings is True - the warnning will
be passed to the warnings module. |
def apply(self, x):
"""Apply Householder transformation to vector x.
Applies the Householder transformation efficiently to the given vector.
"""
# make sure that x is a (N,*) matrix
if len(x.shape) != 2:
raise ArgumentError('x is not a matrix of shape (N,*)')
... | Apply Householder transformation to vector x.
Applies the Householder transformation efficiently to the given vector. |
def _get_upsert_fields(self, kwargs):
"""Gets the fields to use in an upsert.
This some nice magic. We'll split the fields into
a group of "insert fields" and "update fields":
INSERT INTO bla ("val1", "val2") ON CONFLICT DO UPDATE SET val1 = EXCLUDED.val1
^^^^... | Gets the fields to use in an upsert.
This some nice magic. We'll split the fields into
a group of "insert fields" and "update fields":
INSERT INTO bla ("val1", "val2") ON CONFLICT DO UPDATE SET val1 = EXCLUDED.val1
^^^^^^^^^^^^^^ ^^^^^^^^^^^... |
def update_security_of_project(self, ID, data):
"""Update security of project."""
# http://teampasswordmanager.com/docs/api-projects/#update_project_security
log.info('Update project %s security %s' % (ID, data))
self.put('projects/%s/security.json' % ID, data) | Update security of project. |
def select_profile(self, obresult):
"""Select instrument profile based on OB"""
logger = logging.getLogger(__name__)
logger.debug('calling default profile selector')
# check configuration
insconf = obresult.configuration
if insconf != 'default':
key = insconf... | Select instrument profile based on OB |
def create(cls, bootstrap_options):
"""
:param Options bootstrap_options: The bootstrap options bag.
"""
binary_tool_fetcher = BinaryToolFetcher(
bootstrap_dir=bootstrap_options.pants_bootstrapdir,
timeout_secs=bootstrap_options.binaries_fetch_timeout_secs)
binary_util = BinaryUtil(
... | :param Options bootstrap_options: The bootstrap options bag. |
def new_config():
"""Prompt user for config variables and generate new config.
Returns: A new ConfigDict.
"""
config = ConfigDict()
config["module-path"] = qprompt.ask_str(
"Top-level module path",
blk=False,
vld=os.path.exists,
hlp=MODULE_PATH_HELP)
python_vers... | Prompt user for config variables and generate new config.
Returns: A new ConfigDict. |
def pressKeyCode(self, keycode, metaState=0):
'''By default no meta state'''
if self.uiAutomatorHelper:
if DEBUG_UI_AUTOMATOR_HELPER:
print >> sys.stderr, "pressKeyCode(%d, %d)" % (keycode, metaState)
self.uiAutomatorHelper.pressKeyCode(keycode, metaState)
... | By default no meta state |
def get_nodes(graph: BELGraph, node_predicates: NodePredicates) -> Set[BaseEntity]:
"""Get the set of all nodes that pass the predicates."""
return set(filter_nodes(graph, node_predicates=node_predicates)) | Get the set of all nodes that pass the predicates. |
def proc_val(key, val):
"""
Static helper method to convert PWINPUT parameters to proper type, e.g.,
integers, floats, etc.
Args:
key: PWINPUT parameter key
val: Actual value of PWINPUT parameter.
"""
float_keys = ('etot_conv_thr','forc_conv_thr',... | Static helper method to convert PWINPUT parameters to proper type, e.g.,
integers, floats, etc.
Args:
key: PWINPUT parameter key
val: Actual value of PWINPUT parameter. |
def splitpreserve(s,redelim=r'\s'):
'split, but preserves the delimiter so the string can be reassembled with double-spaces (etc) intact'
pattern='[^%s]*%s*'%(redelim,redelim)
return re.findall(pattern,s) | split, but preserves the delimiter so the string can be reassembled with double-spaces (etc) intact |
def parse_doc_tree(self, doctree, pypackages):
"""Parse the given documentation tree.
:param str doctree: The absolute path to the documentation tree which is to be parsed.
:param set pypackages: A set of all Python packages found in the pytree.
:rtype: dict
:returns: A dict whe... | Parse the given documentation tree.
:param str doctree: The absolute path to the documentation tree which is to be parsed.
:param set pypackages: A set of all Python packages found in the pytree.
:rtype: dict
:returns: A dict where each key is the path of an expected Python module and i... |
def AstroDrizzle(input=None, mdriztab=False, editpars=False, configobj=None,
wcsmap=None, **input_dict):
""" AstroDrizzle command-line interface """
# Support input of filenames from command-line without a parameter name
# then copy this into input_dict for merging with TEAL ConfigObj
#... | AstroDrizzle command-line interface |
def run(self):
"""Run flux variability command"""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
reaction = self._get_objective()
... | Run flux variability command |
def run(self):
"""Run when button is pressed."""
inside = 0
for draws in range(1, self.data['samples']):
# generate points and check whether they are inside the unit circle
r1, r2 = (random(), random())
if r1 ** 2 + r2 ** 2 < 1.0:
inside += 1
... | Run when button is pressed. |
def check_tools(cls):
"""
Check whether ``aeneas.tools.*`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.tools.convert_syncmap import ConvertSyncMapCLI
# disabling this check, as it requir... | Check whether ``aeneas.tools.*`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool |
def get_conn(self, aws_access_key=None, aws_secret_key=None):
'''
Hook point for overriding how the CounterPool gets its connection to
AWS.
'''
return boto.connect_dynamodb(
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
) | Hook point for overriding how the CounterPool gets its connection to
AWS. |
def seed_rngs(seed: int) -> None:
"""
Seed the random number generators (Python, Numpy and MXNet)
:param seed: The random seed.
"""
np.random.seed(seed)
random.seed(seed)
mx.random.seed(seed) | Seed the random number generators (Python, Numpy and MXNet)
:param seed: The random seed. |
def _GetFieldByName(message_descriptor, field_name):
"""Returns a field descriptor by field name.
Args:
message_descriptor: A Descriptor describing all fields in message.
field_name: The name of the field to retrieve.
Returns:
The field descriptor associated with the field name.
"""
try:
retu... | Returns a field descriptor by field name.
Args:
message_descriptor: A Descriptor describing all fields in message.
field_name: The name of the field to retrieve.
Returns:
The field descriptor associated with the field name. |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
mode = self.actual_arguments[0]
validator = Validator(rconf=self.rconf, logger=self.logge... | Perform command and return the appropriate exit code.
:rtype: int |
def _resize(self):
'''calculate and set text size, handling multi-line'''
lines = self.text.split('\n')
xsize, ysize = 0, 0
for line in lines:
size = self.textctrl.GetTextExtent(line)
xsize = max(xsize, size[0])
ysize = ysize + size[1]
xsize = ... | calculate and set text size, handling multi-line |
def addWatchedDirectory(self, dirname, watching=Purr.WATCHED, save_config=True):
"""Starts watching the specified directories for changes"""
# see if we're alredy watching this exact set of directories -- do nothing if so
dirname = Purr.canonizePath(dirname)
# do nothing if already watch... | Starts watching the specified directories for changes |
def _one_cycle_mult(areg, breg, rem_bits, sum_sf=0, curr_bit=0):
""" returns a WireVector sum of rem_bits multiplies (in one clock cycle)
note: this method requires a lot of area because of the indexing in the else statement """
if rem_bits == 0:
return sum_sf
else:
a_curr_val = areg[cur... | returns a WireVector sum of rem_bits multiplies (in one clock cycle)
note: this method requires a lot of area because of the indexing in the else statement |
def superReadFile(filepath, **kwargs):
"""
Uses pandas.read_excel (on excel files) and returns a dataframe of the
first sheet (unless sheet is specified in kwargs)
Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of
the data. One function to read almost all types of data file... | Uses pandas.read_excel (on excel files) and returns a dataframe of the
first sheet (unless sheet is specified in kwargs)
Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of
the data. One function to read almost all types of data files. |
def result_for_solid(self, name):
'''Get a :py:class:`SolidExecutionResult` for a given solid name.
'''
check.str_param(name, 'name')
if not self.pipeline.has_solid(name):
raise DagsterInvariantViolationError(
'Try to get result for solid {name} in {pipeline}... | Get a :py:class:`SolidExecutionResult` for a given solid name. |
def apply_model(refwcs):
""" Apply distortion model to WCS, including modifying
CD with linear distortion terms
"""
# apply distortion model to CD matrix
if 'ocx10' in refwcs.__dict__ and refwcs.ocx10 is not None:
linmat = np.array([[refwcs.ocx11,refwcs.ocx10],[refwcs.ocy11,refwcs.ocy10... | Apply distortion model to WCS, including modifying
CD with linear distortion terms |
def get_creation_fakes_migrations():
"""
If TENANT_CREATION_FAKES_MIGRATIONS, tenants will be created by cloning an
existing schema specified by TENANT_CLONE_BASE.
"""
faked = getattr(settings, 'TENANT_CREATION_FAKES_MIGRATIONS', False)
if faked:
if not getattr(settings, 'TENANT_BASE_SCH... | If TENANT_CREATION_FAKES_MIGRATIONS, tenants will be created by cloning an
existing schema specified by TENANT_CLONE_BASE. |
def _qnwgamma1(n, a=1.0, b=1.0, tol=3e-14):
"""
1d quadrature weights and nodes for Gamma distributed random variable
Parameters
----------
n : scalar : int
The number of quadrature points
a : scalar : float, optional(default=1.0)
Shape parameter of the gamma distribution param... | 1d quadrature weights and nodes for Gamma distributed random variable
Parameters
----------
n : scalar : int
The number of quadrature points
a : scalar : float, optional(default=1.0)
Shape parameter of the gamma distribution parameter. Must be positive
b : scalar : float, optional... |
def jacobi(a, b):
'''Calculates the value of the Jacobi symbol (a/b) where both a and b are
positive integers, and b is odd
:returns: -1, 0 or 1
'''
assert a > 0
assert b > 0
if a == 0:
return 0
result = 1
while a > 1:
if a & 1:
if ((a-1)*(b-1) >> 2) & ... | Calculates the value of the Jacobi symbol (a/b) where both a and b are
positive integers, and b is odd
:returns: -1, 0 or 1 |
def get_redirect_args(self, request, callback):
"""Get request parameters for redirect url."""
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
scope ... | Get request parameters for redirect url. |
def jsend_output(fail_exception_classes=None):
"""
Format task result to json output in jsend specification format. See:
https://github.com/omniti-labs. Task return value must be dict or None.
@param fail_exception_classes: exceptions which will produce 'fail' response
status.
"""
fail_exc... | Format task result to json output in jsend specification format. See:
https://github.com/omniti-labs. Task return value must be dict or None.
@param fail_exception_classes: exceptions which will produce 'fail' response
status. |
def __name_unit_regex(word):
"""
Split a name and unit that are bunched together (i.e. '250m')
:param str word:
:return str str:
"""
value = ""
unit = ""
r = re.findall(re_name_unit, word)
try:
value = r[0][0]
except IndexError ... | Split a name and unit that are bunched together (i.e. '250m')
:param str word:
:return str str: |
def get_file(self, user, handle):
"""Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle.
"""
user_dir = self.user_dir(user)
if not user_dir.exists():
return None
if... | Retrieve a file for a user.
:returns: a :class:`pathlib.Path` instance to this file,
or None if no file can be found for this handle. |
def memoize(function):
"""A very simple memoize decorator to optimize pure-ish functions
Don't use this unless you've examined the code and see the
potential risks.
"""
cache = {}
@functools.wraps(function)
def _memoize(*args):
if args in cache:
return cache[args]
... | A very simple memoize decorator to optimize pure-ish functions
Don't use this unless you've examined the code and see the
potential risks. |
def state_argspec(module=''):
'''
Return the argument specification of functions in Salt state
modules.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.state_argspec pkg.installed
salt '*' sys.state_argspec file
salt '*' sys.state_argspec
... | Return the argument specification of functions in Salt state
modules.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' sys.state_argspec pkg.installed
salt '*' sys.state_argspec file
salt '*' sys.state_argspec
State names can be specified as globs.
... |
def close(self):
"""Closes the java driver if started by this client. No-op otherwise."""
if self._proc is not None:
self._proc.stdin.close()
self._proc.wait() | Closes the java driver if started by this client. No-op otherwise. |
def auto_start_vm(self):
"""
Auto start the GNS3 VM if require
"""
if self.enable:
try:
yield from self.start()
except GNS3VMError as e:
# User will receive the error later when they will try to use the node
try:
... | Auto start the GNS3 VM if require |
def which(program):
"""
Find a program in PATH and return path
From: http://stackoverflow.com/q/377017/
"""
def is_exe(fpath):
found = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
if not found and sys.platform == 'win32':
fpath = fpath + ".exe"
found = ... | Find a program in PATH and return path
From: http://stackoverflow.com/q/377017/ |
def get_installed_integration(self, **kwargs): # noqa: E501
"""Gets a flat list of all Integrations that are installed, along with their status # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_... | Gets a flat list of all Integrations that are installed, along with their status # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_installed_integration(async_req=Tr... |
def organization_requests(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/requests#list-requests"
api_path = "/api/v2/organizations/{id}/requests.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/requests#list-requests |
def setup_observations(self):
""" main entry point for setting up observations
"""
obs_methods = [self.setup_water_budget_obs,self.setup_hyd,
self.setup_smp,self.setup_hob,self.setup_hds,
self.setup_sfr_obs]
obs_types = ["mflist water budget... | main entry point for setting up observations |
def jacobian(self, maps):
"""Returns the Jacobian for transforming mchirp and eta to mass1 and
mass2.
"""
mchirp = maps[parameters.mchirp]
eta = maps[parameters.eta]
m1 = conversions.mass1_from_mchirp_eta(mchirp, eta)
m2 = conversions.mass2_from_mchirp_eta(mchirp,... | Returns the Jacobian for transforming mchirp and eta to mass1 and
mass2. |
def run_sync(self, func, timeout=None):
"""Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either a yieldable object or
``None``. If the function returns a yieldable object, the
`IOLoop` will run until the yieldable is resolved (and
`ru... | Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either a yieldable object or
``None``. If the function returns a yieldable object, the
`IOLoop` will run until the yieldable is resolved (and
`run_sync()` will return the yieldable's result). If i... |
def to_local_time(timestamp):
"""Convert a datatime object from UTC time to local time.
Adopted from:
http://stackoverflow.com/questions/4770297/python-convert-utc-datetime-string-to-local-datetime
Parameters
----------
timestamp : string
Default string representation of timestamps exp... | Convert a datatime object from UTC time to local time.
Adopted from:
http://stackoverflow.com/questions/4770297/python-convert-utc-datetime-string-to-local-datetime
Parameters
----------
timestamp : string
Default string representation of timestamps expected to be in
UTC time zone
... |
def split(self, granularity_after_split, exclude_partial=True):
"""
Split a period into a given granularity. Optionally include partial
periods at the start and end of the period.
"""
if granularity_after_split == Granularity.DAY:
return self.get_days()
elif... | Split a period into a given granularity. Optionally include partial
periods at the start and end of the period. |
def create_was_derived_from_relation(self, used_entity_id, used_entity_kind,
generated_entity_id, generated_entity_kind):
"""
Create a was derived from relation.
:param used_entity_id: str: uuid of the used entity (file_version_id)
:param used_ent... | Create a was derived from relation.
:param used_entity_id: str: uuid of the used entity (file_version_id)
:param used_entity_kind: str: kind of entity ('dds-file')
:param generated_entity_id: uuid of the generated entity (file_version_id)
:param generated_entity_kind: str: kind of entity... |
def psit(t, x, xf):
""" A function of t, X_t and X_{t+1} (f=future) """
if t == 0:
return psi0(x) + psit(1, x, xf)
else:
return -0.5 / sigma0**2 + (0.5 / sigma0**4) * ((xf - mu0) -
phi0 * (x - mu0))**2 | A function of t, X_t and X_{t+1} (f=future) |
def generate_packer_filename(provider, region, builder):
"""Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated filenam... | Generate a filename to be used by packer.
Args:
provider (str): Name of Spinnaker provider.
region (str): Name of provider region to use.
builder (str): Name of builder process type.
Returns:
str: Generated filename based on parameters. |
def chi_square(h1, h2): # 23 us @array, 49 us @list \w 100
r"""
Chi-square distance.
Measure how unlikely it is that one distribution (histogram) was drawn from the
other. The Chi-square distance between two histograms :math:`H` and :math:`H'` of size
:math:`m` is defined as:
.. math::... | r"""
Chi-square distance.
Measure how unlikely it is that one distribution (histogram) was drawn from the
other. The Chi-square distance between two histograms :math:`H` and :math:`H'` of size
:math:`m` is defined as:
.. math::
d_{\chi^2}(H, H') = \sum_{m=1}^M
\fra... |
def add_torrent_task(self, torrent_path, save_path='/', selected_idx=(), **kwargs):
"""
添加本地BT任务
:param torrent_path: 本地种子的路径
:param save_path: 远程保存路径
:param selected_idx: 要下载的文件序号 —— 集合为空下载所有,非空集合指定序号集合,空串下载默认
:return: requests.Response
.. note::
... | 添加本地BT任务
:param torrent_path: 本地种子的路径
:param save_path: 远程保存路径
:param selected_idx: 要下载的文件序号 —— 集合为空下载所有,非空集合指定序号集合,空串下载默认
:return: requests.Response
.. note::
返回正确时返回的 Reponse 对象 content 中的数据结构
{"task_id":任务编号,"rapid_download":是否已经完成(急速下... |
def quote_xml(inStr):
"Escape markup chars, but do not modify CDATA sections."
if not inStr:
return ''
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
s2 = ''
pos = 0
matchobjects = CDATA_pattern_.finditer(s1)
for mo in matchobjects:
s3 = s1[pos:mo.start()]
... | Escape markup chars, but do not modify CDATA sections. |
def dslice(value, *args):
"""Returns a 'slice' of the given dictionary value containing only the
requested keys. The keys can be requested in a variety of ways, as an
arg list of keys, as a list of keys, or as a dict whose key(s) represent
the source keys and whose corresponding values represen... | Returns a 'slice' of the given dictionary value containing only the
requested keys. The keys can be requested in a variety of ways, as an
arg list of keys, as a list of keys, or as a dict whose key(s) represent
the source keys and whose corresponding values represent the resulting
key(s) (e... |
def stmts_to_json(stmts_in, use_sbo=False):
"""Return the JSON-serialized form of one or more INDRA Statements.
Parameters
----------
stmts_in : Statement or list[Statement]
A Statement or list of Statement objects to serialize into JSON.
use_sbo : Optional[bool]
If True, SBO annota... | Return the JSON-serialized form of one or more INDRA Statements.
Parameters
----------
stmts_in : Statement or list[Statement]
A Statement or list of Statement objects to serialize into JSON.
use_sbo : Optional[bool]
If True, SBO annotations are added to each applicable element of the
... |
def DbGetDeviceServerClassList(self, argin):
""" Get list of Tango classes for a device server
:param argin: device server process name
:type: tango.DevString
:return: list of classes for this device server
:rtype: tango.DevVarStringArray """
self._log.debug("In DbGetDev... | Get list of Tango classes for a device server
:param argin: device server process name
:type: tango.DevString
:return: list of classes for this device server
:rtype: tango.DevVarStringArray |
def bleu(candidate, references, weights):
"""
Calculate BLEU for a single sentence, comment by atma
The result of this code is same as the most popular perl script
eg:
weight = [0.25, 0.25, 0.25, 0.25]
can = 'It is a guide to action which ensures that the military always obeys the comman... | Calculate BLEU for a single sentence, comment by atma
The result of this code is same as the most popular perl script
eg:
weight = [0.25, 0.25, 0.25, 0.25]
can = 'It is a guide to action which ensures that the military always obeys the commands of the party'.lower().split()
ref1 = 'It is... |
def displ_single(self, g_num, at_1, at_2):
""" Displacement vector between two atoms.
Returns the displacement vector pointing from `at_1`
toward `at_2` from geometry `g_num`.
If `at_1` == `at_2` a strict zero vector is returned.
Displacement vector is returned in units of Bohr... | Displacement vector between two atoms.
Returns the displacement vector pointing from `at_1`
toward `at_2` from geometry `g_num`.
If `at_1` == `at_2` a strict zero vector is returned.
Displacement vector is returned in units of Bohrs.
Parameters
----------
g_num... |
def _get_path_infomation(self):
"""Get useful infomation from the device path."""
long_identifier = self._device_path.split('/')[4]
protocol, remainder = long_identifier.split('-', 1)
identifier, _, device_type = remainder.rsplit('-', 2)
return (protocol, identifier, device_type) | Get useful infomation from the device path. |
def find_n_pc(u, factor=0.5):
"""Find number of principal components
This method finds the minimum number of principal components required
Parameters
----------
u : np.ndarray
Left singular vector of the original data
factor : float, optional
Factor for testing the auto correla... | Find number of principal components
This method finds the minimum number of principal components required
Parameters
----------
u : np.ndarray
Left singular vector of the original data
factor : float, optional
Factor for testing the auto correlation (default is '0.5')
Returns
... |
def pop_choice(self, key: str, choices: List[Any], default_to_first_choice: bool = False) -> Any:
"""
Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of
the given choices. Note that this `pops` the key from params, modifying the dictionary,
consiste... | Gets the value of ``key`` in the ``params`` dictionary, ensuring that the value is one of
the given choices. Note that this `pops` the key from params, modifying the dictionary,
consistent with how parameters are processed in this codebase.
Parameters
----------
key: str
... |
def create_grad(node, namer, tangent=False):
"""Given a variable, create a variable for the gradient.
Args:
node: A node to create a gradient for, can be a normal variable (`x`) or a
subscript (`x[i]`).
namer: The namer object which will determine the name to use for the
gradient.
tange... | Given a variable, create a variable for the gradient.
Args:
node: A node to create a gradient for, can be a normal variable (`x`) or a
subscript (`x[i]`).
namer: The namer object which will determine the name to use for the
gradient.
tangent: Whether a tangent (instead of adjoint) is crea... |
def report(self, morfs, directory=None):
"""Run the report.
See `coverage.report()` for arguments.
"""
self.report_files(self.annotate_file, morfs, directory) | Run the report.
See `coverage.report()` for arguments. |
def clean_tuple(t0, clean_item_fn=None):
"""
Return a json-clean tuple. Will log info message for failures.
"""
clean_item_fn = clean_item_fn if clean_item_fn else clean_item
l = list()
for index, item in enumerate(t0):
cleaned_item = clean_item_fn(item)
l.append(cleaned_item... | Return a json-clean tuple. Will log info message for failures. |
def set_index(self, index):
"""Display the data of the given index
:param index: the index to paint
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None
"""
self.index = index
self.reftrack = index.model().index(index.row(), 1... | Display the data of the given index
:param index: the index to paint
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None |
def getBase(self, doc):
"""Searches for the BASE URL. The code should work on both XML
and HTML document even if base mechanisms are completely
different. It returns the base as defined in RFC 2396
sections 5.1.1. Base URI within Document Content and 5.1.2.
Base URI from ... | Searches for the BASE URL. The code should work on both XML
and HTML document even if base mechanisms are completely
different. It returns the base as defined in RFC 2396
sections 5.1.1. Base URI within Document Content and 5.1.2.
Base URI from the Encapsulating Entity However it... |
def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None):
"""Check to see if the units contain E&M units
This function supports unyt's ability to convert data to and from E&M
electromagnetic units. However, this support is limited and only very
simple unit expressions can be readil... | Check to see if the units contain E&M units
This function supports unyt's ability to convert data to and from E&M
electromagnetic units. However, this support is limited and only very
simple unit expressions can be readily converted. This function tries
to see if the unit is an atomic base unit that is... |
def generate_menu(self, ass, text, path=None, level=0):
"""
Function generates menu from based on ass parameter
"""
menu = self.create_menu()
for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())):
if index != 0:
text += "|"
... | Function generates menu from based on ass parameter |
def _rate_limited():
"""A rate limit decorator for limiting the number of times the
decorated :class:`Miner` method can be called. Limits are set in
:attr:`Miner._max_per_second`.
"""
def decorate(func):
def rate_limited_func(self, *args, **kwargs):
el... | A rate limit decorator for limiting the number of times the
decorated :class:`Miner` method can be called. Limits are set in
:attr:`Miner._max_per_second`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.