code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _set_widths(self, row, proc_group):
"""Update auto-width Fields based on `row`.
Parameters
----------
row : dict
proc_group : {'default', 'override'}
Whether to consider 'default' or 'override' key for pre- and
post-format processors.
Returns... | Update auto-width Fields based on `row`.
Parameters
----------
row : dict
proc_group : {'default', 'override'}
Whether to consider 'default' or 'override' key for pre- and
post-format processors.
Returns
-------
True if any widths require... |
def _handle_nodes(nodes: MaybeNodeList) -> List[BaseEntity]:
"""Handle node(s) that might be dictionaries."""
if isinstance(nodes, BaseEntity):
return [nodes]
return [
(
parse_result_to_dsl(node)
if not isinstance(node, BaseEntity) else
node
)
... | Handle node(s) that might be dictionaries. |
def set_vf0(self, vf):
"""set value for self.vf0 and dae.y[self.vf]"""
self.vf0 = vf
self.system.dae.y[self.vf] = matrix(vf) | set value for self.vf0 and dae.y[self.vf] |
def sharded_cluster_link(rel, cluster_id=None,
shard_id=None, router_id=None, self_rel=False):
"""Helper for getting a ShardedCluster link document, given a rel."""
clusters_href = '/v1/sharded_clusters'
link = _SHARDED_CLUSTER_LINKS[rel].copy()
link['href'] = link['href'].forma... | Helper for getting a ShardedCluster link document, given a rel. |
def encode(self, delimiter=';'):
"""Encode a command string from message."""
try:
return delimiter.join([str(f) for f in [
self.node_id,
self.child_id,
int(self.type),
self.ack,
int(self.sub_type),
... | Encode a command string from message. |
def token_required(view_func):
"""
Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set.
WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be
customized.
"""
def _parse_auth_header(auth_header):
"""
Parse the `Authorization` header
... | Decorator which ensures that one of the WATCHMAN_TOKENS is provided if set.
WATCHMAN_TOKEN_NAME can also be set if the token GET parameter must be
customized. |
def read_csi_node(self, name, **kwargs):
"""
read the specified CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_csi_node(name, async_req=True)
>>> result = thread.get()... | read the specified CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_csi_node(name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name... |
def store_sm(smodel, filename, monitor):
"""
:param smodel: a :class:`openquake.hazardlib.nrml.SourceModel` instance
:param filename: path to an hdf5 file (cache_XXX.hdf5)
:param monitor: a Monitor instance with an .hdf5 attribute
"""
h5 = monitor.hdf5
with monitor('store source model'):
... | :param smodel: a :class:`openquake.hazardlib.nrml.SourceModel` instance
:param filename: path to an hdf5 file (cache_XXX.hdf5)
:param monitor: a Monitor instance with an .hdf5 attribute |
def set_share_path(self, share_path):
"""Set application location for this resource provider.
@param share_path: a UTF-8 encoded, unquoted byte string.
"""
# if isinstance(share_path, unicode):
# share_path = share_path.encode("utf8")
assert share_path == "" or share... | Set application location for this resource provider.
@param share_path: a UTF-8 encoded, unquoted byte string. |
def find_this(search, source=SOURCE):
"""Take a string and a filename path string and return the found value."""
print("Searching for {what}.".format(what=search))
if not search or not source:
print("Not found on source: {what}.".format(what=search))
return ""
return str(re.compile(r'.*_... | Take a string and a filename path string and return the found value. |
def _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data):
"""Trimming with cutadapt, using version installed with bcbio-nextgen.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
if quality_format == "illumina":
quality_base = "64"
else:
... | Trimming with cutadapt, using version installed with bcbio-nextgen. |
def disk_vmag(hemi, retinotopy='any', to=None, **kw):
'''
disk_vmag(mesh) yields the visual magnification based on the projection of disks on the cortical
surface into the visual field.
All options accepted by mag_data() are accepted by disk_vmag().
'''
mdat = mag_data(hemi, retinotopy=retino... | disk_vmag(mesh) yields the visual magnification based on the projection of disks on the cortical
surface into the visual field.
All options accepted by mag_data() are accepted by disk_vmag(). |
def dispatch_hook(cls, _pkt=None, *args, **kargs):
"""
Returns the right parameter set class.
"""
cls = conf.raw_layer
if _pkt is not None:
ptype = orb(_pkt[0])
return globals().get(_param_set_cls.get(ptype), conf.raw_layer)
return cls | Returns the right parameter set class. |
def literal_matches_objectliteral(v1: Literal, v2: ShExJ.ObjectLiteral) -> bool:
""" Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` """
v2_lit = Literal(str(v2.value), datatype=iriref_to_uriref(v2.type), lang=str(v2.language) if v2.language else None)
return v1 == v2_lit | Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` |
def preserve_builtin_query_params(url, request=None):
"""
Given an incoming request, and an outgoing URL representation,
append the value of any built-in query parameters.
"""
if request is None:
return url
overrides = [
api_settings.URL_FORMAT_OVERRIDE,
]
for param in ... | Given an incoming request, and an outgoing URL representation,
append the value of any built-in query parameters. |
def consult_filters(self, url_info: URLInfo, url_record: URLRecord, is_redirect: bool=False) \
-> Tuple[bool, str, dict]:
'''Consult the URL filter.
Args:
url_record: The URL record.
is_redirect: Whether the request is a redirect and it is
desired tha... | Consult the URL filter.
Args:
url_record: The URL record.
is_redirect: Whether the request is a redirect and it is
desired that it spans hosts.
Returns
tuple:
1. bool: The verdict
2. str: A short reason string: nofilters, fil... |
def set_value(self, attribute, section, value):
"""
Sets requested attribute value.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = Sectio... | Sets requested attribute value.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = conten... |
def get_assets_by_repository(self, repository_id):
"""Gets the list of ``Assets`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.AssetList) - list of related assets
raise: NotFound - ``repository_id`` is not f... | Gets the list of ``Assets`` associated with a ``Repository``.
arg: repository_id (osid.id.Id): ``Id`` of the ``Repository``
return: (osid.repository.AssetList) - list of related assets
raise: NotFound - ``repository_id`` is not found
raise: NullArgument - ``repository_id`` is ``nul... |
def get_schemas():
"""Return a dict of schema names mapping to a Schema.
The schema is of type schul_cloud_resources_api_v1.schema.Schema
"""
schemas = {}
for name in os.listdir(JSON_PATH):
if name not in NO_SCHEMA:
schemas[name] = Schema(name)
return schemas | Return a dict of schema names mapping to a Schema.
The schema is of type schul_cloud_resources_api_v1.schema.Schema |
def to_unicode(s, encoding=None, errors='strict'):
"""
Make unicode string from any value
:param s:
:param encoding:
:param errors:
:return: unicode
"""
encoding = encoding or 'utf-8'
if is_unicode(s):
return s
elif is_strlike(s):
return s.decode(encoding, errors... | Make unicode string from any value
:param s:
:param encoding:
:param errors:
:return: unicode |
def _pseudoinverse(self, A, tol=1.0e-10):
"""
Compute the Moore-Penrose pseudoinverse.
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
... | Compute the Moore-Penrose pseudoinverse.
REQUIRED ARGUMENTS
A (np KxK matrix) - the square matrix whose pseudoinverse is to be computed
RETURN VALUES
Ainv (np KxK matrix) - the pseudoinverse
OPTIONAL VALUES
tol - the tolerance (relative to largest magnitude singl... |
def render_entry(entry_id, slug_text='', category=''):
""" Render an entry page.
Arguments:
entry_id -- The numeric ID of the entry to render
slug_text -- The expected URL slug text
category -- The expected category
"""
# pylint: disable=too-many-return-statements
# check if it's a v... | Render an entry page.
Arguments:
entry_id -- The numeric ID of the entry to render
slug_text -- The expected URL slug text
category -- The expected category |
def check_version(mod, required):
"""Require minimum version of module using ``__version__`` member."""
vers = tuple(int(v) for v in mod.__version__.split('.')[:3])
if vers < required:
req = '.'.join(str(v) for v in required)
raise ImproperlyConfigured(
"Module \"%s\" version (%s... | Require minimum version of module using ``__version__`` member. |
def get_lead(self, lead_id):
"""
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
"""
params = self.base_params
endpoint = self.base_endpoint.format('leads/' + str(lead_id))
... | Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict. |
def visit_decorators(self, node, parent):
"""visit a Decorators node by returning a fresh instance of it"""
# /!\ node is actually a _ast.FunctionDef node while
# parent is an astroid.nodes.FunctionDef node
newnode = nodes.Decorators(node.lineno, node.col_offset, parent)
newnode.... | visit a Decorators node by returning a fresh instance of it |
def check_webhook_validation(app_configs=None, **kwargs):
"""
Check that DJSTRIPE_WEBHOOK_VALIDATION is valid
"""
from . import settings as djstripe_settings
messages = []
validation_options = ("verify_signature", "retrieve_event")
if djstripe_settings.WEBHOOK_VALIDATION is None:
messages.append(
checks.... | Check that DJSTRIPE_WEBHOOK_VALIDATION is valid |
def _recursive_split(self, bbox, zoom_level, column, row):
"""Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in t... | Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in the OSM grid
:type column: int
:param row: Row in the O... |
def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs normal vectors"""
if root is None:
root = {}
normals = dataset.GetPointData().GetNormals()
if normals:
dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
root['poin... | dump vtkjs normal vectors |
def calculateDatasets(self, scene, axes, datasets):
"""
Builds the datasets for this renderer. Each renderer will need to
subclass and implemenent this method, otherwise, no data will be
shown in the chart.
:param scene | <XChartScene>
ax... | Builds the datasets for this renderer. Each renderer will need to
subclass and implemenent this method, otherwise, no data will be
shown in the chart.
:param scene | <XChartScene>
axes | [<
datasets | [<XChartDataset>, ..] |
def add_missing_children(required_children, element_children):
"""Determine if there are elements not in the children
that need to be included as blank elements in the form.
"""
element_tags = [element.tag for element in element_children]
# Loop through the elements that should be in the form.
f... | Determine if there are elements not in the children
that need to be included as blank elements in the form. |
def _get_metadata_for_galaxies(
self):
"""get metadata for galaxies
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
... | get metadata for galaxies
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any use... |
def parse_dformat(dformat, check=True):
"""Return `dformat` or raise if it is not 'dense' or 'sparse'"""
if check and dformat not in ['dense', 'sparse']:
raise IOError(
"{} is a bad features format, please choose 'dense' or 'sparse'"
.format(dformat))
return dformat | Return `dformat` or raise if it is not 'dense' or 'sparse |
def login_with_google(self, email, oauth2_token, **kwargs):
"""Login to Todoist using Google's oauth2 authentication.
:param email: The user's Google email address.
:type email: str
:param oauth2_token: The user's Google oauth2 token.
:type oauth2_token: str
:param auto_... | Login to Todoist using Google's oauth2 authentication.
:param email: The user's Google email address.
:type email: str
:param oauth2_token: The user's Google oauth2 token.
:type oauth2_token: str
:param auto_signup: If ``1`` register an account automatically.
:type auto_... |
def check_alive_instances(self):
"""Check alive instances.
If not, log error and try to restart it
:return: None
"""
# Only for external
for instance in self.instances:
if instance in self.to_restart:
continue
if instance.is_exter... | Check alive instances.
If not, log error and try to restart it
:return: None |
def relabel_groups_masked(group_idx, keep_group):
"""
group_idx: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5]
0 1 2 3 4 5
keep_group: [0 1 0 1 1 1]
ret: [0 2 2 2 0 0 4 0 0 1 1 0 2 4 4]
Description of above in words: remove group 2, and relabel group 3,4, and 5
to be 2, 3 ... | group_idx: [0 3 3 3 0 2 5 2 0 1 1 0 3 5 5]
0 1 2 3 4 5
keep_group: [0 1 0 1 1 1]
ret: [0 2 2 2 0 0 4 0 0 1 1 0 2 4 4]
Description of above in words: remove group 2, and relabel group 3,4, and 5
to be 2, 3 and 4 respecitvely, in order to fill the gap. Note that group... |
def resolve_image_as_pil(self, image_url, coords=None):
"""
Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image
"""
files = self.mets.find... | Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image |
def transform_inverse(im_tensor, mean, std):
"""
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: im [height, width, channel(RGB)]
... | transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: im [height, width, channel(RGB)] |
def isopen(self) -> bool:
"""State of backing file."""
if self._file is None:
return False
# try accessing the id attribute to see if the file is open
return bool(self._file.id) | State of backing file. |
def Call(method,url,payload=None,session=None,debug=False):
"""Execute v2 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:returns: decoded API json result
"""
if session is not None:
token = session['token']
http_s... | Execute v2 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:returns: decoded API json result |
def rdlevenshtein_norm(source, target):
"""Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between string... | Calculates the normalized restricted Damerau-Levenshtein distance
(a.k.a. the normalized optimal string alignment distance) between two
string arguments. The result will be a float in the range [0.0, 1.0], with
1.0 signifying the maximum distance between strings with these lengths |
def preprocess_cell(
self, cell: "NotebookNode", resources: dict, cell_index: int
) -> Tuple["NotebookNode", dict]:
"""Apply a transformation on each cell.
Parameters
----------
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary... | Apply a transformation on each cell.
Parameters
----------
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine... |
def decode(geohash):
"""
Decode geohash, returning two strings with latitude and longitude
containing only relevant digits and with trailing zeroes removed.
"""
lat, lon, lat_err, lon_err = decode_exactly(geohash)
# Format to the number of decimals that are known
lats = "%.*f" % (max(1, int(... | Decode geohash, returning two strings with latitude and longitude
containing only relevant digits and with trailing zeroes removed. |
def _as_dict(self):
""" Returns a map of column names to cleaned values """
values = self._dynamic_columns or {}
for name, col in self._columns.items():
values[name] = col.to_database(getattr(self, name, None))
return values | Returns a map of column names to cleaned values |
def module_imports_on_top_of_file(
logical_line, indent_level, checker_state, noqa):
r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments
and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is ... | r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments
and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is ... |
def weather(self, latitude=None, longitude=None, date=None):
# type:(float, float, datetime) -> Weather
"""
:param float latitude: Locations latitude
:param float longitude: Locations longitude
:param datetime or str or int date: Date/time for historical weather data
:ra... | :param float latitude: Locations latitude
:param float longitude: Locations longitude
:param datetime or str or int date: Date/time for historical weather data
:raises requests.exceptions.HTTPError: Raises on bad http response
:raises TypeError: Raises on invalid param types
:r... |
def forestplot(trace_obj, vars=None, alpha=0.05, quartiles=True, rhat=True,
main=None, xtitle=None, xrange=None, ylabels=None, chain_spacing=0.05, vline=0):
""" Forest plot (model summary plot)
Generates a "forest plot" of 100*(1-alpha)% credible intervals for either the
set of variables in ... | Forest plot (model summary plot)
Generates a "forest plot" of 100*(1-alpha)% credible intervals for either the
set of variables in a given model, or a specified set of nodes.
:Arguments:
trace_obj: NpTrace or MultiTrace object
Trace(s) from an MCMC sample.
vars: list
... |
def bfs_depth(self, U):
'''
Returns the maximum distance between any vertex and U in the connected
component containing U
:param U:
:return:
'''
bfs_queue = [[U, 0]] # Stores the vertices whose BFS hadn't been completed.
visited = set()
max_depth = 0
while bfs_queue:
[V, d... | Returns the maximum distance between any vertex and U in the connected
component containing U
:param U:
:return: |
def set_topic_config(self, topic, value, kafka_version=(0, 10, )):
"""Set configuration information for specified topic.
:topic : topic whose configuration needs to be changed
:value : config value with which the topic needs to be
updated with. This would be of the form key=value.
... | Set configuration information for specified topic.
:topic : topic whose configuration needs to be changed
:value : config value with which the topic needs to be
updated with. This would be of the form key=value.
Example 'cleanup.policy=compact'
:kafka_version :tuple kaf... |
def restrict_args(func, *args, **kwargs):
'''
Restricts the possible arguements to a method to match the func argument.
restrict_args(lambda a: a, 1, 2)
# => 1
'''
callargs = getargspec(func)
if not callargs.varargs:
args = args[0:len(callargs.args)]
return func(*args,... | Restricts the possible arguements to a method to match the func argument.
restrict_args(lambda a: a, 1, 2)
# => 1 |
def paginate(parser, token, paginator_class=None):
"""Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* ori... | Paginate objects.
Usage:
.. code-block:: html+django
{% paginate entries %}
After this call, the *entries* variable in the template context is replaced
by only the entries of the current page.
You can also keep your *entries* original variable (usually a queryset)
and add to the con... |
def add_locals(self, locals):
'''
If locals are provided, create a copy of self containing those
locals in addition to what is already in this variable proxy.
'''
if locals is None:
return self
return _jinja2_vars(self.basedir, self.vars, self.globals, locals,... | If locals are provided, create a copy of self containing those
locals in addition to what is already in this variable proxy. |
def color(self, *args):
'''
:param args: color in a supported format.
:return: Color object containing the color.
'''
return self.Color(mode=self.color_mode, color_range=self.color_range, *args) | :param args: color in a supported format.
:return: Color object containing the color. |
def _register_simple(self, endpoint, scheme, f):
"""Register a simple endpoint with this TChannel.
:param endpoint:
Name of the endpoint being registered.
:param scheme:
Name of the arg scheme under which the endpoint will be
registered.
:param f:
... | Register a simple endpoint with this TChannel.
:param endpoint:
Name of the endpoint being registered.
:param scheme:
Name of the arg scheme under which the endpoint will be
registered.
:param f:
Callable handler for the endpoint. |
def kafka_kip(enrich):
""" Kafka Improvement Proposals process study """
def extract_vote_and_binding(body):
""" Extracts the vote and binding for a KIP process included in message body """
vote = 0
binding = 0 # by default the votes are binding for +1
nlines = 0
for... | Kafka Improvement Proposals process study |
def get_outcome_for_state_id(self, state_id):
""" Returns the final outcome of the child state specified by the state_id.
:param state_id: The id of the state to get the final outcome for.
:return:
"""
return_value = None
for s_id, name_outcome_tuple in self.final_outcom... | Returns the final outcome of the child state specified by the state_id.
:param state_id: The id of the state to get the final outcome for.
:return: |
def _get_torrent_category(self, tag, result=None):
"""Given a tag containing torrent details try to find category
of torrent. In search pages the category is found in links of
the form <a href='/tv/'>TV</a> with TV replaced with movies, books
etc. For the home page I will use the result number to
... | Given a tag containing torrent details try to find category
of torrent. In search pages the category is found in links of
the form <a href='/tv/'>TV</a> with TV replaced with movies, books
etc. For the home page I will use the result number to
decide the category |
def _is_bst(root, min_value=float('-inf'), max_value=float('inf')):
"""Check if the binary tree is a BST (binary search tree).
:param root: Root node of the binary tree.
:type root: binarytree.Node | None
:param min_value: Minimum node value seen.
:type min_value: int | float
:param max_value: ... | Check if the binary tree is a BST (binary search tree).
:param root: Root node of the binary tree.
:type root: binarytree.Node | None
:param min_value: Minimum node value seen.
:type min_value: int | float
:param max_value: Maximum node value seen.
:type max_value: int | float
:return: True... |
def managed(name, users=None, defaults=None):
'''
Manages the configuration of the users on the device, as specified in the state SLS file. Users not defined in that
file will be remove whilst users not configured on the device, will be added.
SLS Example:
.. code-block:: yaml
netusers_e... | Manages the configuration of the users on the device, as specified in the state SLS file. Users not defined in that
file will be remove whilst users not configured on the device, will be added.
SLS Example:
.. code-block:: yaml
netusers_example:
netusers.managed:
- us... |
def main():
"""
Parse command line arguments and then run the test suite
"""
parser = argparse.ArgumentParser(description='A distributed test framework')
parser.add_argument('testfile',
help='The file that is used to determine the test suite run')
parser.add_argument('--test-only',
nargs='*',
... | Parse command line arguments and then run the test suite |
def _ParseDateTimeValue(self, parser_mediator, date_time_value):
"""Parses a date time value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_... | Parses a date time value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) in the format: "YYYYMMDDhhmmssZ".
Returns:
... |
def validate(self, columns=None):
"""
Validates the current record object to make sure it is ok to commit to the database. If
the optional override dictionary is passed in, then it will use the given values vs. the one
stored with this record object which can be useful to check to see i... | Validates the current record object to make sure it is ok to commit to the database. If
the optional override dictionary is passed in, then it will use the given values vs. the one
stored with this record object which can be useful to check to see if the record will be valid before
it is commit... |
def check_monophyly(self,
values,
target_attr,
ignore_missing=False,
unrooted=False):
"""
Returns True if a given target attribute is monophyletic under
this node for the provided set of values.
If not all values are represented in the current tree
... | Returns True if a given target attribute is monophyletic under
this node for the provided set of values.
If not all values are represented in the current tree
structure, a ValueError exception will be raised to warn that
strict monophyly could never be reached (this behaviour can be
... |
def _handle_version(self, data):
"""
Handles received version data.
:param data: Version string to parse
:type data: string
"""
_, version_string = data.split(':')
version_parts = version_string.split(',')
self.serial_number = version_parts[0]
s... | Handles received version data.
:param data: Version string to parse
:type data: string |
def _grp_store_group(self, traj_group, store_data=pypetconstants.STORE_DATA,
with_links=True, recursive=False, max_depth=None,
_hdf5_group=None, _newly_created=False):
"""Stores a group node.
For group nodes only annotations and comments need to be stor... | Stores a group node.
For group nodes only annotations and comments need to be stored. |
def additions_version():
'''
Check VirtualBox Guest Additions version.
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_version
:return: version of VirtualBox Guest Additions or False if they are not installed
'''
try:
d = _additions_dir()
except Enviro... | Check VirtualBox Guest Additions version.
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_version
:return: version of VirtualBox Guest Additions or False if they are not installed |
def addPath(rel_path, prepend=False):
""" Adds a directory to the system python path, either by append (doesn't
override default or globally installed package names) or by prepend
(overrides default/global package names).
"""
path = lambda *paths: os.path.abspath(
os.path.join(os.path.dirnam... | Adds a directory to the system python path, either by append (doesn't
override default or globally installed package names) or by prepend
(overrides default/global package names). |
def handle_namespace_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
"""Handle statements like ``DEFINE NAMESPACE X AS PATTERN "Y"``.
:raises: RedefinedNamespaceError
"""
namespace = tokens['name']
self.raise_for_redefined_namespace(line, position,... | Handle statements like ``DEFINE NAMESPACE X AS PATTERN "Y"``.
:raises: RedefinedNamespaceError |
def linkify(text, shorten=False, extra_params="",
require_protocol=False, permitted_protocols=["http", "https"]):
"""Converts plain text into HTML with links.
For example: ``linkify("Hello http://tornadoweb.org!")`` would return
``Hello <a href="http://tornadoweb.org">http://tornadoweb.org... | Converts plain text into HTML with links.
For example: ``linkify("Hello http://tornadoweb.org!")`` would return
``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!``
Parameters:
* ``shorten``: Long urls will be shortened for display.
* ``extra_params``: Extra text to incl... |
def bayesian_hmm(observations, estimated_hmm, nsample=100, reversible=True, stationary=False,
p0_prior='mixed', transition_matrix_prior='mixed', store_hidden=False, call_back=None):
r""" Bayesian HMM based on sampling the posterior
Generic maximum-likelihood estimation of HMMs
Parameters
... | r""" Bayesian HMM based on sampling the posterior
Generic maximum-likelihood estimation of HMMs
Parameters
----------
observations : list of numpy arrays representing temporal data
`observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i`
estimated_hmm : HMM
... |
def textmetrics(self, txt, width=None, height=None, **kwargs):
'''Returns the width and height of a string of text as a tuple
(according to current font settings).
'''
# for now only returns width and height (as per Nodebox behaviour)
# but maybe we could use the other data from ... | Returns the width and height of a string of text as a tuple
(according to current font settings). |
def cublasZtpmv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Matrix-vector product for complex triangular-packed matrix.
"""
status = _libcublas.cublasZtpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
... | Matrix-vector product for complex triangular-packed matrix. |
def create_from_other( Class, other, values=None ):
"""
Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided
"""
m = Class()
m.alphabet = other.alphabet
m.sorted_alphabet = other.sorted_alphabet
m.char... | Create a new Matrix with attributes taken from `other` but with the
values taken from `values` if provided |
def full_signature(self):
"""
The full signature of a ``"function"`` node.
**Return**
:class:`python:str`
The full signature of the function, including template, return type,
name, and parameter types.
**Raises**
:class:`python:Ru... | The full signature of a ``"function"`` node.
**Return**
:class:`python:str`
The full signature of the function, including template, return type,
name, and parameter types.
**Raises**
:class:`python:RuntimeError`
If ``self.kind != ... |
def index(self, alias):
"""
Selects which database this QuerySet should execute its query against.
"""
clone = self._clone()
clone._index = alias
return clone | Selects which database this QuerySet should execute its query against. |
def _maybe_clear_confirmation_futures(self):
"""Invoked when the message has finished processing, ensuring there
are no confirmation futures pending.
"""
for name in self._connections.keys():
self._connections[name].clear_confirmation_futures() | Invoked when the message has finished processing, ensuring there
are no confirmation futures pending. |
def _add32(ins):
""" Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
o1, o2 = _in... | Pops last 2 bytes from the stack and adds them.
Then push the result onto the stack.
Optimizations:
* If any of the operands is ZERO,
then do NOTHING: A + 0 = 0 + A = A |
def do_copy(self,args):
"""Copy specified id to stack. copy -h for detailed help."""
parser = CommandArgumentParser("copy")
parser.add_argument('-a','--asg',dest='asg',nargs='+',required=False,default=[],help='Copy specified ASG info.')
parser.add_argument('-o','--output',dest='output',n... | Copy specified id to stack. copy -h for detailed help. |
def add_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False):
"""
Adds the given text in the image.
:param img: Input image
:param text: String text
:param pos: (x, y) in the image or relative to the given Box object
:param box: Box object. If not None, the text ... | Adds the given text in the image.
:param img: Input image
:param text: String text
:param pos: (x, y) in the image or relative to the given Box object
:param box: Box object. If not None, the text is placed inside the box.
:param color: Color of the text.
:param thickness: Thickness of the font... |
def intersection(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Intersection between self and moc. ``delta_t`` gives the possibility to the user
to set a time resolution for performing the tmoc intersection
Parameters
----------
another_moc : `~mocpy.abstract_... | Intersection between self and moc. ``delta_t`` gives the possibility to the user
to set a time resolution for performing the tmoc intersection
Parameters
----------
another_moc : `~mocpy.abstract_moc.AbstractMOC`
the MOC/TimeMOC used for performing the intersection with self... |
def print_email(message, app):
"""Print mail to stream.
Signal handler for email_dispatched signal. Prints by default the output
to the stream specified in the constructor of InvenioMail.
:param message: Message object.
:param app: Flask application object.
"""
invenio_mail = app.extension... | Print mail to stream.
Signal handler for email_dispatched signal. Prints by default the output
to the stream specified in the constructor of InvenioMail.
:param message: Message object.
:param app: Flask application object. |
def new_geom(geom_type, size, pos=(0, 0, 0), rgba=RED, group=0, **kwargs):
"""
Creates a geom element with attributes specified by @**kwargs.
Args:
geom_type (str): type of the geom.
see all types here: http://mujoco.org/book/modeling.html#geom
size: geom size parameters.
... | Creates a geom element with attributes specified by @**kwargs.
Args:
geom_type (str): type of the geom.
see all types here: http://mujoco.org/book/modeling.html#geom
size: geom size parameters.
pos: 3d position of the geom frame.
rgba: color and transparency. Defaults to... |
def read_cell(self, x, y):
"""
reads the cell at position x and y; puts the default styles in xlwt
"""
cell = self._sheet.row(x)[y]
if self._file.xf_list[
cell.xf_index].background.pattern_colour_index == 64:
self._file.xf_list[
cell.xf... | reads the cell at position x and y; puts the default styles in xlwt |
def bna_config_cmd_status_input_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
bna_config_cmd_status = ET.Element("bna_config_cmd_status")
config = bna_config_cmd_status
input = ET.SubElement(bna_config_cmd_status, "input")
se... | Auto Generated Code |
def _get_template(self, event, ctype, fields):
"""Gets the contents of the template for the specified event and type
with all the fields replaced.
:arg event: one of ['start', 'error', 'success', 'timeout', 'failure'].
:arg ctype: one of ["txt", "html"] specifying which template... | Gets the contents of the template for the specified event and type
with all the fields replaced.
:arg event: one of ['start', 'error', 'success', 'timeout', 'failure'].
:arg ctype: one of ["txt", "html"] specifying which template to use.
:arg fields: a dictionary of fields and t... |
def _build_gui(self):
"""
Removes all existing sliders and rebuilds them based on the colormap.
"""
# remove all widgets (should destroy all children too)
self._central_widget.deleteLater()
# remove all references to other controls
self._sliders = [... | Removes all existing sliders and rebuilds them based on the colormap. |
def plot_forward_models(self, maglim=None, phalim=None, **kwargs):
"""Create plots of the forward models
Returns
-------
mag_fig: dict
Dictionary containing the figure and axes objects of the magnitude
plots
"""
return_dict = {}
N = len(... | Create plots of the forward models
Returns
-------
mag_fig: dict
Dictionary containing the figure and axes objects of the magnitude
plots |
def _arrays_to_sections(self, arrays):
'''
input: unprocessed numpy arrays.
returns: columns of the size that they will appear in the image, not scaled
for display. That needs to wait until after variance is computed.
'''
sections = []
sections_to_resize_later = {}
show_all = se... | input: unprocessed numpy arrays.
returns: columns of the size that they will appear in the image, not scaled
for display. That needs to wait until after variance is computed. |
def AddClientKeywords(self, client_id, keywords):
"""Associates the provided keywords with the client."""
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id)
for kw in keywords:
self.keywords.setdefault(kw, {})
self.keywords[kw][client_id] = rdfvalue.RDFDatetime.Now... | Associates the provided keywords with the client. |
def data_slice(self, slice_ind):
""" Returns a slice of datapoints """
if self.height is None:
return self.data[slice_ind]
return self.data[slice_ind, ...] | Returns a slice of datapoints |
def pfopen(self, event=None):
""" Load the parameter settings from a user-specified file. """
# Get the selected file name
fname = self._openMenuChoice.get()
# Also allow them to simply find any file - do not check _task_name_...
# (could use tkinter's FileDialog, but this one ... | Load the parameter settings from a user-specified file. |
def add_poisson(image, exp_time):
"""
adds a poison (or Gaussian) distributed noise with mean given by surface brightness
:param image: pixel values (photon counts per unit exposure time)
:param exp_time: exposure time
:return: Poisson noise realization of input image
"""
"""
adds a pois... | adds a poison (or Gaussian) distributed noise with mean given by surface brightness
:param image: pixel values (photon counts per unit exposure time)
:param exp_time: exposure time
:return: Poisson noise realization of input image |
def ParseZeitgeistEventRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses a zeitgeist event row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... | Parses a zeitgeist event row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. |
def _parse_key(stream):
"""Parse key, value combination
returns :
Parsed key (string)
"""
logger.debug("parsing key")
key = stream.advance_past_chars(["="])
logger.debug("parsed key:")
logger.debug("%s", fmt_green(key))
return key | Parse key, value combination
returns :
Parsed key (string) |
def setShapeClass(self, vehID, clazz):
"""setShapeClass(string, string) -> None
Sets the shape class for this vehicle.
"""
self._connection._sendStringCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_SHAPECLASS, vehID, clazz) | setShapeClass(string, string) -> None
Sets the shape class for this vehicle. |
def embed(self, title=''):
"""Start an IPython embed
Calling embed won't do anything in a multithread context
The stack_depth will be found automatically
"""
if self.embed_disabled:
self.warning_log("Embed is disabled when runned from the grid runner because of the ... | Start an IPython embed
Calling embed won't do anything in a multithread context
The stack_depth will be found automatically |
def ack(self):
"""Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
"""
if self.acknowledged:
raise self.MessageStateError... | Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected. |
def _merge_variables(new, cur):
"""Add any new variables to the world representation in cur.
Replaces any variables adjusted by previous steps.
"""
new_added = set([])
out = []
for cur_var in cur:
updated = False
for new_var in new:
if get_base_id(new_var["id"]) == g... | Add any new variables to the world representation in cur.
Replaces any variables adjusted by previous steps. |
def create_entity_type(project_id, display_name, kind):
"""Create an entity type with the given display name."""
import dialogflow_v2 as dialogflow
entity_types_client = dialogflow.EntityTypesClient()
parent = entity_types_client.project_agent_path(project_id)
entity_type = dialogflow.types.EntityT... | Create an entity type with the given display name. |
def coords_by_cutoff(self, cutoff=0.80):
""" Returns fitted coordinates in as many dimensions as are needed to
explain a given amount of variance (specified in the cutoff) """
i = np.where(self.cve >= cutoff)[0][0]
coords_matrix = self.vecs[:, :i + 1]
return coords_matrix, self.... | Returns fitted coordinates in as many dimensions as are needed to
explain a given amount of variance (specified in the cutoff) |
def is_integer(value, min=None, max=None):
"""
A check that tests that a given value is an integer (int, or long)
and optionally, between bounds. A negative value is accepted, while
a float will fail.
If the value is a string, then the conversion is done - if possible.
Otherwise a VdtError is r... | A check that tests that a given value is an integer (int, or long)
and optionally, between bounds. A negative value is accepted, while
a float will fail.
If the value is a string, then the conversion is done - if possible.
Otherwise a VdtError is raised.
>>> vtor = Validator()
>>> vtor.check('... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.