code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def setValidityErrorHandler(self, err_func, warn_func, arg=None):
"""
Register error and warning handlers for DTD validation.
These will be called back as f(msg,arg)
"""
libxml2mod.xmlSetValidErrors(self._o, err_func, warn_func, arg) | Register error and warning handlers for DTD validation.
These will be called back as f(msg,arg) |
def get_parent_path(index=2): # type: (int) -> str
"""
Get the caller's parent path to sys.path
If the caller is a CLI through stdin, the parent of the current working
directory is used
"""
try:
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
path = os... | Get the caller's parent path to sys.path
If the caller is a CLI through stdin, the parent of the current working
directory is used |
def match_in(grammar, text):
"""Determine if there is a match for grammar in text."""
for result in grammar.parseWithTabs().scanString(text):
return True
return False | Determine if there is a match for grammar in text. |
def process_request(self, request, response):
"""Logs the basic endpoint requested"""
self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type)) | Logs the basic endpoint requested |
def get_headers_from_environ(environ):
"""Get a wsgiref.headers.Headers object with headers from the environment.
Headers in environ are prefixed with 'HTTP_', are all uppercase, and have
had dashes replaced with underscores. This strips the HTTP_ prefix and
changes underscores back to dashes before adding th... | Get a wsgiref.headers.Headers object with headers from the environment.
Headers in environ are prefixed with 'HTTP_', are all uppercase, and have
had dashes replaced with underscores. This strips the HTTP_ prefix and
changes underscores back to dashes before adding them to the returned set
of headers.
Args... |
def cancel_task(all, task_id):
"""
Executor for `globus task cancel`
"""
if bool(all) + bool(task_id) != 1:
raise click.UsageError(
"You must pass EITHER the special --all flag "
"to cancel all in-progress tasks OR a single "
"task ID to cancel."
)
... | Executor for `globus task cancel` |
def zero_year_special_case(from_date, to_date, start, end):
"""strptime does not resolve a 0000 year, we must handle this."""
if start == 'pos' and end == 'pos':
# always interval from earlier to later
if from_date.startswith('0000') and not to_date.startswith('0000'):
return True
... | strptime does not resolve a 0000 year, we must handle this. |
def params(self, **kwargs):
"""
Specify query params to be used when executing the search. All the
keyword arguments will override the current values. See
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search
for all available parameters.
... | Specify query params to be used when executing the search. All the
keyword arguments will override the current values. See
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search
for all available parameters.
Example::
s = Search()
... |
def get_key_value_pairs(self, subsystem, filename):
"""
Read the lines of the given file from the given subsystem
and split the lines into key-value pairs.
Do not include the subsystem name in the option name.
Only call this method if the given subsystem is available.
"""... | Read the lines of the given file from the given subsystem
and split the lines into key-value pairs.
Do not include the subsystem name in the option name.
Only call this method if the given subsystem is available. |
def get_item(self, key):
"""
Returns the value associated with the key.
"""
keys = list(self.keys())
# make sure it exists
if not key in keys:
self.print_message("ERROR: '"+str(key)+"' not found.")
return None
try:
x = eval(se... | Returns the value associated with the key. |
def cli_aliases(self):
r"""Developer script aliases.
"""
scripting_groups = []
aliases = {}
for cli_class in self.cli_classes:
instance = cli_class()
if getattr(instance, "alias", None):
scripting_group = getattr(instance, "scripting_group"... | r"""Developer script aliases. |
def author_to_dict(obj):
"""Who needs a switch/case statement when you can instead use this easy to
comprehend drivel?
"""
def default():
raise RuntimeError("unsupported type {t}".format(t=type(obj).__name__))
# a more pythonic way to handle this would be several try blocks to catch
# m... | Who needs a switch/case statement when you can instead use this easy to
comprehend drivel? |
def make_number(value, lineno, type_=None):
""" Wrapper: creates a constant number node.
"""
return symbols.NUMBER(value, type_=type_, lineno=lineno) | Wrapper: creates a constant number node. |
def model(x_train, y_train, x_test, y_test):
"""Model providing function:
Create Keras model with double curly brackets dropped-in as needed.
Return value has to be a valid python dictionary with two customary keys:
- loss: Specify a numeric evaluation metric to be minimized
- status: Just ... | Model providing function:
Create Keras model with double curly brackets dropped-in as needed.
Return value has to be a valid python dictionary with two customary keys:
- loss: Specify a numeric evaluation metric to be minimized
- status: Just use STATUS_OK and see hyperopt documentation if not ... |
def average_colors(c1, c2):
''' Average the values of two colors together '''
r = int((c1[0] + c2[0])/2)
g = int((c1[1] + c2[1])/2)
b = int((c1[2] + c2[2])/2)
return (r, g, b) | Average the values of two colors together |
def get_font_glyph_data(font):
"""Return information for each glyph in a font"""
from fontbakery.constants import (PlatformID,
WindowsEncodingID)
font_data = []
try:
subtable = font['cmap'].getcmap(PlatformID.WINDOWS,
... | Return information for each glyph in a font |
def populate(self, source=DEFAULT_SEGMENT_SERVER,
segments=None, pad=True, on_error='raise', **kwargs):
"""Query the segment database for each flag's active segments.
This method assumes all of the metadata for each flag have been
filled. Minimally, the following attributes mus... | Query the segment database for each flag's active segments.
This method assumes all of the metadata for each flag have been
filled. Minimally, the following attributes must be filled
.. autosummary::
~DataQualityFlag.name
~DataQualityFlag.known
Segments will be ... |
def _have_conf(self, magic_hash=None):
"""Get the daemon current configuration state
If the daemon has received a configuration from its arbiter, this will
return True
If a `magic_hash` is provided it is compared with the one included in the
daemon configuration and this functi... | Get the daemon current configuration state
If the daemon has received a configuration from its arbiter, this will
return True
If a `magic_hash` is provided it is compared with the one included in the
daemon configuration and this function returns True only if they match!
:retu... |
def main():
"""The command line interface for the ``pip-accel`` program."""
arguments = sys.argv[1:]
# If no arguments are given, the help text of pip-accel is printed.
if not arguments:
usage()
sys.exit(0)
# If no install subcommand is given we pass the command line straight
# t... | The command line interface for the ``pip-accel`` program. |
def _build_amps_list(self, amp_value, processlist):
"""Return the AMPS process list according to the amp_value
Search application monitored processes by a regular expression
"""
ret = []
try:
# Search in both cmdline and name (for kernel thread, see #1261)
... | Return the AMPS process list according to the amp_value
Search application monitored processes by a regular expression |
def _process_thread(self, client):
"""Process a single client.
Args:
client: GRR client object to act on.
"""
file_list = self.files
if not file_list:
return
print('Filefinder to collect {0:d} items'.format(len(file_list)))
flow_action = flows_pb2.FileFinderAction(
acti... | Process a single client.
Args:
client: GRR client object to act on. |
def symlink(source, link_name):
"""
Method to allow creating symlinks on Windows
"""
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
impor... | Method to allow creating symlinks on Windows |
def current_op(self, include_all=False):
"""Get information on operations currently running.
:Parameters:
- `include_all` (optional): if ``True`` also list currently
idle operations in the result
"""
cmd = SON([("currentOp", 1), ("$all", include_all)])
with... | Get information on operations currently running.
:Parameters:
- `include_all` (optional): if ``True`` also list currently
idle operations in the result |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Implements equation 3.5.1-1 page 148 for mean value and equation
3.5.5-2 page 151 for total standard deviation.
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
... | Implements equation 3.5.1-1 page 148 for mean value and equation
3.5.5-2 page 151 for total standard deviation.
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def levenshtein(s1, s2, allow_substring=False):
"""Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to Tr... | Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to True allows s1 to be a
substring of s2, so that, for ... |
def is_valid(number):
"""determines whether the card number is valid."""
n = str(number)
if not n.isdigit():
return False
return int(n[-1]) == get_check_digit(n[:-1]) | determines whether the card number is valid. |
def _getDict(j9Page):
"""Parses a Journal Title Abbreviations page
Note the pages are not well formatted html as the <DT> tags are not closes so html parses (Beautiful Soup) do not work. This is a simple parser that only works on the webpages and may fail if they are changed
For Backend
"""
slines... | Parses a Journal Title Abbreviations page
Note the pages are not well formatted html as the <DT> tags are not closes so html parses (Beautiful Soup) do not work. This is a simple parser that only works on the webpages and may fail if they are changed
For Backend |
def list_all_commands(self):
""" Returns a list of all the Workbench commands"""
commands = [name for name, _ in inspect.getmembers(self, predicate=inspect.isroutine) if not name.startswith('_')]
return commands | Returns a list of all the Workbench commands |
def _nextPage(self, offset):
"""Retrieves the next set of results from the service."""
self.logger.debug("Iterator crecord=%s" % str(self.crecord))
params = {
'q': self.q,
'rows': '0',
'facet': 'true',
'facet.field': self.field,
'facet... | Retrieves the next set of results from the service. |
def update_confirmation_comment(self, confirmation_comment_id, confirmation_comment_dict):
"""
Updates a confirmation comment
:param confirmation_comment_id: the confirmation comment id
:param confirmation_comment_dict: dict
:return: dict
"""
return self._create_... | Updates a confirmation comment
:param confirmation_comment_id: the confirmation comment id
:param confirmation_comment_dict: dict
:return: dict |
def get_column_cursor_position(self, column):
"""
Return the relative cursor position for this column at the current
line. (It will stay between the boundaries of the line in case of a
larger number.)
"""
line_length = len(self.current_line)
current_column = self.... | Return the relative cursor position for this column at the current
line. (It will stay between the boundaries of the line in case of a
larger number.) |
def register(linter):
"""required method to auto register this checker """
linter.register_checker(ClassChecker(linter))
linter.register_checker(SpecialMethodsChecker(linter)) | required method to auto register this checker |
def mul_inv(a, b):
"""
Modular inversion a mod b
:param a:
:param b:
:return:
"""
b0 = b
x0, x1 = 0, 1
if b == 1:
return 1
while a > 1:
q = a // b
a, b = b, a % b
x0, x1 = x1 - q * x0, x0
... | Modular inversion a mod b
:param a:
:param b:
:return: |
def get_member_profile(self, member_id):
''' a method to retrieve member profile details
:param member_id: integer with member id from member profile
:return: dictionary with member profile details inside [json] key
profile_details = self.objects.profile.schema
'''
... | a method to retrieve member profile details
:param member_id: integer with member id from member profile
:return: dictionary with member profile details inside [json] key
profile_details = self.objects.profile.schema |
def _execute(self, execute_inputs, execute_outputs, backward_execution=False):
"""Calls the custom execute function of the script.py of the state
"""
self._script.build_module()
outcome_item = self._script.execute(self, execute_inputs, execute_outputs, backward_execution)
# in... | Calls the custom execute function of the script.py of the state |
def _get_esxcluster_proxy_details():
'''
Returns the running esxcluster's proxy details
'''
det = __salt__['esxcluster.get_details']()
return det.get('vcenter'), det.get('username'), det.get('password'), \
det.get('protocol'), det.get('port'), det.get('mechanism'), \
det.get(... | Returns the running esxcluster's proxy details |
def SpinBasisKet(*numer_denom, hs):
"""Constructor for a :class:`BasisKet` for a :class:`SpinSpace`
For a half-integer spin system::
>>> hs = SpinSpace('s', spin=(3, 2))
>>> assert SpinBasisKet(1, 2, hs=hs) == BasisKet("+1/2", hs=hs)
For an integer spin system::
>>> hs = SpinSpac... | Constructor for a :class:`BasisKet` for a :class:`SpinSpace`
For a half-integer spin system::
>>> hs = SpinSpace('s', spin=(3, 2))
>>> assert SpinBasisKet(1, 2, hs=hs) == BasisKet("+1/2", hs=hs)
For an integer spin system::
>>> hs = SpinSpace('s', spin=1)
>>> assert SpinBasis... |
def file_stat(self, filters=all_true):
"""Find out how many files, directorys and total size (Include file in
it's sub-folder).
:returns: stat, a dict like ``{"file": number of files,
"dir": number of directorys, "size": total size in bytes}``
**中文文档**
返回一个目录中的文件, 文件... | Find out how many files, directorys and total size (Include file in
it's sub-folder).
:returns: stat, a dict like ``{"file": number of files,
"dir": number of directorys, "size": total size in bytes}``
**中文文档**
返回一个目录中的文件, 文件夹, 大小的统计数据。 |
def path_to_tuple(path, windows=False):
"""
Split `chan_path` into individual parts and form a tuple (used as key).
"""
if windows:
path_tup = tuple(path.split('\\'))
else:
path_tup = tuple(path.split('/'))
#
# Normalize UTF-8 encoding to consistent form so cache lookups will... | Split `chan_path` into individual parts and form a tuple (used as key). |
def clean_extra(self):
"""Clean extra files/directories specified by get_extra_paths()"""
extra_paths = self.get_extra_paths()
for path in extra_paths:
if not os.path.exists(path):
continue
if os.path.isdir(path):
self._clean_directory(path... | Clean extra files/directories specified by get_extra_paths() |
def _get_resource_per_page(self, resource, per_page=1000, page=1, params=None):
"""
Gets specific data per resource page and per page
"""
assert (isinstance(resource, str))
common_params = {'per_page': per_page, 'page': page}
if not params:
params = common_pa... | Gets specific data per resource page and per page |
def value(self):
"""Value of a reference property.
You can set the reference with a Part, Part id or None value.
Ensure that the model of the provided part, matches the configured model
:return: a :class:`Part` or None
:raises APIError: When unable to find the associated :class... | Value of a reference property.
You can set the reference with a Part, Part id or None value.
Ensure that the model of the provided part, matches the configured model
:return: a :class:`Part` or None
:raises APIError: When unable to find the associated :class:`Part`
Example
... |
def alltoall(self, x, mesh_axis, split_axis, concat_axis):
"""Grouped alltoall.
Args:
x: a LaidOutTensor
mesh_axis: an integer the mesh axis along which to group
split_axis: an integer (the Tensor axis along which to split)
concat_axis: an integer (the Tensor axis along which to concate... | Grouped alltoall.
Args:
x: a LaidOutTensor
mesh_axis: an integer the mesh axis along which to group
split_axis: an integer (the Tensor axis along which to split)
concat_axis: an integer (the Tensor axis along which to concatenate)
Returns:
a LaidOutTensor |
def request(self, rule, view_class, annotation):
"""Make a request against the app.
This attempts to use the schema to replace any url params in the path
pattern. If there are any unused parameters in the schema, after
substituting the ones in the path, they will be sent as query string... | Make a request against the app.
This attempts to use the schema to replace any url params in the path
pattern. If there are any unused parameters in the schema, after
substituting the ones in the path, they will be sent as query string
parameters or form parameters. The substituted valu... |
def get_download_urls(self, package_name, version="", pkg_type="all"):
"""Query PyPI for pkg download URI for a packge"""
if version:
versions = [version]
else:
#If they don't specify version, show em all.
(package_name, versions) = self.query_versions_pypi... | Query PyPI for pkg download URI for a packge |
def barcode(self, code, bc, width=255, height=2, pos='below', font='a'):
""" Print Barcode """
# Align Bar Code()
self._raw(TXT_ALIGN_CT)
# Height
if height >=2 or height <=6:
self._raw(BARCODE_HEIGHT)
else:
raise BarcodeSizeError()
# Width... | Print Barcode |
def _enter(ins):
""" Enter function sequence for doing a function start
ins.quad[1] contains size (in bytes) of local variables
Use '__fastcall__' as 1st parameter to prepare a fastcall
function (no local variables).
"""
output = []
if ins.quad[1] == '__fastcall__':
retu... | Enter function sequence for doing a function start
ins.quad[1] contains size (in bytes) of local variables
Use '__fastcall__' as 1st parameter to prepare a fastcall
function (no local variables). |
def crop(img, i, j, h, w):
"""Crop the given PIL Image.
Args:
img (PIL Image): Image to be cropped.
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped image.
w (int): ... | Crop the given PIL Image.
Args:
img (PIL Image): Image to be cropped.
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped image.
w (int): Width of the cropped image.
R... |
def show(self, uuid=None, term=None):
"""Show the information related to unique identities.
This method prints information related to unique identities such as
identities or enrollments.
When <uuid> is given, it will only show information about the unique
identity related to <u... | Show the information related to unique identities.
This method prints information related to unique identities such as
identities or enrollments.
When <uuid> is given, it will only show information about the unique
identity related to <uuid>.
When <term> is set, it will only s... |
def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loop
print_cost -- if True, pr... | Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loop
print_cost -- if True, print the cost every 1000 iterations
Returns:
parameters -- parameters... |
def __pauli_meas_gates(circuit, qreg, op):
"""
Add state measurement gates to a circuit.
"""
if op not in ['X', 'Y', 'Z']:
raise QiskitError("There's no X, Y or Z basis for this Pauli "
"measurement")
if op == "X":
circuit.u2(0., np.pi, qreg) # H
elif ... | Add state measurement gates to a circuit. |
def _loadFromHStruct(self, dtype: HdlType, bitAddr: int):
"""
Parse HStruct type to this transaction template instance
:return: address of it's end
"""
for f in dtype.fields:
t = f.dtype
origin = f
isPadding = f.name is None
if is... | Parse HStruct type to this transaction template instance
:return: address of it's end |
def filter_catalog(catalog, **kwargs):
""" Create a new catalog selected from input based on photometry.
Parameters
----------
bright_limit : float
Fraction of catalog based on brightness that should be retained.
Value of 1.00 means full catalog.
max_bright : int
Maximum nu... | Create a new catalog selected from input based on photometry.
Parameters
----------
bright_limit : float
Fraction of catalog based on brightness that should be retained.
Value of 1.00 means full catalog.
max_bright : int
Maximum number of sources to keep regardless of `bright_l... |
def _edge_group_substitution(
self, ndid, nsplit, idxs, sr_tab, ndoffset, ed_remove, into_or_from
):
"""
Reconnect edges.
:param ndid: id of low resolution edges
:param nsplit: number of split
:param idxs: indexes of low resolution
:param sr_tab:
:para... | Reconnect edges.
:param ndid: id of low resolution edges
:param nsplit: number of split
:param idxs: indexes of low resolution
:param sr_tab:
:param ndoffset:
:param ed_remove:
:param into_or_from: if zero, connection of input edges is done. If one, connection of ... |
def gpp(argv=None):
"""Shortcut function for running the previewing command."""
if argv is None:
argv = sys.argv[1:]
argv.insert(0, 'preview')
return main(argv) | Shortcut function for running the previewing command. |
def observe(self, terminal, reward, index=0):
"""
Observe experience from the environment to learn from. Optionally pre-processes rewards
Child classes should call super to get the processed reward
EX: terminal, reward = super()...
Args:
terminal (bool): boolean indi... | Observe experience from the environment to learn from. Optionally pre-processes rewards
Child classes should call super to get the processed reward
EX: terminal, reward = super()...
Args:
terminal (bool): boolean indicating if the episode terminated after the observation.
... |
def load(self, filename):
"""
Load a npz file. Supports only files previously saved by
:meth:`pypianoroll.Multitrack.save`.
Notes
-----
Attribute values will all be overwritten.
Parameters
----------
filename : str
The name of the npz... | Load a npz file. Supports only files previously saved by
:meth:`pypianoroll.Multitrack.save`.
Notes
-----
Attribute values will all be overwritten.
Parameters
----------
filename : str
The name of the npz file to be loaded. |
def refresh_db(**kwargs):
'''
Check the yum repos for updated packages
Returns:
- ``True``: Updates are available
- ``False``: An error occurred
- ``None``: No updates are available
repo
Refresh just the specified repo
disablerepo
Do not refresh the specified repo
... | Check the yum repos for updated packages
Returns:
- ``True``: Updates are available
- ``False``: An error occurred
- ``None``: No updates are available
repo
Refresh just the specified repo
disablerepo
Do not refresh the specified repo
enablerepo
Refresh a disable... |
def do_implicit_flow_authorization(self, session):
""" Standard OAuth2 authorization method. It's used for getting access token
More info: https://vk.com/dev/implicit_flow_user
"""
logger.info('Doing implicit flow authorization, app_id=%s', self.app_id)
auth_data = {
... | Standard OAuth2 authorization method. It's used for getting access token
More info: https://vk.com/dev/implicit_flow_user |
def invert_if_negative(self):
"""
|True| if a point having a value less than zero should appear with a
fill different than those with a positive value. |False| if the fill
should be the same regardless of the bar's value. When |True|, a bar
with a solid fill appears with white fi... | |True| if a point having a value less than zero should appear with a
fill different than those with a positive value. |False| if the fill
should be the same regardless of the bar's value. When |True|, a bar
with a solid fill appears with white fill; in a bar with gradient
fill, the direc... |
def resource_type(self):
"""
Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute
"""
value = "rt="
lst = self._attributes.get("rt")
if lst is None:
value = ""
else:
value += "\"" + str(... | Get the CoRE Link Format rt attribute of the resource.
:return: the CoRE Link Format rt attribute |
def _create_dictionary_of_IFS(
self):
"""*Generate the list of dictionaries containing all the rows in the IFS stream*
**Return:**
- ``dictList`` - a list of dictionaries containing all the rows in the IFS stream
**Usage:**
.. code-block:: python
... | *Generate the list of dictionaries containing all the rows in the IFS stream*
**Return:**
- ``dictList`` - a list of dictionaries containing all the rows in the IFS stream
**Usage:**
.. code-block:: python
from sherlock.imports import IFS
stre... |
def process_waypoint_request(self, m, master):
'''process a waypoint request from the master'''
if (not self.loading_waypoints or
time.time() > self.loading_waypoint_lasttime + 10.0):
self.loading_waypoints = False
self.console.error("not loading waypoints")
... | process a waypoint request from the master |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current i... |
def modifyInPlace(self, *, sort=None, purge=False, done=None):
"""Like Model.modify, but changes existing database instead of
returning a new one."""
self.data = self.modify(sort=sort, purge=purge, done=done) | Like Model.modify, but changes existing database instead of
returning a new one. |
def finish_review(self, success=True, error=False):
"""Mark our review as finished."""
if self.set_status:
if error:
self.github_repo.create_status(
state="error",
description="Static analysis error! inline-plz failed to run.",
... | Mark our review as finished. |
def get_match_details(self, match_id=None, **kwargs):
"""Returns a dictionary containing the details for a Dota 2 match
:param match_id: (int, optional)
:return: dictionary of matches, see :doc:`responses </responses>`
"""
if 'match_id' not in kwargs:
kwargs['match_i... | Returns a dictionary containing the details for a Dota 2 match
:param match_id: (int, optional)
:return: dictionary of matches, see :doc:`responses </responses>` |
def to_dict(self):
"""Convert instance to a serializable mapping."""
config = {}
for attr in dir(self):
if not attr.startswith('_'):
value = getattr(self, attr)
if not hasattr(value, '__call__'):
config[attr] = value
return ... | Convert instance to a serializable mapping. |
def mangle_command(command, name_max=255, has_variables=False):
"""
Mangle a command line string into something suitable for use as the basename of a filename.
At minimum this function must remove slashes, but it also does other things to clean up
the basename: removing directory names from the command ... | Mangle a command line string into something suitable for use as the basename of a filename.
At minimum this function must remove slashes, but it also does other things to clean up
the basename: removing directory names from the command name, replacing many non-typical
characters with undersores, in addition... |
def f_rollup(items, times, freq):
"""
Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
"""
rollup = [np.sum(item for __, item in ts)
... | Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str |
def get_string(self, input_string):
"""
Return string type user input
"""
if input_string in ('--input', '--outname', '--framework'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn'... | Return string type user input |
def to_dict(self):
""" Return the user as a dict. """
public_keys = [public_key.b64encoded for public_key in self.public_keys]
return dict(name=self.name, passwd=self.passwd, uid=self.uid, gid=self.gid, gecos=self.gecos,
home_dir=self.home_dir, shell=self.shell, public_keys=p... | Return the user as a dict. |
def deserialize(self, d):
"""
De-serialize a Q object from a (possibly nested) dict.
"""
children = []
for child in d.pop('children'):
if isinstance(child, dict):
children.append(self.deserialize(child))
else:
children.appen... | De-serialize a Q object from a (possibly nested) dict. |
def exists(self, names):
"""Checks if the given file list exists in the current directory
level.
in names of type str
The names to check.
return exists of type str
The names which exist.
"""
if not isinstance(names, list):
raise Type... | Checks if the given file list exists in the current directory
level.
in names of type str
The names to check.
return exists of type str
The names which exist. |
def set_query(self, value):
""" Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values.
"""
if isinstance(value,... | Convert a dict form of query in a string of needed and store the query string.
Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values. |
def split(self, url):
"""
Split the url into I{protocol} and I{location}
@param url: A URL.
@param url: str
@return: (I{url}, I{location})
@rtype: tuple
"""
parts = url.split('://', 1)
if len(parts) == 2:
return parts
else:
... | Split the url into I{protocol} and I{location}
@param url: A URL.
@param url: str
@return: (I{url}, I{location})
@rtype: tuple |
def log(self, *args):
"""stdout and stderr for the link"""
print("%s %s" % (str(self).ljust(8), " ".join([str(x) for x in args]))) | stdout and stderr for the link |
def labels(self):
""" Returns the taxon set of the tree (same as the label- or
leaf-set) """
return set([n.taxon.label for n in self._tree.leaf_nodes()]) | Returns the taxon set of the tree (same as the label- or
leaf-set) |
def parallel_tfa_lcdir(lcdir,
templateinfo,
lcfileglob=None,
timecols=None,
magcols=None,
errcols=None,
lcformat='hat-sql',
lcformatdir=None,
... | This applies TFA in parallel to all LCs in a directory.
Parameters
----------
lcdir : str
This is the directory containing the light curve files to process..
templateinfo : dict or str
This is either the dict produced by `tfa_templates_lclist` or the pickle
produced by the sam... |
def zscale(data,contrast,min=100,max=60000):
"""Scale the data cube into the range 0-255"""
## pic 100 random elements along each dimension
## use zscale (see the IRAF display man page or
## http://iraf.net/article.php/20051205162333315
import random
x=[]
for i in random.sample(xrange(data.shape[0]),50):
... | Scale the data cube into the range 0-255 |
def skip_if_needed(self, job_record):
""" method is called from abstract_state_machine.manage_job to notify about job's failed processing
if should_skip_node returns True - the node's job_record is transferred to STATE_SKIPPED """
tree = self.get_tree(job_record.process_name)
node = ... | method is called from abstract_state_machine.manage_job to notify about job's failed processing
if should_skip_node returns True - the node's job_record is transferred to STATE_SKIPPED |
def sync_local_order(self):
"""!
@brief Calculates current level of local (partial) synchronization in the network.
@return (double) Level of local (partial) synchronization.
@see sync_order()
"""
if (self._ccore_network_point... | !
@brief Calculates current level of local (partial) synchronization in the network.
@return (double) Level of local (partial) synchronization.
@see sync_order() |
def framewise(self):
"""
Property to determine whether the current frame should have
framewise normalization enabled. Required for bokeh plotting
classes to determine whether to send updated ranges for each
frame.
"""
current_frames = [el for f in self.traverse(la... | Property to determine whether the current frame should have
framewise normalization enabled. Required for bokeh plotting
classes to determine whether to send updated ranges for each
frame. |
def relative_strength_index(data, period):
"""
Relative Strength Index.
Formula:
RSI = 100 - (100 / 1 + (prevGain/prevLoss))
"""
catch_errors.check_for_period_error(data, period)
period = int(period)
changes = [data_tup[1] - data_tup[0] for data_tup in zip(data[::1], data[1::1])]
... | Relative Strength Index.
Formula:
RSI = 100 - (100 / 1 + (prevGain/prevLoss)) |
def __we_c(cls, calib, tc, temp, we_v, ae_v):
"""
Compute weC from sensor temperature compensation of weV, aeV
"""
we_t = we_v - (calib.we_elc_mv / 1000.0) # remove electronic we zero
ae_t = ae_v - (calib.ae_elc_mv / 1000.0) # remove electronic ae zero
we_c... | Compute weC from sensor temperature compensation of weV, aeV |
def _format_download_uri_for_extension(etextno, extension, mirror=None):
"""Returns the download location on the Project Gutenberg servers for a
given text and extension. The list of available extensions for a given
text can be found via the formaturi metadata extractor.
"""
mirror = mirror or _GUT... | Returns the download location on the Project Gutenberg servers for a
given text and extension. The list of available extensions for a given
text can be found via the formaturi metadata extractor. |
def owner(self, data):
"""The Owner payload value for this resource request."""
if data is not None:
self._request.add_payload('owner', data)
else:
self.tcex.log.warn(u'Provided owner was invalid. ({})'.format(data)) | The Owner payload value for this resource request. |
def init():
""" Initializes the preprocessor
"""
global OUTPUT
global INCLUDED
global CURRENT_DIR
global ENABLED
global INCLUDEPATH
global IFDEFS
global ID_TABLE
global CURRENT_FILE
global_.FILENAME = '(stdin)'
OUTPUT = ''
INCLUDED = {}
CURRENT_DIR = ''
pwd =... | Initializes the preprocessor |
def set_permissions(obj_name,
principal,
permissions,
access_mode='grant',
applies_to=None,
obj_type='file',
reset_perms=False,
protected=None):
'''
Set the permissions of ... | Set the permissions of an object. This can be a file, folder, registry key,
printer, service, etc...
Args:
obj_name (str):
The object for which to set permissions. This can be the path to a
file or folder, a registry key, printer, etc. For more information
about how... |
def findspans(self, type,set=None):
"""Yields span annotation elements of the specified type that include this word.
Arguments:
type: The annotation type, can be passed as using any of the :class:`AnnotationType` member, or by passing the relevant :class:`AbstractSpanAnnotation` or :class:`... | Yields span annotation elements of the specified type that include this word.
Arguments:
type: The annotation type, can be passed as using any of the :class:`AnnotationType` member, or by passing the relevant :class:`AbstractSpanAnnotation` or :class:`AbstractAnnotationLayer` class.
set... |
def get_weather(self):
"""
Returns an instance of the Weather Service.
"""
import predix.data.weather
weather = predix.data.weather.WeatherForecast()
return weather | Returns an instance of the Weather Service. |
def bg(func):
"""Run a function in background, will not block main thread's exit.(thread.daemon=True)
::
from torequests.utils import bg, print_info
import time
def test1(n):
time.sleep(n)
print_info(n, 'done')
@bg
def test2(n):
time... | Run a function in background, will not block main thread's exit.(thread.daemon=True)
::
from torequests.utils import bg, print_info
import time
def test1(n):
time.sleep(n)
print_info(n, 'done')
@bg
def test2(n):
time.sleep(n)
... |
def put(self, url, data):
"""
Make a PUT request to save data.
data should be a dictionary.
"""
response = self._run_method('PUT', url, data=data)
log.debug("OUTPUT: %s" % response.content)
return self._handle_response(url, response) | Make a PUT request to save data.
data should be a dictionary. |
def read_nonblocking (self, size = 1, timeout = -1):
"""This reads at most size bytes from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be r... | This reads at most size bytes from the child application. It
includes a timeout. If the read does not complete within the timeout
period then a TIMEOUT exception is raised. If the end of file is read
then an EOF exception will be raised. If a log file was set using
setlog() then all data... |
def run(command, timeout=None, cwd=None, env=None, debug=None):
"""
Runs a given command on the system within a set time period, providing an easy way to access
command output as it happens without waiting for the command to finish running.
:type list
:param command: Should be a list that contains ... | Runs a given command on the system within a set time period, providing an easy way to access
command output as it happens without waiting for the command to finish running.
:type list
:param command: Should be a list that contains the command that should be ran on the given
system. The ... |
def _prune_components(self):
"""
Remove components for which the remote party did not provide any candidates.
This can only be determined after end-of-candidates.
"""
seen_components = set(map(lambda x: x.component, self._remote_candidates))
missing_components = self._co... | Remove components for which the remote party did not provide any candidates.
This can only be determined after end-of-candidates. |
def GetValues(self, fd):
"""Return the values for this attribute as stored in an AFF4Object."""
result = None
for result in fd.new_attributes.get(self, []):
# We need to interpolate sub fields in this rdfvalue.
if self.field_names:
for x in self.GetSubFields(result, self.field_names):
... | Return the values for this attribute as stored in an AFF4Object. |
def get_cert_contents(kwargs):
"""Builds parameters with server cert file contents.
Args:
kwargs(dict): The keyword args passed to ensure_server_cert_exists,
optionally containing the paths to the cert, key and chain files.
Returns:
dict: A dictionary containing the appropriate... | Builds parameters with server cert file contents.
Args:
kwargs(dict): The keyword args passed to ensure_server_cert_exists,
optionally containing the paths to the cert, key and chain files.
Returns:
dict: A dictionary containing the appropriate parameters to supply to
u... |
def get_network_channel(self):
"""Get a reasonable 'default' network channel.
When configuring/examining network configuration, it's desirable to
find the correct channel. Here we run with the 'real' number of the
current channel if it is a LAN channel, otherwise it evaluates
a... | Get a reasonable 'default' network channel.
When configuring/examining network configuration, it's desirable to
find the correct channel. Here we run with the 'real' number of the
current channel if it is a LAN channel, otherwise it evaluates
all of the channels to find the first worka... |
def _subspace_process(streams, lowcut, highcut, filt_order, sampling_rate,
multiplex, align, shift_len, reject, no_missed=True,
stachans=None, parallel=False, plot=False, cores=1):
"""
Process stream data, internal function.
:type streams: list
:param streams... | Process stream data, internal function.
:type streams: list
:param streams: List of obspy.core.stream.Stream to be used to \
generate the subspace detector. These should be pre-clustered \
and aligned.
:type lowcut: float
:param lowcut: Lowcut in Hz, can be None to not apply filter
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.