code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def match_check(self, regex, fun):
'''
Validate a single regex to function comparison, the function argument
can be a list of functions. It is all or nothing for a list of
functions
'''
vals = []
if isinstance(fun, six.string_types):
fun = [fun]
... | Validate a single regex to function comparison, the function argument
can be a list of functions. It is all or nothing for a list of
functions |
def clean_account(self):
"""Ensure this is an income account"""
account = self.cleaned_data['account']
if not account:
return
if account.type != Account.TYPES.income:
raise ValidationError('Account must be an income account')
try:
account.hou... | Ensure this is an income account |
def parseStr(self, html):
'''
parseStr - Parses a string and creates the DOM tree and indexes.
@param html <str> - valid HTML
'''
self.reset()
if isinstance(html, bytes):
self.feed(html.decode(self.encoding))
else:
self.feed(h... | parseStr - Parses a string and creates the DOM tree and indexes.
@param html <str> - valid HTML |
def data_from_dict(self, data):
"""
Populate model parameters from a dictionary of parameters
Parameters
----------
data : dict
List of parameter dictionaries
Returns
-------
None
"""
nvars = []
for key, val in data.i... | Populate model parameters from a dictionary of parameters
Parameters
----------
data : dict
List of parameter dictionaries
Returns
-------
None |
def add_get(self, path: str, handler: _WebHandler, *,
name: Optional[str]=None, allow_head: bool=True,
**kwargs: Any) -> AbstractRoute:
"""
Shortcut for add_route with method GET, if allow_head is true another
route is added allowing head requests to the same endp... | Shortcut for add_route with method GET, if allow_head is true another
route is added allowing head requests to the same endpoint |
def clean_time(time_string):
"""Return a datetime from the Amazon-provided datetime string"""
# Get a timezone-aware datetime object from the string
time = dateutil.parser.parse(time_string)
if not settings.USE_TZ:
# If timezone support is not active, convert the time to UTC and
# remove... | Return a datetime from the Amazon-provided datetime string |
def RunMetadata(self, tag):
"""Given a tag, return the associated session.run() metadata.
Args:
tag: A string tag associated with the event.
Raises:
ValueError: If the tag is not found.
Returns:
The metadata in form of `RunMetadata` proto.
"""
if tag not in self._tagged_meta... | Given a tag, return the associated session.run() metadata.
Args:
tag: A string tag associated with the event.
Raises:
ValueError: If the tag is not found.
Returns:
The metadata in form of `RunMetadata` proto. |
def store_transition(self, frame, action, reward, done, extra_info=None):
""" Store given transition in the backend """
self.current_idx = (self.current_idx + 1) % self.buffer_capacity
self.state_buffer[self.current_idx] = frame
self.action_buffer[self.current_idx] = action
self... | Store given transition in the backend |
def detect_all_faces(image, cascade = None, sampler = None, threshold = 0, overlaps = 1, minimum_overlap = 0.2, relative_prediction_threshold = 0.25):
"""detect_all_faces(image, [cascade], [sampler], [threshold], [overlaps], [minimum_overlap], [relative_prediction_threshold]) -> bounding_boxes, qualities
Detects a... | detect_all_faces(image, [cascade], [sampler], [threshold], [overlaps], [minimum_overlap], [relative_prediction_threshold]) -> bounding_boxes, qualities
Detects all faces in the given image, whose prediction values are higher than the given threshold.
If the given ``minimum_overlap`` is lower than 1, overlapping b... |
def generate_blob_names(self):
"""
Generate blob names for each one of the edge. At this time, Keras does not
support "fork" operation (a layer with more than 1 blob output). So we just
use names of the src layer to identify a blob. We also assume all neural
networks are singly... | Generate blob names for each one of the edge. At this time, Keras does not
support "fork" operation (a layer with more than 1 blob output). So we just
use names of the src layer to identify a blob. We also assume all neural
networks are singly-connected graphs - which should be the case. |
def absolute_magnitude(self, richness=1, steps=1e4):
"""
Calculate the absolute visual magnitude (Mv) from the richness
by transforming the isochrone in the SDSS system and using the
g,r -> V transform equations from Jester 2005
[astro-ph/0506022].
Parameters:
-... | Calculate the absolute visual magnitude (Mv) from the richness
by transforming the isochrone in the SDSS system and using the
g,r -> V transform equations from Jester 2005
[astro-ph/0506022].
Parameters:
-----------
richness : isochrone normalization parameter
s... |
def get(img, light=False):
"""Get colorscheme."""
colors = gen_colors(img)
return adjust(colors, light) | Get colorscheme. |
def _import_component(name):
"""
Returns a class, function, or class method specified by the fully qualified
name.
"""
for f in (_get_from_module, _get_from_class):
try:
return f(name)
except:
pass
log.debug("Couldn't load %s" % name) | Returns a class, function, or class method specified by the fully qualified
name. |
def _ParseFileData(self, knowledge_base, file_object):
"""Parses file content (data) for user account preprocessing attributes.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.... | Parses file content (data) for user account preprocessing attributes.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessin... |
def zone_exists(zone, region=None, key=None, keyid=None, profile=None,
retry_on_rate_limit=None, rate_limit_retries=None,
retry_on_errors=True, error_retries=5):
'''
Check for the existence of a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt... | Check for the existence of a Route53 hosted zone.
.. versionadded:: 2015.8.0
CLI Example::
salt myminion boto_route53.zone_exists example.org |
def get_field_choices(self, field, field_name):
"""
Returns the valid choices for ``field``. The ``field_name`` argument is given for
convenience.
"""
if self.request.GET.get('select2'):
names = ['id', 'text']
else:
names = ['value', 'text']
... | Returns the valid choices for ``field``. The ``field_name`` argument is given for
convenience. |
def initialize_config_values(parsed):
"""Given the parsed args, initialize the dbt tracking code.
It would be nice to re-use this profile later on instead of parsing it
twice, but dbt's intialization is not structured in a way that makes that
easy.
"""
try:
cfg = UserConfig.from_directo... | Given the parsed args, initialize the dbt tracking code.
It would be nice to re-use this profile later on instead of parsing it
twice, but dbt's intialization is not structured in a way that makes that
easy. |
def get_vtkjs_url(*args):
"""After using ``export_vtkjs()`` to create a ``.vtkjs`` file from a
data scene which is uploaded to an online file hosting service like Dropbox,
use this method to get a shareable link to that scene on the
`PVGeo VTKjs viewer`_.
.. _PVGeo VTKjs viewer: http://viewer.vtki.... | After using ``export_vtkjs()`` to create a ``.vtkjs`` file from a
data scene which is uploaded to an online file hosting service like Dropbox,
use this method to get a shareable link to that scene on the
`PVGeo VTKjs viewer`_.
.. _PVGeo VTKjs viewer: http://viewer.vtki.org
**Current file hosts sup... |
def _x_start_ok(self, client_properties, mechanism, response, locale):
"""Select security mechanism and locale
This method selects a SASL security mechanism. ASL uses SASL
(RFC2222) to negotiate authentication and encryption.
PARAMETERS:
client_properties: table
... | Select security mechanism and locale
This method selects a SASL security mechanism. ASL uses SASL
(RFC2222) to negotiate authentication and encryption.
PARAMETERS:
client_properties: table
client properties
mechanism: shortstr
selected... |
def select_renderer(request: web.Request, renderers: OrderedDict, force=True):
"""
Given a request, a list of renderers, and the ``force`` configuration
option, return a two-tuple of:
(media type, render callable). Uses mimeparse to find the best media
type match from the ACCEPT header.
"""
... | Given a request, a list of renderers, and the ``force`` configuration
option, return a two-tuple of:
(media type, render callable). Uses mimeparse to find the best media
type match from the ACCEPT header. |
def get_arguments(self):
""" Gets the arguments from the command line. """
parser = argparse.ArgumentParser(
description='Downloads images from given URL')
parser.add_argument('url2scrape', nargs=1, help="URL to scrape")
parser.add_argument('-m', '--max-images', type=int, de... | Gets the arguments from the command line. |
def _pour(opener, flags=0, *args, **kwargs):
"""A flexible pouring facility that knows how to enumerate entry data."""
with _enumerator(opener,
*args,
entry_cls=_ArchiveEntryItState,
**kwargs) as r:
ext = libarchive.calls.archive_write.c_ar... | A flexible pouring facility that knows how to enumerate entry data. |
def dotplot(adata, var_names, groupby=None, use_raw=None, log=False, num_categories=7,
expression_cutoff=0., mean_only_expressed=False, color_map='Reds', dot_max=None,
dot_min=None, figsize=None, dendrogram=False, gene_symbols=None,
var_group_positions=None, standard_scale=None, smal... | \
Makes a *dot plot* of the expression values of `var_names`.
For each var_name and each `groupby` category a dot is plotted. Each dot
represents two values: mean expression within each category (visualized by
color) and fraction of cells expressing the var_name in the
category (visualized by the s... |
def get_assignable_bank_ids(self, bank_id):
"""Gets a list of bank including and under the given bank node in which any assessment part can be assigned.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.id.IdList) - list of assignable bank ``Ids``
raise: NullArgume... | Gets a list of bank including and under the given bank node in which any assessment part can be assigned.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.id.IdList) - list of assignable bank ``Ids``
raise: NullArgument - ``bank_id`` is ``null``
raise: OperationF... |
def map_url_to_cache_id(self, url):
"""use of the url resource location as cached id
e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html``
- map the url to local file
:param url:
:type url:
:return:
:rtype:
"""
base, _ = self.get_dom... | use of the url resource location as cached id
e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html``
- map the url to local file
:param url:
:type url:
:return:
:rtype: |
def list_lv_grid_districts(self, session, lv_stations):
"""Imports all lv grid districts within given load area
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
lv_stations:
List required LV_stations==LV districts.
... | Imports all lv grid districts within given load area
Parameters
----------
session : sqlalchemy.orm.session.Session
Database session
lv_stations:
List required LV_stations==LV districts.
Returns
-------
pandas Dataframe
Table ... |
def execProcCmd(self, *args):
"""Execute ps command with positional params args and return result as
list of lines.
@param *args: Positional params for ps command.
@return: List of output lines
"""
out = util.exec_command([psCmd,] + list(args))
... | Execute ps command with positional params args and return result as
list of lines.
@param *args: Positional params for ps command.
@return: List of output lines |
def _get_template_name(self):
'''Find template name.
:returns: string of template name
:raises: NonextantTemplateNameException
'''
start_pattern = r"sys application template\s+" \
r"(\/[\w\.\-]+\/)?" \
r"(?P<name>[\w\.\-]+)\s*\{"
... | Find template name.
:returns: string of template name
:raises: NonextantTemplateNameException |
def read_var_int(self, max_size=sys.maxsize):
"""
Read a variable length integer from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max_size (int): (Optional) maximum... | Read a variable length integer from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max_size (int): (Optional) maximum number of bytes to read.
Returns:
int: |
def reverse_set(self, subid, ipaddr, entry, params=None):
''' /v1/server/reverse_set_ipv4
POST - account
Set a reverse DNS entry for an IPv4 address of a virtual machine. Upon
success, DNS changes may take 6-12 hours to become active.
Link: https://www.vultr.com/api/#server_reve... | /v1/server/reverse_set_ipv4
POST - account
Set a reverse DNS entry for an IPv4 address of a virtual machine. Upon
success, DNS changes may take 6-12 hours to become active.
Link: https://www.vultr.com/api/#server_reverse_set_ipv4 |
def compute_pointwise_distances(self, other, default=None):
"""
Compute the minimal distance between each point on self and other.
Parameters
----------
other : tuple of number \
or imgaug.augmentables.kps.Keypoint \
or imgaug.augmentables.LineStr... | Compute the minimal distance between each point on self and other.
Parameters
----------
other : tuple of number \
or imgaug.augmentables.kps.Keypoint \
or imgaug.augmentables.LineString
Other object to which to compute the distances.
default... |
def main():
"""
NAME
di_rot.py
DESCRIPTION
rotates set of directions to new coordinate system
SYNTAX
di_rot.py [command line options]
OPTIONS
-h prints help message and quits
-f specify input file, default is standard input
-F specify output file, d... | NAME
di_rot.py
DESCRIPTION
rotates set of directions to new coordinate system
SYNTAX
di_rot.py [command line options]
OPTIONS
-h prints help message and quits
-f specify input file, default is standard input
-F specify output file, default is standard outpu... |
def insert(self, key, minhash, check_duplication=True):
'''
Insert a key to the index, together
with a MinHash (or weighted MinHash) of the set referenced by
the key.
:param str key: The identifier of the set.
:param datasketch.MinHash minhash: The MinHash of the set.
... | Insert a key to the index, together
with a MinHash (or weighted MinHash) of the set referenced by
the key.
:param str key: The identifier of the set.
:param datasketch.MinHash minhash: The MinHash of the set.
:param bool check_duplication: To avoid duplicate keys in the storage... |
def search_ipv6_environment(self, ipv6, id_environment):
"""Get IPv6 with an associated environment.
:param ipv6: IPv6 address in the format x1:x2:x3:x4:x5:x6:x7:x8.
:param id_environment: Environment identifier. Integer value and greater than zero.
:return: Dictionary with the followi... | Get IPv6 with an associated environment.
:param ipv6: IPv6 address in the format x1:x2:x3:x4:x5:x6:x7:x8.
:param id_environment: Environment identifier. Integer value and greater than zero.
:return: Dictionary with the following structure:
::
{'ipv6': {'id': < id >,
... |
def clear(self, match="*", count=1000):
""" Removes all |{key: value}| entries in :prop:key_prefix of
:prop:_client
"""
cursor = '0'
while cursor != 0:
cursor, keys = self.scan(cursor=cursor, match=match, count=count)
if keys:
self._cli... | Removes all |{key: value}| entries in :prop:key_prefix of
:prop:_client |
def set(self, value: Optional[bool]):
"""Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown)
"""
prev_value = self._value
self._value = value
if self._value != prev_value:
# notify all watc... | Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown) |
def _get_autoscaling_min_max(template, parameters, asg_name):
"""Helper to extract the configured MinSize, MaxSize attributes from the
template.
:param template: cloudformation template (json)
:param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'}
:param asg_name: logical resourc... | Helper to extract the configured MinSize, MaxSize attributes from the
template.
:param template: cloudformation template (json)
:param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'}
:param asg_name: logical resource name of the autoscaling group
:return: MinSize, MaxSize |
def normalize_hex(hex_value):
"""
Normalize a hexadecimal color value to 6 digits, lowercase.
"""
match = HEX_COLOR_RE.match(hex_value)
if match is None:
raise ValueError(
u"'{}' is not a valid hexadecimal color value.".format(hex_value)
)
hex_digits = match.group(1)... | Normalize a hexadecimal color value to 6 digits, lowercase. |
def leave_chat(
self,
chat_id: Union[int, str],
delete: bool = False
):
"""Use this method to leave a group chat or channel.
Args:
chat_id (``int`` | ``str``):
Unique identifier for the target chat or username of the target channel/supergroup
... | Use this method to leave a group chat or channel.
Args:
chat_id (``int`` | ``str``):
Unique identifier for the target chat or username of the target channel/supergroup
(in the format @username).
delete (``bool``, *optional*):
Deletes the ... |
def generate(self, vars=None, env=None):
"""Generate this template with the given arguments."""
def defined(v, default=None):
_v = default
if v in vars:
_v = vars[v]
elif v in env:
_v = env[v]
return _v
na... | Generate this template with the given arguments. |
def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443,
sslflags=0):
'''
Assign a certificate to an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
The web binding that the certificate is being assigned to must already
exist.
Arg... | Assign a certificate to an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
The web binding that the certificate is being assigned to must already
exist.
Args:
name (str): The thumbprint of the certificate.
site (str): The IIS site name.
hostheader (str): Th... |
def add_suffix(path, suffix=""):
"""Adds a suffix to a filename *path*"""
return join(dirname(path), basename(path, ext=False) + suffix + extname(path)) | Adds a suffix to a filename *path* |
def get_nonce_timestamp(nonce):
'''
Extract the timestamp from a Nonce. To be sure the timestamp was generated by this site,
make sure you validate the nonce using validate_nonce().
'''
components = nonce.split(':',2)
if not len(components) == 3:
return None
try:
return floa... | Extract the timestamp from a Nonce. To be sure the timestamp was generated by this site,
make sure you validate the nonce using validate_nonce(). |
def build_dot(self):
"""Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object.
"""
from graphviz import Digraph
# Build GraphViz Digraph
dot = Digraph()
dot.attr("graph",
bgcolor=self.theme["background_color"],
color... | Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object. |
def get_image_and_mask(self, label, positive_only=True, hide_rest=False,
num_features=5, min_weight=0.):
"""Init function.
Args:
label: label to explain
positive_only: if True, only take superpixels that contribute to
the prediction of ... | Init function.
Args:
label: label to explain
positive_only: if True, only take superpixels that contribute to
the prediction of the label. Otherwise, use the top
num_features superpixels, which can be positive or negative
towards the label... |
def check_field_multiplicity(tag, previous_tags):
"""
Check the multiplicity of a 'field' for an object.
"""
fail = False
#If the field is single
if not tag.field.multiple:
#If the tag is being created...
if not tag.id:
#... and the new field was already included in t... | Check the multiplicity of a 'field' for an object. |
def parse_conservation(variant, info_key):
"""Get the conservation prediction
Args:
variant(dict): A variant dictionary
info_key(str)
Returns:
conservations(list): List of censervation terms
"""
raw_score = variant.INFO.get(info_key)
conservations = ... | Get the conservation prediction
Args:
variant(dict): A variant dictionary
info_key(str)
Returns:
conservations(list): List of censervation terms |
def render(template, **kwargs):
"""
Renders the HTML containing provided summaries.
The summary has to be an instance of summary.Summary,
or at least contain similar properties: title, image, url,
description and collections: titles, images, descriptions.
"""
import jinja2
imp... | Renders the HTML containing provided summaries.
The summary has to be an instance of summary.Summary,
or at least contain similar properties: title, image, url,
description and collections: titles, images, descriptions. |
def compute(self, feedforwardInput=(), lateralInputs=(),
feedforwardGrowthCandidates=None, learn=True,
predictedInput = None,):
"""
Runs one time step of the column pooler algorithm.
@param feedforwardInput (sequence)
Sorted indices of active feedforward input bits
... | Runs one time step of the column pooler algorithm.
@param feedforwardInput (sequence)
Sorted indices of active feedforward input bits
@param lateralInputs (list of sequences)
For each lateral layer, a list of sorted indices of active lateral
input bits
@param feedfo... |
def execute_task(task_id,
verbosity=None,
runmode='run',
sigmode=None,
monitor_interval=5,
resource_monitor_interval=60):
'''Execute single or master task, return a dictionary'''
tf = TaskFile(task_id)
# this will automati... | Execute single or master task, return a dictionary |
def parseTimestamp(s):
"""
Parses a textual datetime format and return a Python datetime object.
The supported format is: ``yyyy-mm-dd h:m:s.ms``
The time component is optional.
- hours are 00..23 (no AM/PM)
- minutes are 00..59
- seconds are 00..59
- micro-seconds are 000000..999999
:param s: (st... | Parses a textual datetime format and return a Python datetime object.
The supported format is: ``yyyy-mm-dd h:m:s.ms``
The time component is optional.
- hours are 00..23 (no AM/PM)
- minutes are 00..59
- seconds are 00..59
- micro-seconds are 000000..999999
:param s: (string) input time text
:return... |
def finalise(self):
"""Remove conflict requests, detect cyclic dependencies, and reorder
packages wrt dependency and then request order.
Returns:
A new copy of the phase with conflict requests removed and packages
correctly ordered; or, if cyclic dependencies were detect... | Remove conflict requests, detect cyclic dependencies, and reorder
packages wrt dependency and then request order.
Returns:
A new copy of the phase with conflict requests removed and packages
correctly ordered; or, if cyclic dependencies were detected, a new
phase mar... |
def _cas_1(self):
'''1 - The desired structure is entirely contained into one image.'''
lonc = self._format_lon(self.lonm)
latc = self._format_lat(self.latm)
img = self._format_name_map(lonc, latc)
img_map = BinaryTable(img, self.path_pdsfiles)
return img_map.extract_gr... | 1 - The desired structure is entirely contained into one image. |
def _executor(self, host):
''' handler for multiprocessing library '''
try:
exec_rc = self._executor_internal(host)
#if type(exec_rc) != ReturnData and type(exec_rc) != ansible.runner.return_data.ReturnData:
# raise Exception("unexpected return type: %s" % type(ex... | handler for multiprocessing library |
def list(self, var, cast=None, default=NOTSET):
"""
:rtype: list
"""
return self.get_value(var, cast=list if not cast else [cast], default=default) | :rtype: list |
def status(self, head):
"""Get status from server.
head - Ping the the head node if True.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if head:
sock.connect((self.server, self.port))
else:
sock.connect((self.server2, self.port2))
... | Get status from server.
head - Ping the the head node if True. |
def from_twodim_list(cls, datalist, tsformat=None, dimensions=1):
"""Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used... | Creates a new MultiDimensionalTimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefined format,
the second is a list, con... |
def create_query_constraint():
""" Create a constraint for a query WHERE clause """
op = oneOf("= < > >= <= != <>", caseless=True).setName("operator")
basic_constraint = (var + op + var_val).setResultsName("operator")
between = (
var + Suppress(upkey("between")) + value + Suppress(and_) + value
... | Create a constraint for a query WHERE clause |
def qteGetAppletFromWidget(widgetObj):
"""
Return the parent applet of ``widgetObj``.
|Args|
* ``widgetObj`` (**QWidget**): widget (if any) for which the
containing applet is requested.
|Returns|
* **QtmacsApplet**: the applet containing ``widgetObj`` or **None**.
|Raises|
* ... | Return the parent applet of ``widgetObj``.
|Args|
* ``widgetObj`` (**QWidget**): widget (if any) for which the
containing applet is requested.
|Returns|
* **QtmacsApplet**: the applet containing ``widgetObj`` or **None**.
|Raises|
* **None** |
def return_tip(self) -> 'InstrumentContext':
"""
If a tip is currently attached to the pipette, then it will return the
tip to it's location in the tiprack.
It will not reset tip tracking so the well flag will remain False.
:returns: This instance
"""
if not sel... | If a tip is currently attached to the pipette, then it will return the
tip to it's location in the tiprack.
It will not reset tip tracking so the well flag will remain False.
:returns: This instance |
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if sys.ver... | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class. |
def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool:
"""
Does a CGI form contain the key?
"""
s = get_cgi_parameter_str(form, key)
return s is not None | Does a CGI form contain the key? |
def fetch(self, vault_client):
"""Updates the context based on the contents of the Vault
server. Note that some resources can not be read after
they have been written to and it is up to those classes
to handle that case properly."""
backends = [(self.mounts, SecretBackend),
... | Updates the context based on the contents of the Vault
server. Note that some resources can not be read after
they have been written to and it is up to those classes
to handle that case properly. |
def attach_to_container(self, container_id):
""" A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket
object and close_socket() to close the connection """
sock = self._docker.containers.get(container_id).attach_socket... | A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket
object and close_socket() to close the connection |
def nrzi(data):
'''
Packet uses NRZI (non-return to zero inverted) encoding, which means
that a 0 is encoded as a change in tone, and a 1 is encoded as
no change in tone.
'''
current = True
for bit in data:
if not bit:
current = not current
yield current | Packet uses NRZI (non-return to zero inverted) encoding, which means
that a 0 is encoded as a change in tone, and a 1 is encoded as
no change in tone. |
def multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits):
"""
Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss... | Args:
multilevel_anchors: #lvl RPNAnchors
multilevel_label_logits: #lvl tensors of shape HxWxA
multilevel_box_logits: #lvl tensors of shape HxWxAx4
Returns:
label_loss, box_loss |
def require_request_model(cls, validate=True):
"""
Makes a handler require that a request body that map towards the given
model is provided. Unless the ``validate`` option is set to ``False`` the
data will be validated against the model's fields.
The model will be passed to the handler as the last ... | Makes a handler require that a request body that map towards the given
model is provided. Unless the ``validate`` option is set to ``False`` the
data will be validated against the model's fields.
The model will be passed to the handler as the last positional argument. ::
@require_request_model(Mod... |
def __start_command_queue_listener(self):
"""Start the function __command_queue_listener in a separate thread. This
function continuously listens to the pipe connected to the frontend.
"""
thread_function = self.__command_queue_listener
class QueueListenerThread(threading.Thread... | Start the function __command_queue_listener in a separate thread. This
function continuously listens to the pipe connected to the frontend. |
def __build_level(self, previous_level_blocks, level):
"""!
@brief Build new level of directory.
@param[in] previous_level_blocks (list): BANG-blocks on the previous level.
@param[in] level (uint): Level number that should be built.
@return (list) New block on the specif... | !
@brief Build new level of directory.
@param[in] previous_level_blocks (list): BANG-blocks on the previous level.
@param[in] level (uint): Level number that should be built.
@return (list) New block on the specified level. |
def get_partial_object(self, bucket_name, object_name, offset=0, length=0, request_headers=None, sse=None):
"""
Retrieves an object from a bucket.
Optionally takes an offset and length of data to retrieve.
This function returns an object that contains an open network
connection... | Retrieves an object from a bucket.
Optionally takes an offset and length of data to retrieve.
This function returns an object that contains an open network
connection to enable incremental consumption of the
response. To re-use the connection (if desired) on subsequent
requests... |
def parse_section_data_files(self, section_options):
"""Parses `data_files` configuration file section.
:param dict section_options:
"""
parsed = self._parse_section_to_dict(section_options, self._parse_list)
self['data_files'] = [(k, v) for k, v in parsed.items()] | Parses `data_files` configuration file section.
:param dict section_options: |
def start_client(self, language):
"""Start an LSP client for a given language."""
started = False
if language in self.clients:
language_client = self.clients[language]
queue = self.register_queue[language]
# Don't start LSP services when testing unless we dem... | Start an LSP client for a given language. |
def getfile(object):
"""Work out which source or compiled file an object was defined in."""
if ismodule(object):
if hasattr(object, '__file__'):
return object.__file__
raise TypeError, 'arg is a built-in module'
if isclass(object):
object = sys.modules.get(object.__module... | Work out which source or compiled file an object was defined in. |
def calling_convention(self):
"""function calling convention. See
:class:CALLING_CONVENTION_TYPES class for possible values"""
if self._calling_convention is None:
self._calling_convention = \
calldef_types.CALLING_CONVENTION_TYPES.extract(self.attributes)
... | function calling convention. See
:class:CALLING_CONVENTION_TYPES class for possible values |
def rmap(fn, coll, is_iterable=None):
"""A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]]
"""
result = []
for x in ... | A recursive map
:param fn: a function
:param coll: a list
:param isiterable: a predicate function determining whether a value is iterable.
:returns: a list
>>> rmap(lambda x: 2*x, [1, 2, [3, 4]])
[2, 4, [6, 8]] |
def decode_coords(ds, gridfile=None):
"""
Sets the coordinates and bounds in a dataset
This static method sets those coordinates and bounds that are marked
marked in the netCDF attributes as coordinates in :attr:`ds` (without
deleting them from the variable attributes because th... | Sets the coordinates and bounds in a dataset
This static method sets those coordinates and bounds that are marked
marked in the netCDF attributes as coordinates in :attr:`ds` (without
deleting them from the variable attributes because this information is
necessary for visualizing the da... |
def fit_mle(self, data, init_vals=(80, 80)):
"""%(super)s
In addition to data, can take init_vals which allows the user to
specify initial values for (alpha, theta) during the optimization.
"""
if len(data) > 1:
mu = np.mean(data)
var = np.var(data)
... | %(super)s
In addition to data, can take init_vals which allows the user to
specify initial values for (alpha, theta) during the optimization. |
def is_ssl_error(error=None):
"""Checks if the given error (or the current one) is an SSL error."""
if error is None:
error = sys.exc_info()[1]
from OpenSSL import SSL
return isinstance(error, SSL.Error) | Checks if the given error (or the current one) is an SSL error. |
def attach_schema(self, schem):
"""Add a tuple schema to this object (externally imposed)"""
self.tuple_schema = schema.AndSchema.make(self.tuple_schema, schem) | Add a tuple schema to this object (externally imposed) |
def setupHeaderMenu(self, menu, index):
"""
Updates the header right-click menu to include grouping options if
desired.
:param menu | <QMenu>
index | <int>
"""
if not self.userGroupingEnabled():
return False
... | Updates the header right-click menu to include grouping options if
desired.
:param menu | <QMenu>
index | <int> |
def add_device(dev):
"""Adds a device to the list of devices we know about."""
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
# This device is already in our list. ... | Adds a device to the list of devices we know about. |
def _encode_decode_decorator(func):
"""decorator for encoding and decoding geoms"""
def wrapper(*args):
"""error catching"""
try:
processed_geom = func(*args)
return processed_geom
except ImportError as err:
raise ImportError('The Python package `shape... | decorator for encoding and decoding geoms |
def key_dict( from_dict ):
"""Returns dict from_dict['unicode_save_field'] = 'original key with unicode' """
new_dict = {}
old2new = {}
new2old = {}
for key in from_dict:
k = normalizeUnicode(key,'identifier')
if k != key:
i = ''
while new_dict.has_key("%s%s" % (k,i) ):
if not i:
i = 1
else:... | Returns dict from_dict['unicode_save_field'] = 'original key with unicode' |
def close(self):
'''
Terminates the session. It schedules the ``close()`` coroutine
of the underlying aiohttp session and then enqueues a sentinel
object to indicate termination. Then it waits until the worker
thread to self-terminate by joining.
'''
if self._cl... | Terminates the session. It schedules the ``close()`` coroutine
of the underlying aiohttp session and then enqueues a sentinel
object to indicate termination. Then it waits until the worker
thread to self-terminate by joining. |
def get_heron_dir():
"""
This will extract heron directory from .pex file.
For example,
when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and
its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc',
the internal variable ``... | This will extract heron directory from .pex file.
For example,
when __file__ is '/Users/heron-user/bin/heron/heron/tools/common/src/python/utils/config.pyc', and
its real path is '/Users/heron-user/.heron/bin/heron/tools/common/src/python/utils/config.pyc',
the internal variable ``path`` would be '/Users/heron... |
def get(self, *args, **kwargs):
"""Return the single item from the filtered queryset."""
assert not args
assert list(kwargs.keys()) == ['pk']
pk = kwargs['pk']
model_name = self.model.__name__
object_spec = (model_name, pk, None)
instances = self.cache.get_instanc... | Return the single item from the filtered queryset. |
def has_control_chars(i):
""" Returns true if the passed token is an unknown string
or a constant string having control chars (inverse, etc
"""
if not hasattr(i, 'type_'):
return False
if i.type_ != Type.string:
return False
if i.token in ('VAR',... | Returns true if the passed token is an unknown string
or a constant string having control chars (inverse, etc |
def _calculate_menu_wh(self):
""" Calculate menu widht and height."""
w = iw = 50
h = ih = 0
# menu.index returns None if there are no choices
index = self._menu.index(tk.END)
index = index if index is not None else 0
count = index + 1
# First calculate u... | Calculate menu widht and height. |
def point_source_list(self, kwargs_ps, kwargs_lens, k=None):
"""
returns the coordinates and amplitudes of all point sources in a single array
:param kwargs_ps:
:param kwargs_lens:
:return:
"""
ra_list, dec_list = self.image_position(kwargs_ps, kwargs_lens, k=k)
... | returns the coordinates and amplitudes of all point sources in a single array
:param kwargs_ps:
:param kwargs_lens:
:return: |
def impulse_deltav_general_curvedstream(v,x,b,w,x0,v0,pot):
"""
NAME:
impulse_deltav_general_curvedstream
PURPOSE:
calculate the delta velocity to due an encounter with a general spherical potential in the impulse approximation; allows for arbitrary velocity vectors and arbitrary shaped str... | NAME:
impulse_deltav_general_curvedstream
PURPOSE:
calculate the delta velocity to due an encounter with a general spherical potential in the impulse approximation; allows for arbitrary velocity vectors and arbitrary shaped streams
INPUT:
v - velocity of the stream (nstar,3)
x ... |
def process_IN_CREATE(self, raw_event):
"""
If the event affects a directory and the auto_add flag of the
targetted watch is set to True, a new watch is added on this
new directory, with the same attribute values than those of
this watch.
"""
if raw_event.mask & I... | If the event affects a directory and the auto_add flag of the
targetted watch is set to True, a new watch is added on this
new directory, with the same attribute values than those of
this watch. |
def beacon(config):
'''
Emit a dict name "texts" whose value is a list
of texts.
.. code-block:: yaml
beacons:
twilio_txt_msg:
- account_sid: "<account sid>"
- auth_token: "<auth token>"
- twilio_number: "+15555555555"
- interval: 10
... | Emit a dict name "texts" whose value is a list
of texts.
.. code-block:: yaml
beacons:
twilio_txt_msg:
- account_sid: "<account sid>"
- auth_token: "<auth token>"
- twilio_number: "+15555555555"
- interval: 10 |
def DecryptPassword(cipher, key):
""" Decrypts the password using the given key with which the password was encrypted first. """
import base64
import hmac
import sha
from array import array
H = UcsUtils.GetShaHash
cipher = cipher + "\n"
cipher = base64.decodestring(cipher)
n = len(cipher) - 16 - 8
... | Decrypts the password using the given key with which the password was encrypted first. |
def _loadFromArray(self, dtype: HdlType, bitAddr: int) -> int:
"""
Parse HArray type to this transaction template instance
:return: address of it's end
"""
self.itemCnt = evalParam(dtype.size).val
self.children = TransTmpl(
dtype.elmType, 0, parent=self, orig... | Parse HArray type to this transaction template instance
:return: address of it's end |
def _move(self, from_state=None, to_state=None, when=None, mode=None):
"""
Internal helper to move a task from one state to another (e.g. from
QUEUED to DELAYED). The "when" argument indicates the timestamp of the
task in the new state. If no to_state is specified, the task will be
... | Internal helper to move a task from one state to another (e.g. from
QUEUED to DELAYED). The "when" argument indicates the timestamp of the
task in the new state. If no to_state is specified, the task will be
simply removed from the original state.
The "mode" param can be specified to de... |
def _do_cron():
"""Handles the cron request to github to check for new pull requests. If
any are found, they are run *sequentially* until they are all completed.
"""
if not args["cron"]:
return
if ("enabled" in db and not db["enabled"]) or "enabled" not in db:
warn("The CI serve... | Handles the cron request to github to check for new pull requests. If
any are found, they are run *sequentially* until they are all completed. |
def mkvirtualenv():
"""
Create the virtualenv project environment
"""
root = '/'.join([deployment_root(),'env'])
path = '/'.join([root,env.project_fullname])
dirs_created = []
if env.verbosity:
print env.host,'CREATING VIRTUALENV', path
if not exists(root): dirs_created += mkdirs... | Create the virtualenv project environment |
def upgrade_api(request, client, version):
"""Ugrade the nova API to the specified version if possible."""
min_ver, max_ver = api_versions._get_server_version_range(client)
if min_ver <= api_versions.APIVersion(version) <= max_ver:
client = _nova.novaclient(request, version)
return client | Ugrade the nova API to the specified version if possible. |
def query(self, hostname, x509):
"""
Return true if the given :class:`OpenSSL.crypto.X509` object `x509` has
previously been pinned for use with the given `hostname` and
:data:`None` otherwise.
Returning :data:`None` allows this method to be used with
:class:`PinningPKIX... | Return true if the given :class:`OpenSSL.crypto.X509` object `x509` has
previously been pinned for use with the given `hostname` and
:data:`None` otherwise.
Returning :data:`None` allows this method to be used with
:class:`PinningPKIXCertificateVerifier`. |
def get_normalized_path(path):
"""
Normalizes a path, escaping slashes if needed on Windows.
Usage::
>>> get_normalized_path("C:\\Users/johnDoe\\Documents")
u'C:\\Users\\JohnDoe\\Documents'
:param path: Path to normalize.
:type path: unicode
:return: Normalized path.
:rtyp... | Normalizes a path, escaping slashes if needed on Windows.
Usage::
>>> get_normalized_path("C:\\Users/johnDoe\\Documents")
u'C:\\Users\\JohnDoe\\Documents'
:param path: Path to normalize.
:type path: unicode
:return: Normalized path.
:rtype: unicode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.