code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_mark_css(aes_name, css_value):
"""Generate CSS class for <mark> tag.
Parameters
----------
aes_name: str
The name of the class.
css_value: str
The value for the CSS property defined by aes_name.
Returns
-------
list of str
The CSS codeblocks
"""
... | Generate CSS class for <mark> tag.
Parameters
----------
aes_name: str
The name of the class.
css_value: str
The value for the CSS property defined by aes_name.
Returns
-------
list of str
The CSS codeblocks |
def pack(self, value=None):
"""Pack the struct in a binary representation.
Merge some fields to ensure correct packing.
If no arguments are set for a particular instance, it is interpreted as
abscence of VLAN information, and the pack() method will return an
empty binary string... | Pack the struct in a binary representation.
Merge some fields to ensure correct packing.
If no arguments are set for a particular instance, it is interpreted as
abscence of VLAN information, and the pack() method will return an
empty binary string.
Returns:
bytes: ... |
def qos_map_cos_traffic_class_cos3(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
cos_traffic_class = ET.SubElement(map, "cos-traffic-cl... | Auto Generated Code |
def _deserialize_primitive(data, klass):
"""Deserializes to primitive type.
:param data: data to deserialize.
:param klass: class literal.
:return: int, long, float, str, bool.
:rtype: int | long | float | str | bool
"""
try:
value = klass(data)
except UnicodeEncodeError:
... | Deserializes to primitive type.
:param data: data to deserialize.
:param klass: class literal.
:return: int, long, float, str, bool.
:rtype: int | long | float | str | bool |
def embed(self, name, data=None):
"""Attach an image file and prepare for HTML embedding.
This method should only be used to embed images.
:param name: Path to the image to embed if data is None, or the name
of the file if the ``data`` argument is given
:param data: Contents of the image to embed, or No... | Attach an image file and prepare for HTML embedding.
This method should only be used to embed images.
:param name: Path to the image to embed if data is None, or the name
of the file if the ``data`` argument is given
:param data: Contents of the image to embed, or None if the data is to
be read from... |
def deleteByPk(self, pk):
'''
deleteByPk - Delete object associated with given primary key
'''
obj = self.mdl.objects.getOnlyIndexedFields(pk)
if not obj:
return 0
return self.deleteOne(obj) | deleteByPk - Delete object associated with given primary key |
def backward(self, speed=1):
"""
Drive the motor backwards.
:param float speed:
The speed at which the motor should turn. Can be any value between
0 (stopped) and the default 1 (maximum speed).
"""
if isinstance(self.enable_device, DigitalOutputDevice):
... | Drive the motor backwards.
:param float speed:
The speed at which the motor should turn. Can be any value between
0 (stopped) and the default 1 (maximum speed). |
def design_list(self):
"""
List all design documents for the current bucket.
:return: A :class:`~couchbase.result.HttpResult` containing
a dict, with keys being the ID of the design document.
.. note::
This information is derived using the
``pools/d... | List all design documents for the current bucket.
:return: A :class:`~couchbase.result.HttpResult` containing
a dict, with keys being the ID of the design document.
.. note::
This information is derived using the
``pools/default/buckets/<bucket>ddocs`` endpoint, bu... |
def BoolEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a boolean field."""
false_byte = b'\x00'
true_byte = b'\x01'
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value... | Returns an encoder for a boolean field. |
def _read_quoted(ctx: ReaderContext) -> llist.List:
"""Read a quoted form from the input stream."""
start = ctx.reader.advance()
assert start == "'"
next_form = _read_next_consuming_comment(ctx)
return llist.l(_QUOTE, next_form) | Read a quoted form from the input stream. |
def mobile_sign(self, id_code, country, phone_nr, language=None, signing_profile='LT_TM'):
""" This can be used to add a signature to existing data files
WARNING: Must have at least one datafile in the session
"""
if not (self.container and isinstance(self.container, PreviouslyCrea... | This can be used to add a signature to existing data files
WARNING: Must have at least one datafile in the session |
def process_input_graph(func):
"""Decorator, ensuring first argument is a networkx graph object.
If the first arg is a dict {node: succs}, a networkx graph equivalent
to the dict will be send in place of it."""
@wraps(func)
def wrapped_func(*args, **kwargs):
input_graph = args[0]
if ... | Decorator, ensuring first argument is a networkx graph object.
If the first arg is a dict {node: succs}, a networkx graph equivalent
to the dict will be send in place of it. |
def xcorr_plot(template, image, shift=None, cc=None, cc_vec=None, **kwargs):
"""
Plot a template overlying an image aligned by correlation.
:type template: numpy.ndarray
:param template: Short template image
:type image: numpy.ndarray
:param image: Long master image
:type shift: int
:pa... | Plot a template overlying an image aligned by correlation.
:type template: numpy.ndarray
:param template: Short template image
:type image: numpy.ndarray
:param image: Long master image
:type shift: int
:param shift: Shift to apply to template relative to image, in samples
:type cc: float
... |
def _call_and_format(self, req, props=None):
"""
Invokes a single request against a handler using _call() and traps any errors,
formatting them using _err(). If the request is successful it is wrapped in a
JSON-RPC 2.0 compliant dict with keys: 'jsonrpc', 'id', 'result'.
:Para... | Invokes a single request against a handler using _call() and traps any errors,
formatting them using _err(). If the request is successful it is wrapped in a
JSON-RPC 2.0 compliant dict with keys: 'jsonrpc', 'id', 'result'.
:Parameters:
req
A single dict representing a si... |
def create_cmdclass(prerelease_cmd=None, package_data_spec=None,
data_files_spec=None):
"""Create a command class with the given optional prerelease class.
Parameters
----------
prerelease_cmd: (name, Command) tuple, optional
The command to run before releasing.
package_data_spec: d... | Create a command class with the given optional prerelease class.
Parameters
----------
prerelease_cmd: (name, Command) tuple, optional
The command to run before releasing.
package_data_spec: dict, optional
A dictionary whose keys are the dotted package names and
whose values are... |
def parse_unit(item, group, slash):
"""Parse surface and power from unit text."""
surface = item.group(group).replace('.', '')
power = re.findall(r'\-?[0-9%s]+' % r.SUPERSCRIPTS, surface)
if power:
power = [r.UNI_SUPER[i] if i in r.UNI_SUPER else i for i
in power]
power... | Parse surface and power from unit text. |
def _build_kernel(self):
"""Private method to build kernel matrix
Runs public method to build kernel matrix and runs
additional checks to ensure that the result is okay
Returns
-------
Kernel matrix, shape=[n_samples, n_samples]
Raises
------
Ru... | Private method to build kernel matrix
Runs public method to build kernel matrix and runs
additional checks to ensure that the result is okay
Returns
-------
Kernel matrix, shape=[n_samples, n_samples]
Raises
------
RuntimeWarning : if K is not symmetric |
def start(self):
'''
Serving loop
'''
print('Waiting for a client to connect to url http://%s:%d/' % (self.host, self.port))
self.state = RpcServer._STATE_RUN
while self.state == RpcServer._STATE_RUN:
self.server.handle_request()
self.server.server_clo... | Serving loop |
def _compute_rtfilter_map(self):
"""Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a particular neighbor is
... | Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a particular neighbor is
interested in. |
def start(self, test_connection=True):
"""Checks for forking and starts/restarts if desired"""
self._detect_fork()
super(ForkAwareLockerClient, self).start(test_connection) | Checks for forking and starts/restarts if desired |
def set_reverb(self, roomsize=-1.0, damping=-1.0, width=-1.0, level=-1.0):
"""
roomsize Reverb room size value (0.0-1.2)
damping Reverb damping value (0.0-1.0)
width Reverb width value (0.0-100.0)
level Reverb level value (0.0-1.0)
"""
... | roomsize Reverb room size value (0.0-1.2)
damping Reverb damping value (0.0-1.0)
width Reverb width value (0.0-100.0)
level Reverb level value (0.0-1.0) |
def handle_notification(self, data):
"""Handle Callback from a Bluetooth (GATT) request."""
_LOGGER.debug("Received notification from the device..")
if data[0] == PROP_INFO_RETURN and data[1] == 1:
_LOGGER.debug("Got status: %s" % codecs.encode(data, 'hex'))
status = Sta... | Handle Callback from a Bluetooth (GATT) request. |
def environment_schedule_unset(self, name):
"""Schedules unsetting (removing) an environment variable when creating
the next guest process. This affects the
:py:func:`IGuestSession.environment_changes` attribute.
in name of type str
Name of the environment variable to unse... | Schedules unsetting (removing) an environment variable when creating
the next guest process. This affects the
:py:func:`IGuestSession.environment_changes` attribute.
in name of type str
Name of the environment variable to unset. This cannot be empty
nor can it contain... |
def find(cls, name):
'''Find the exception class by name'''
if not cls.mapping: # pragma: no branch
for _, obj in inspect.getmembers(exceptions):
if inspect.isclass(obj):
if issubclass(obj, exceptions.NSQException): # pragma: no branch
... | Find the exception class by name |
def p_expr_GT_expr(p):
""" expr : expr GT expr
"""
p[0] = make_binary(p.lineno(2), 'GT', p[1], p[3], lambda x, y: x > y) | expr : expr GT expr |
def Increment(self, delta, fields=None):
"""Increments counter value by a given delta."""
if delta < 0:
raise ValueError(
"Counter increment should not be < 0 (received: %d)" % delta)
self._metric_values[_FieldsToKey(fields)] = self.Get(fields=fields) + delta | Increments counter value by a given delta. |
def path_in_cache(self, filename, metahash):
"""Generates the path to a file in the mh cache.
The generated path does not imply the file's existence!
Args:
filename: Filename relative to buildroot
rule: A targets.SomeBuildRule object
metahash: hash object
... | Generates the path to a file in the mh cache.
The generated path does not imply the file's existence!
Args:
filename: Filename relative to buildroot
rule: A targets.SomeBuildRule object
metahash: hash object |
def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
"""
if len(node.children) > n:
return node.children[n] | Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code. |
def escape(msg):
"""Takes a raw IRC message and returns a girc-escaped message."""
msg = msg.replace(escape_character, 'girc-escaped-character')
for escape_key, irc_char in format_dict.items():
msg = msg.replace(irc_char, escape_character + escape_key)
# convert colour codes
new_msg = ''
... | Takes a raw IRC message and returns a girc-escaped message. |
def get_encoding_name(self, encoding):
"""Given an encoding provided by the user, will return a
canonical encoding name; and also validate that the encoding
is supported.
TODO: Support encoding aliases: pc437 instead of cp437.
"""
encoding = CodePages.get_encoding_name(e... | Given an encoding provided by the user, will return a
canonical encoding name; and also validate that the encoding
is supported.
TODO: Support encoding aliases: pc437 instead of cp437. |
def _retrieve_config_xml(config_xml, saltenv):
'''
Helper to cache the config XML and raise a CommandExecutionError if we fail
to do so. If we successfully cache the file, return the cached path.
'''
ret = __salt__['cp.cache_file'](config_xml, saltenv)
if not ret:
raise CommandExecution... | Helper to cache the config XML and raise a CommandExecutionError if we fail
to do so. If we successfully cache the file, return the cached path. |
def _fill_get_item_cache(self, catalog, key):
"""
get from redis, cache locally then return
:param catalog: catalog name
:param key:
:return:
"""
lang = self._get_lang()
keylist = self.get_all(catalog)
self.ITEM_CACHE[lang][catalog] = dict([(i['va... | get from redis, cache locally then return
:param catalog: catalog name
:param key:
:return: |
def merge_dicts(d1, d2, _path=None):
"""
Merge dictionary d2 into d1, overriding entries in d1 with values from d2.
d1 is mutated.
_path is for internal, recursive use.
"""
if _path is None:
_path = ()
if isinstance(d1, dict) and isinstance(d2, dict):
for k, v in d2.items()... | Merge dictionary d2 into d1, overriding entries in d1 with values from d2.
d1 is mutated.
_path is for internal, recursive use. |
def startswith(haystack, prefix):
"""
py3 comp startswith
:param haystack:
:param prefix:
:return:
"""
if haystack is None:
return None
if sys.version_info[0] < 3:
return haystack.startswith(prefix)
return to_bytes(haystack).startswith(to_bytes(prefix)) | py3 comp startswith
:param haystack:
:param prefix:
:return: |
def remove_nans_1D(*args) -> tuple:
"""Remove nans in a set of 1D arrays.
Removes indicies in all arrays if any array is nan at that index.
All input arrays must have the same size.
Parameters
----------
args : 1D arrays
Returns
-------
tuple
Tuple of 1D arrays in same ord... | Remove nans in a set of 1D arrays.
Removes indicies in all arrays if any array is nan at that index.
All input arrays must have the same size.
Parameters
----------
args : 1D arrays
Returns
-------
tuple
Tuple of 1D arrays in same order as given, with nan indicies removed. |
def query_edges_by_pubmed_identifiers(self, pubmed_identifiers: List[str]) -> List[Edge]:
"""Get all edges annotated to the documents identified by the given PubMed identifiers."""
fi = and_(Citation.type == CITATION_TYPE_PUBMED, Citation.reference.in_(pubmed_identifiers))
return self.session.qu... | Get all edges annotated to the documents identified by the given PubMed identifiers. |
def ks_synth(freq):
"""
Synthesize the given frequency into a Stream by using a model based on
Karplus-Strong.
"""
ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) +
lz.white_noise() + lz.Stream(-1, 1)) / 5
return lz.karplus_strong(freq, memory=ks_mem) | Synthesize the given frequency into a Stream by using a model based on
Karplus-Strong. |
def get_author_tags(index_page):
"""
Parse `authors` from HTML ``<meta>`` and dublin core.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects.
"""
dom = dhtmlparser.parseString(index_page)
authors = ... | Parse `authors` from HTML ``<meta>`` and dublin core.
Args:
index_page (str): HTML content of the page you wisht to analyze.
Returns:
list: List of :class:`.SourceString` objects. |
def transform(self, attrs):
"""Perform all actions on a given attribute dict."""
self.collect(attrs)
self.add_missing_implementations()
self.fill_attrs(attrs) | Perform all actions on a given attribute dict. |
def diff_commonPrefix(self, text1, text2):
"""Determine the common prefix of two strings.
Args:
text1: First string.
text2: Second string.
Returns:
The number of characters common to the start of each string.
"""
# Quick check for common null cases.
if not text1 or not text2 ... | Determine the common prefix of two strings.
Args:
text1: First string.
text2: Second string.
Returns:
The number of characters common to the start of each string. |
def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
args = parser.parse_args()
if args.order < 0 or args.order > 5:
parser.error('The order has to be a number between 0 and 5.')
return args | Provides additional validation of the arguments collected by argparse. |
def alignment_changed(self, settings, key, user_data):
"""If the gconf var window_halignment be changed, this method will
be called and will call the move function in guake.
"""
RectCalculator.set_final_window_rect(self.settings, self.guake.window)
self.guake.set_tab_position()
... | If the gconf var window_halignment be changed, this method will
be called and will call the move function in guake. |
def makeAudibleSong(self):
"""Use mass to render wav soundtrack.
"""
sound0=n.hstack((sy.render(220,d=1.5),
sy.render(220*(2**(7/12)),d=2.5),
sy.render(220*(2**(-5/12)),d=.5),
sy.render(220*(2**(0/12)),d=1.5),
... | Use mass to render wav soundtrack. |
def _AddClearFieldMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def ClearField(self, field_name):
try:
field = message_descriptor.fields_by_name[field_name]
except KeyError:
try:
field = message_descriptor.oneofs_by_name[field_name]
if field in self._one... | Helper for _AddMessageMethods(). |
def login_to_portal(username, password, client, retries=2, delay=0):
"""Log `username` into the MemberSuite Portal.
Returns a PortalUser object if successful, raises
LoginToPortalError if not.
Will retry logging in if a GeneralException occurs, up to `retries`.
Will pause `delay` seconds between r... | Log `username` into the MemberSuite Portal.
Returns a PortalUser object if successful, raises
LoginToPortalError if not.
Will retry logging in if a GeneralException occurs, up to `retries`.
Will pause `delay` seconds between retries. |
def ws_disconnect(message):
"""
Channels connection close.
Deregister the client
"""
language = message.channel_session['knocker']
gr = Group('knocker-{0}'.format(language))
gr.discard(message.reply_channel) | Channels connection close.
Deregister the client |
def wheel(self, package, options=None):
"""Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django... | Creates a wheel of the given package from this virtual environment,
as specified in pip's package syntax or a tuple of ('name', 'ver'),
only if it is not already installed. Some valid examples:
'Django'
'Django==1.5'
('Django', '1.5')
The `options` is a list of strin... |
def get_help(self, is_category, item):
"""Sends documentation on <item> to <callback>.
This can be used for programmatically accessing documentation.
Keyword arguments:
is_category -- <bool>; Set this to <True> if <item> is for
getting documentation on a permissi... | Sends documentation on <item> to <callback>.
This can be used for programmatically accessing documentation.
Keyword arguments:
is_category -- <bool>; Set this to <True> if <item> is for
getting documentation on a permission level and
<False> if <it... |
def ang2pix(nside, theta, phi, nest=False, lonlat=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`."""
lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring') | Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`. |
def registerItem(self, regItem):
""" Adds a ClassRegItem object to the registry.
"""
super(RtiRegistry, self).registerItem(regItem)
for ext in regItem.extensions:
self._registerExtension(ext, regItem) | Adds a ClassRegItem object to the registry. |
def add_media_description(self, media_description):
"""Adds a media_description.
arg: media_description (displayText): the new media_description
raise: InvalidArgument - ``media_description`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArg... | Adds a media_description.
arg: media_description (displayText): the new media_description
raise: InvalidArgument - ``media_description`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``media_description`` is ``null``
*compliance: ... |
def Main():
"""The main program function.
Returns:
bool: True if successful or False if not.
"""
args_parser = argparse.ArgumentParser(
description='Validates an artifact definitions file.')
args_parser.add_argument(
'filename',
nargs='?',
action='store',
metavar='artifacts... | The main program function.
Returns:
bool: True if successful or False if not. |
def _FormatDescription(self, event):
"""Formats the description.
Args:
event (EventObject): event.
Returns:
str: formatted description field.
"""
date_time_string = timelib.Timestamp.CopyToIsoFormat(
event.timestamp, timezone=self._output_mediator.timezone)
timestamp_descri... | Formats the description.
Args:
event (EventObject): event.
Returns:
str: formatted description field. |
def maximum_cut(G, sampler=None, **sampler_args):
"""Returns an approximate maximum cut.
Defines an Ising problem with ground states corresponding to
a maximum cut and uses the sampler to sample from it.
A maximum cut is a subset S of the vertices of G such that
the number of edges between S and t... | Returns an approximate maximum cut.
Defines an Ising problem with ground states corresponding to
a maximum cut and uses the sampler to sample from it.
A maximum cut is a subset S of the vertices of G such that
the number of edges between S and the complementary subset
is as large as possible.
... |
def get_comments_data(self, slug):
"""
Returns a flat list of all comments in XML dump. Formatted as the JSON
output from Wordpress API.
Keys:
('content', 'slug', 'date', 'status', 'author', 'ID', 'parent')
date format: '%Y-%m-%dT%H:%M:%S'
... | Returns a flat list of all comments in XML dump. Formatted as the JSON
output from Wordpress API.
Keys:
('content', 'slug', 'date', 'status', 'author', 'ID', 'parent')
date format: '%Y-%m-%dT%H:%M:%S'
author: {'username': 'Name', 'URL': ''} |
def get_provider(self, name):
"""Allows for lazy instantiation of providers (Jinja2 templating is heavy, so only instantiate it if
necessary)."""
if name not in self.providers:
cls = self.provider_classes[name]
# instantiate the provider
self.providers[name] =... | Allows for lazy instantiation of providers (Jinja2 templating is heavy, so only instantiate it if
necessary). |
def mdwarf_subtype_from_sdsscolor(ri_color, iz_color):
'''This calculates the M-dwarf subtype given SDSS `r-i` and `i-z` colors.
Parameters
----------
ri_color : float
The SDSS `r-i` color of the object.
iz_color : float
The SDSS `i-z` color of the object.
Returns
-------... | This calculates the M-dwarf subtype given SDSS `r-i` and `i-z` colors.
Parameters
----------
ri_color : float
The SDSS `r-i` color of the object.
iz_color : float
The SDSS `i-z` color of the object.
Returns
-------
(subtype, index1, index2) : tuple
`subtype`: if ... |
def _has_branch(branch):
"""Return True if the target branch exists."""
ret = temple.utils.shell('git rev-parse --verify {}'.format(branch),
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
check=False)
return ret.re... | Return True if the target branch exists. |
def start_log_child(self):
'''Start the logging child process.'''
self.stop_log_child()
gconfig = yakonfig.get_global_config()
read_end, write_end = os.pipe()
pid = os.fork()
if pid == 0:
# We are the child
self.clear_signal_handlers()
... | Start the logging child process. |
def get(self):
'''This handles GET requests to the index page.
TODO: provide the correct baseurl from the checkplotserver options dict,
so the frontend JS can just read that off immediately.
'''
# generate the project's list of checkplots
project_checkplots = self.curr... | This handles GET requests to the index page.
TODO: provide the correct baseurl from the checkplotserver options dict,
so the frontend JS can just read that off immediately. |
def _parse_spectral_data(
self,
content,
TNSId):
"""*parse spectra data from a row in the tns results content*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page
- ``TNSId`` -- the tns id of the transient
**Re... | *parse spectra data from a row in the tns results content*
**Key Arguments:**
- ``content`` -- a table row from the TNS results page
- ``TNSId`` -- the tns id of the transient
**Return:**
- ``specData`` -- a list of dictionaries of the spectral data
- ... |
def _replace(variables, match):
"""
Return the appropriate replacement for `match` using the passed variables
"""
expression = match.group(1)
# Look-up chars and functions for the specified operator
(prefix_char, separator_char, split_fn, escape_fn,
format_fn) = operator_map.get(expression... | Return the appropriate replacement for `match` using the passed variables |
def download(path, source_url):
"""
Download a file to a given path from a given URL, if it does not exist.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
source_url: str
The URL from which to download the file
Returns
-------... | Download a file to a given path from a given URL, if it does not exist.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
source_url: str
The URL from which to download the file
Returns
-------
str
The path of the file |
def set_zone_order(self, zone_ids):
""" reorder zones per the passed in list
:param zone_ids:
:return:
"""
reordered_zones = []
current_zone_ids = [z['id'] for z in self.my_osid_object_form._my_map['zones']]
if set(zone_ids) != set(current_zone_ids):
r... | reorder zones per the passed in list
:param zone_ids:
:return: |
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to t... |
def _set_trunk_vlans(self, v, load=False):
"""
Setter method for trunk_vlans, mapped from YANG variable /interfaces/interface/aggregation/switched_vlan/state/trunk_vlans (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_trunk_vlans is considered as a private
... | Setter method for trunk_vlans, mapped from YANG variable /interfaces/interface/aggregation/switched_vlan/state/trunk_vlans (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_trunk_vlans is considered as a private
method. Backends looking to populate this variable should... |
def unset_env(self, key):
"""Removes an environment variable using the prepended app_name convention with `key`."""
os.environ.pop(make_env_key(self.appname, key), None)
self._registered_env_keys.discard(key)
self._clear_memoization() | Removes an environment variable using the prepended app_name convention with `key`. |
def backward(A, pobs, T=None, beta_out=None, dtype=np.float32):
"""Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probab... | Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hidden state i
beta_out : nda... |
def finalize(self) -> None:
''' split statement and task by last directive '''
self.wrap_script()
if not self.statements:
self.task = ''
return
# handle tasks
input_directive = [
idx for idx, statement in enumerate(self.statements)
... | split statement and task by last directive |
def _parseStylesheet(self, src):
"""stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
"""
# FIXME: BYTES to STR
if type(src) == six.binary_type:
... | stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
; |
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
"""Returns the times when this search is scheduled to run.
By default this method returns the times in the next hour. For different
time ranges, set *earliest_time* and *latest_time*. For example,
for all times in the la... | Returns the times when this search is scheduled to run.
By default this method returns the times in the next hour. For different
time ranges, set *earliest_time* and *latest_time*. For example,
for all times in the last day use "earliest_time=-1d" and
"latest_time=now".
:param ... |
def isbinary(*args):
"""Checks if value can be part of binary/bitwise operations."""
return all(map(lambda c: isnumber(c) or isbool(c), args)) | Checks if value can be part of binary/bitwise operations. |
def from_legacy_urlsafe(cls, urlsafe):
"""Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). This assumes that ``urlsafe`` was created... | Convert urlsafe string to :class:`~google.cloud.datastore.key.Key`.
This is intended to work with the "legacy" representation of a
datastore "Key" used within Google App Engine (a so-called
"Reference"). This assumes that ``urlsafe`` was created within an App
Engine app via something li... |
def schedule(cron, name, params):
'''
Schedule the job <name> to run periodically given the <cron> expression.
Jobs args and kwargs are given as parameters without dashes.
Ex:
udata job schedule "* * 0 * *" my-job arg1 arg2 key1=value key2=value
'''
if name not in celery.tasks:
... | Schedule the job <name> to run periodically given the <cron> expression.
Jobs args and kwargs are given as parameters without dashes.
Ex:
udata job schedule "* * 0 * *" my-job arg1 arg2 key1=value key2=value |
def subdomain_check_pending(self, subrec, atlasdb_path, cur=None):
"""
Determine whether or not a subdomain record's domain is missing zone files
(besides the ones we expect) that could invalidate its history.
"""
_, _, domain = is_address_subdomain(subrec.get_fqn())
sql ... | Determine whether or not a subdomain record's domain is missing zone files
(besides the ones we expect) that could invalidate its history. |
def staticfy(html_file, args=argparse.ArgumentParser()):
"""
Staticfy method.
Loop through each line of the file and replaces the old links
"""
# unpack arguments
static_endpoint = args.static_endpoint or 'static'
framework = args.framework or os.getenv('STATICFY_FRAMEWORK', 'flask')
ad... | Staticfy method.
Loop through each line of the file and replaces the old links |
def strel_disk(radius):
"""Create a disk structuring element for morphological operations
radius - radius of the disk
"""
iradius = int(radius)
x,y = np.mgrid[-iradius:iradius+1,-iradius:iradius+1]
radius2 = radius * radius
strel = np.zeros(x.shape)
strel[x*x+y*y <= radius2] =... | Create a disk structuring element for morphological operations
radius - radius of the disk |
def normalize_name(self, header_name):
""" Return header name as it is recommended (required) by corresponding http protocol. For
protocol switching use :meth:`.WHTTPHeaders.switch_name_style` method.
All current available protocols (0.9-2) compare header names in a case-insensitive fashion. However,
previous ... | Return header name as it is recommended (required) by corresponding http protocol. For
protocol switching use :meth:`.WHTTPHeaders.switch_name_style` method.
All current available protocols (0.9-2) compare header names in a case-insensitive fashion. However,
previous protocol versions (0.9-1.1) recommends to use... |
def delete_user(self, username):
"""Deletes a JIRA User.
:param username: Username to delete
:type username: str
:return: Success of user deletion
:rtype: bool
"""
url = self._options['server'] + '/rest/api/latest/user/?username=%s' % username
r = sel... | Deletes a JIRA User.
:param username: Username to delete
:type username: str
:return: Success of user deletion
:rtype: bool |
def sub_retab(match):
r"""Remove all tabs and convert them into spaces.
PARAMETERS:
match -- regex match; uses re_retab pattern: \1 is text before tab,
\2 is a consecutive string of tabs.
A simple substitution of 4 spaces would result in the following:
to\tlive # original
... | r"""Remove all tabs and convert them into spaces.
PARAMETERS:
match -- regex match; uses re_retab pattern: \1 is text before tab,
\2 is a consecutive string of tabs.
A simple substitution of 4 spaces would result in the following:
to\tlive # original
to live # simple s... |
def merge_up(self, target_branch=None, feature_branch=None, delete=True, create=True):
"""
Merge a change into one or more release branches and the default branch.
:param target_branch: The name of the release branch where merging of
the feature branch starts (a st... | Merge a change into one or more release branches and the default branch.
:param target_branch: The name of the release branch where merging of
the feature branch starts (a string or
:data:`None`, defaults to
:attr:`curren... |
def get_genres(self):
"""
Grab genre URLs from iTunes Podcast preview
"""
page = r.get(ITUNES_GENRES_URL)
tree = html.fromstring(page.content)
elements = tree.xpath("//a[@class='top-level-genre']")
return [e.attrib['href'] for e in elements] | Grab genre URLs from iTunes Podcast preview |
def _filter_list_to_conjunction_expression(filter_list):
"""Convert a list of filters to an Expression that is the conjunction of all of them."""
if not isinstance(filter_list, list):
raise AssertionError(u'Expected `list`, Received: {}.'.format(filter_list))
if any((not isinstance(filter_block, Fil... | Convert a list of filters to an Expression that is the conjunction of all of them. |
def title(self):
"""
The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME
"""
name = c.namemap_lookup(self.id)
if name is None:
name = self._title + " " + client.get_semester_... | The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME |
def setup_matchedfltr_workflow(workflow, science_segs, datafind_outs,
tmplt_banks, output_dir=None,
injection_file=None, tags=None):
'''
This function aims to be the gateway for setting up a set of matched-filter
jobs in a workflow. This function... | This function aims to be the gateway for setting up a set of matched-filter
jobs in a workflow. This function is intended to support multiple
different ways/codes that could be used for doing this. For now the only
supported sub-module is one that runs the matched-filtering by setting up
a serious of ma... |
def runSearchReferenceSets(self, request):
"""
Runs the specified SearchReferenceSetsRequest.
"""
return self.runSearchRequest(
request, protocol.SearchReferenceSetsRequest,
protocol.SearchReferenceSetsResponse,
self.referenceSetsGenerator) | Runs the specified SearchReferenceSetsRequest. |
def start_time(self):
"""Start timestamp of the dataset"""
dt = self.nc['time'].dt
return datetime(year=dt.year, month=dt.month, day=dt.day,
hour=dt.hour, minute=dt.minute,
second=dt.second, microsecond=dt.microsecond) | Start timestamp of the dataset |
def get_lang_dict(self):
"""gets supported langs as an dictionary"""
r = self.yandex_translate_request("getLangs")
self.handle_errors(r)
return r.json()["langs"] | gets supported langs as an dictionary |
def add_or_update(self, app_id):
'''
Add or update the category.
'''
logger.info('Collect info: user-{0}, uid-{1}'.format(self.userinfo.uid, app_id))
MCollect.add_or_update(self.userinfo.uid, app_id)
out_dic = {'success': True}
return json.dump(out_dic, self) | Add or update the category. |
def wait_until_not_moving(self, timeout=None):
"""
Blocks until ``running`` is not in ``self.state`` or ``stalled`` is in
``self.state``. The condition is checked when there is an I/O event
related to the ``state`` attribute. Exits early when ``timeout``
(in milliseconds) is re... | Blocks until ``running`` is not in ``self.state`` or ``stalled`` is in
``self.state``. The condition is checked when there is an I/O event
related to the ``state`` attribute. Exits early when ``timeout``
(in milliseconds) is reached.
Returns ``True`` if the condition is met, and ``Fal... |
def execute_cmdline_scenarios(scenario_name, args, command_args):
"""
Execute scenario sequences based on parsed command-line arguments.
This is useful for subcommands that run scenario sequences, which
excludes subcommands such as ``list``, ``login``, and ``matrix``.
``args`` and ``command_args``... | Execute scenario sequences based on parsed command-line arguments.
This is useful for subcommands that run scenario sequences, which
excludes subcommands such as ``list``, ``login``, and ``matrix``.
``args`` and ``command_args`` are combined using :func:`get_configs`
to generate the scenario(s) config... |
def setup(self, phase=None, quantity='', conductance='', r_tolerance=None,
max_iter=None, relaxation_source=None,
relaxation_quantity=None, **kwargs):
r"""
This method takes several arguments that are essential to running the
algorithm and adds them to the settings
... | r"""
This method takes several arguments that are essential to running the
algorithm and adds them to the settings
Parameters
----------
phase : OpenPNM Phase object
The phase on which the algorithm is to be run. If no value is
given, the existing value i... |
def learn(self, state_arr, limit=1000):
'''
Learning and searching the optimal solution.
Args:
state_arr: `np.ndarray` of initial state.
limit: The maximum number of iterative updates based on value iteration algorithms.
'''
while se... | Learning and searching the optimal solution.
Args:
state_arr: `np.ndarray` of initial state.
limit: The maximum number of iterative updates based on value iteration algorithms. |
def jsonarrappend(self, name, path=Path.rootPath(), *args):
"""
Appends the objects ``args`` to the array under the ``path` in key
``name``
"""
pieces = [name, str_path(path)]
for o in args:
pieces.append(self._encode(o))
return self.execute_command('J... | Appends the objects ``args`` to the array under the ``path` in key
``name`` |
def _LeaseMessageHandlerRequests(self, lease_time, limit, cursor=None):
"""Leases a number of message handler requests up to the indicated limit."""
now = rdfvalue.RDFDatetime.Now()
now_str = mysql_utils.RDFDatetimeToTimestamp(now)
expiry = now + lease_time
expiry_str = mysql_utils.RDFDatetimeToTi... | Leases a number of message handler requests up to the indicated limit. |
def setDetailedText( self, text ):
"""
Sets the details text for this message box to the inputed text. \
Overloading the default method to support HTML details.
:param text | <str>
"""
super(XMessageBox, self).setDetailedText(text)
if ( tex... | Sets the details text for this message box to the inputed text. \
Overloading the default method to support HTML details.
:param text | <str> |
def to_pretty_midi(self, constant_tempo=None, constant_velocity=100):
"""
Convert to a :class:`pretty_midi.PrettyMIDI` instance.
Notes
-----
- Only constant tempo is supported by now.
- The velocities of the converted pianorolls are clipped to [0, 127],
i.e. va... | Convert to a :class:`pretty_midi.PrettyMIDI` instance.
Notes
-----
- Only constant tempo is supported by now.
- The velocities of the converted pianorolls are clipped to [0, 127],
i.e. values below 0 and values beyond 127 are replaced by 127 and 0,
respectively.
... |
def _processor(self):
"""Application processor to setup session for every request"""
self.store.cleanup(self._config.timeout)
self._load() | Application processor to setup session for every request |
def handler(self, environ, start_response):
"""XMLRPC service for windmill browser core to communicate with"""
if environ['REQUEST_METHOD'] == 'POST':
return self.handle_POST(environ, start_response)
else:
start_response("400 Bad request", [('Content-Type', 'text/plain')... | XMLRPC service for windmill browser core to communicate with |
async def verify_worker_impls(chain):
"""Verify the task type (e.g. decision, build) of each link in the chain.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure
"""
valid_worker_impls = get_valid_worker_impls()
for obj in chain.get_all_link... | Verify the task type (e.g. decision, build) of each link in the chain.
Args:
chain (ChainOfTrust): the chain we're operating on
Raises:
CoTError: on failure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.