code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def firmware_download_output_cluster_output_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
output = ET.SubElement(firmware_download, "output")
clus... | Auto Generated Code |
def engine(func):
"""Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is similar to `coroutine`, except it d... | Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is similar to `coroutine`, except it does not
return a `.Fu... |
def to_polar(x, y, theta_units="radians"):
"""
Converts cartesian x, y to polar r, theta.
"""
assert theta_units in [
"radians",
"degrees",
], "kwarg theta_units must specified in radians or degrees"
theta = atan2(y, x)
r = sqrt(x ** 2 + y ** 2)
if theta_units == "degre... | Converts cartesian x, y to polar r, theta. |
def parse_extras(self):
# type: () -> None
"""
Parse extras from *self.line* and set them on the current object
:returns: Nothing
:rtype: None
"""
extras = None
if "@" in self.line or self.is_vcs or self.is_url:
line = "{0}".format(self.line)
... | Parse extras from *self.line* and set them on the current object
:returns: Nothing
:rtype: None |
def registerUpgrader(upgrader, typeName, oldVersion, newVersion):
"""
Register a callable which can perform a schema upgrade between two
particular versions.
@param upgrader: A one-argument callable which will upgrade an object. It
is invoked with an instance of the old version of the object.
... | Register a callable which can perform a schema upgrade between two
particular versions.
@param upgrader: A one-argument callable which will upgrade an object. It
is invoked with an instance of the old version of the object.
@param typeName: The database typename for which this is an upgrader.
@par... |
def save_sampler(sampler):
"""
Dumps a sampler into its hdf5 database.
"""
db = sampler.db
fnode = tables.filenode.newnode(db._h5file, where='/', name='__sampler__')
import pickle
pickle.dump(sampler, fnode) | Dumps a sampler into its hdf5 database. |
def virtualenv(self, virtualenv):
'''
Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv creation
should be skipped.
'''
# If a boole... | Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv creation
should be skipped. |
def initialize(logger_name=LOGGER_NAME,
log_filename=LOG_FILENAME,
app_logging_level=APP_LOGGING_LEVEL,
dep_logging_level=DEP_LOGGING_LEVEL,
format=None,
logger_class=None,
handlers=[],
global_logger=True):
"""
... | Constructs and initializes a `logging.Logger` object.
Returns :class:`logging.Logger` object.
:param logger_name: name of the new logger.
:param log_filename: The log file location :class:`str` or None.
:param app_logging_level: The logging level to use for the application.
:param dep_logging_leve... |
def get_pmap_from_csv(oqparam, fnames):
"""
:param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fnames:
a space-separated list of .csv relative filenames
:returns:
the site mesh and the hazard curves read by the .csv files
"""
if not oqpar... | :param oqparam:
an :class:`openquake.commonlib.oqvalidation.OqParam` instance
:param fnames:
a space-separated list of .csv relative filenames
:returns:
the site mesh and the hazard curves read by the .csv files |
def _format_exception(err, is_failure, stdout=None, stderr=None):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and _is_relevant_tb_level(tb):
tb = tb.tb_next
if is_failure:
# Skip assert*()... | Converts a sys.exc_info()-style tuple of values into a string. |
def validate_anneal_schedule(self, anneal_schedule):
"""Raise an exception if the specified schedule is invalid for the sampler.
Args:
anneal_schedule (list):
An anneal schedule variation is defined by a series of pairs of floating-point
numbers identifying p... | Raise an exception if the specified schedule is invalid for the sampler.
Args:
anneal_schedule (list):
An anneal schedule variation is defined by a series of pairs of floating-point
numbers identifying points in the schedule at which to change slope. The first
... |
def pack_turret(turret, temp_files, base_config_path, path=None):
"""pack a turret into a tar file based on the turret configuration
:param dict turret_config: the turret configuration to pack
:param str tmp_config_file: the path of the temp config file
:param str base_config_path: the base directory o... | pack a turret into a tar file based on the turret configuration
:param dict turret_config: the turret configuration to pack
:param str tmp_config_file: the path of the temp config file
:param str base_config_path: the base directory of the main configuration file |
def barplot(bars, title='', upColor='blue', downColor='red'):
"""
Create candlestick plot for the given bars. The bars can be given as
a DataFrame or as a list of bar objects.
"""
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patc... | Create candlestick plot for the given bars. The bars can be given as
a DataFrame or as a list of bar objects. |
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
_setup(module, ["QtUiTools"])
Qt.__... | Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py |
def get_number_unit(number):
"""get the unit of number"""
n = str(float(number))
mult, submult = n.split('.')
if float(submult) != 0:
unit = '0.' + (len(submult)-1)*'0' + '1'
return float(unit)
else:
return float(1) | get the unit of number |
def get_dynamodb_type(self, val):
"""
Take a scalar Python value and return a string representing
the corresponding Amazon DynamoDB type. If the value passed in is
not a supported type, raise a TypeError.
"""
dynamodb_type = None
if is_num(val):
dynam... | Take a scalar Python value and return a string representing
the corresponding Amazon DynamoDB type. If the value passed in is
not a supported type, raise a TypeError. |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.metric_name is not None:
self._metric_name = self.args.metric_name
if self.args.sample is not None:
self.sample = self.args.sample... | Extracts the specific arguments of this CLI |
def parallel_cp(
pfpicklelist,
outdir,
lcbasedir,
fast_mode=False,
lcfnamelist=None,
cprenorm=False,
lclistpkl=None,
gaia_max_timeout=60.0,
gaia_mirror=None,
nbrradiusarcsec=60.0,
maxnumneighbors=5,
makeneighborlcs=True,
... | This drives the parallel execution of `runcp` for a list of periodfinding
result pickles.
Parameters
----------
pfpicklelist : list of str or list of Nones
This is the list of the filenames of the period-finding result pickles
to process. To make checkplots using the light curves direc... |
def phreg(self, data: ['SASdata', str] = None,
assess: str = None,
bayes: str = None,
by: str = None,
cls: [str, list] = None,
contrast: str = None,
effect: str = None,
estimate: str = None,
freq: str = None,... | Python method to call the PHREG procedure
Documentation link:
https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=statug&docsetTarget=statug_phreg_syntax.htm&locale=en
:param data: SASdata object or string. This parameter is required.
:parm assess: The assess ... |
def __validate(self, value, validate_element):
"""Internal validation function.
Validate an internal value using a function to validate
individual elements.
Args:
value: Value to validate.
validate_element: Function to use to validate individual elements.
R... | Internal validation function.
Validate an internal value using a function to validate
individual elements.
Args:
value: Value to validate.
validate_element: Function to use to validate individual elements.
Raises:
ValidationError if value is not expected ... |
def subdivide(self):
"""Split the curve into a left and right half.
See :meth:`.Curve.subdivide` for more information.
Returns:
Tuple[SubdividedCurve, SubdividedCurve]: The left and right
sub-curves.
"""
left_nodes, right_nodes = _curve_helpers.subdivide... | Split the curve into a left and right half.
See :meth:`.Curve.subdivide` for more information.
Returns:
Tuple[SubdividedCurve, SubdividedCurve]: The left and right
sub-curves. |
def setup_parser(sub_parsers):
"""
Sets up the command line parser for the *software* subprogram and adds it to *sub_parsers*.
"""
parser = sub_parsers.add_parser("software", prog="law software", description="Create or update"
" the law software cache ({}). This is only required for some sandbox... | Sets up the command line parser for the *software* subprogram and adds it to *sub_parsers*. |
def config_loader(app, **kwargs):
"""Custom config loader."""
app.config.from_object(Config)
app.config.update(**kwargs) | Custom config loader. |
def get_simplex_solution_graph(self):
'''
API:
get_simplex_solution_graph(self):
Description:
Assumes a feasible flow solution stored in 'flow' attribute's of
arcs. Returns the graph with arcs that have flow between 0 and
capacity.
Pre:
... | API:
get_simplex_solution_graph(self):
Description:
Assumes a feasible flow solution stored in 'flow' attribute's of
arcs. Returns the graph with arcs that have flow between 0 and
capacity.
Pre:
(1) 'flow' attribute represents a feasible flow s... |
def _build_url(self, host, sport, method, id, format, parameters):
"""
build url from args
"""
path = "/".join(filter(None, (sport, method, id)))
url = "https://" + host + "/" + path + "." + format
if parameters:
paramstring = urllib.parse.urlencode(parame... | build url from args |
def umi_below_threshold(umi_quals, quality_encoding, quality_filter_threshold):
''' return true if any of the umi quals is below the threshold'''
below_threshold = get_below_threshold(
umi_quals, quality_encoding, quality_filter_threshold)
return any(below_threshold) | return true if any of the umi quals is below the threshold |
def _load(self, value: Any):
"""
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
"""
if value in self.empty_values:
# If a default has been set fo... | Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field |
def j0_4(f=1, rho=0.3, z=50):
r"""Hankel transform pair J0_4 ([ChCo82]_).
Parameters
----------
f : float
Frequency (Hz)
rho : float
Resistivity (Ohm.m)
z : float
Vertical distance between source and receiver (m)
"""
gam = np.sqrt(2j*np.pi*mu_0*f/rho)
def ... | r"""Hankel transform pair J0_4 ([ChCo82]_).
Parameters
----------
f : float
Frequency (Hz)
rho : float
Resistivity (Ohm.m)
z : float
Vertical distance between source and receiver (m) |
def addStep(self, callback, *args, **kwargs):
'''
Add rollback step with optional arguments. If a rollback is
triggered, each step is called in LIFO order.
'''
self.steps.append((callback, args, kwargs)) | Add rollback step with optional arguments. If a rollback is
triggered, each step is called in LIFO order. |
def update_from_json(self, data):
"""
Update the attributes of this :class:`Item` using the values obtained
from the dictionary `data`.
The format of `data` should be the same as the format returned by
:meth:`export_as_json`.
"""
self.subscription = data.get("sub... | Update the attributes of this :class:`Item` using the values obtained
from the dictionary `data`.
The format of `data` should be the same as the format returned by
:meth:`export_as_json`. |
def get_record_set_md5(rs_name, rs_type):
"""Accept record_set Name and Type. Return MD5 sum of these values."""
rs_name = rs_name.lower()
rs_type = rs_type.upper()
# Make A and CNAME records hash to same sum to support updates.
rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type
return... | Accept record_set Name and Type. Return MD5 sum of these values. |
def guess(self, *args):
"""
guess() allows a guess to be made. Before the guess is made, the method
checks to see if the game has been won, lost, or there are no tries
remaining. It then creates a return object stating the number of bulls
(direct matches), cows (indirect matches)... | guess() allows a guess to be made. Before the guess is made, the method
checks to see if the game has been won, lost, or there are no tries
remaining. It then creates a return object stating the number of bulls
(direct matches), cows (indirect matches), an analysis of the guess (a
list o... |
def perform_work(
self):
"""perform_work
Process handler function for processing messages
found in the ``multiprocessing.Manager.queue``
Build the ``self.log_payload`` from the queued log messages
and POST it to the Splunk endpoint
"""
self.debug_l... | perform_work
Process handler function for processing messages
found in the ``multiprocessing.Manager.queue``
Build the ``self.log_payload`` from the queued log messages
and POST it to the Splunk endpoint |
def check_angle_solution(ang,n_vec,toy_aa,timeseries):
""" Plots the toy angle solution against the toy angles ---
Takes true angles and frequencies ang,
the Fourier vectors n_vec,
the toy action-angles toy_aa
and the timeseries """
f,a=plt.subplots(3,1)
for i in range(3):
... | Plots the toy angle solution against the toy angles ---
Takes true angles and frequencies ang,
the Fourier vectors n_vec,
the toy action-angles toy_aa
and the timeseries |
def load_trajectory(name=None,
index=None,
as_new=False,
load_parameters=pypetconstants.LOAD_DATA,
load_derived_parameters=pypetconstants.LOAD_SKELETON,
load_results=pypetconstants.LOAD_SKELETON,
load... | Helper function that creates a novel trajectory and loads it from disk.
For the parameters see :func:`~pypet.trajectory.Trajectory.f_load`.
``new_name`` and ``add_time`` are only used in case ``as_new`` is ``True``.
Accordingly, they determine the new name of trajectory. |
def b58decode(v):
'''Decode a Base58 encoded string'''
if not isinstance(v, str):
v = v.decode('ascii')
origlen = len(v)
v = v.lstrip(alphabet[0])
newlen = len(v)
acc = b58decode_int(v)
result = []
while acc > 0:
acc, mod = divmod(acc, 256)
result.append(mod)
... | Decode a Base58 encoded string |
def is_sharable(self):
"""
Is sharable if marked as and if buttons are sharable (they might
hold sensitive data).
"""
return self.sharable and all(x.is_sharable() for x in self.buttons) | Is sharable if marked as and if buttons are sharable (they might
hold sensitive data). |
def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2):
'''
Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x
'''
xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5)
ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2... | Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x |
def get_info(self):
"""
Return plugin information.
"""
plugin_infos = {}
for pc in self.plugins:
plugin_infos.update(pc.get_info())
return {
self.get_plugin_name() : {
"version" : self.get_version(),
"sub-plugin... | Return plugin information. |
def resize(self, capacity):
""" Re-sizes the `Array` by appending new *array elements* or
removing *array elements* from the end.
:param int capacity: new capacity of the `Array` in number of *array elements*.
"""
count = max(int(capacity), 0) - len(self)
if count == 0:... | Re-sizes the `Array` by appending new *array elements* or
removing *array elements* from the end.
:param int capacity: new capacity of the `Array` in number of *array elements*. |
def InitKeypair(aws_id, aws_secret, ec2, s3, keypair_name, src_region,
dst_regions):
"""
Returns the ssh private key for the given keypair name Cirrus created bucket.
Creates the keypair if it doesn't yet exist and stores private key in S3.
"""
# check if a keypair has been created
metada... | Returns the ssh private key for the given keypair name Cirrus created bucket.
Creates the keypair if it doesn't yet exist and stores private key in S3. |
def NextToken(self):
"""Fetch the next token by trying to match any of the regexes in order."""
# Nothing in the input stream - no token can match.
if not self.buffer:
return
current_state = self.state
for token in self._tokens:
# Does the rule apply to us?
if token.state_regex an... | Fetch the next token by trying to match any of the regexes in order. |
def getAllCols(self, sddsfile=None):
""" get all available column names from sddsfile
:param sddsfile: sdds file name, if not given, rollback to the one that from ``__init__()``
:return: all sdds data column names
:rtype: list
:Example:
>>> dh = DataExtracter('test.out... | get all available column names from sddsfile
:param sddsfile: sdds file name, if not given, rollback to the one that from ``__init__()``
:return: all sdds data column names
:rtype: list
:Example:
>>> dh = DataExtracter('test.out')
>>> print(dh.getAllCols())
['x... |
def scroll(self, x, y):
"""Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scr... | Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Retu... |
def get_full_url(self, url):
# type: (str) -> str
"""Get full url including any additional parameters
Args:
url (str): URL for which to get full url
Returns:
str: Full url including any additional parameters
"""
request = Request('GET', url)
... | Get full url including any additional parameters
Args:
url (str): URL for which to get full url
Returns:
str: Full url including any additional parameters |
def reverse_guard(lst):
""" Reverse guard expression. not
(@a > 5) -> (@a =< 5)
Args:
lst (list): Expression
returns:
list
"""
rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'}
return [rev[l] if l in rev else l for l in lst] | Reverse guard expression. not
(@a > 5) -> (@a =< 5)
Args:
lst (list): Expression
returns:
list |
def get_repos(self):
"""
:calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(
github.Repository.Repositor... | :calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` |
def _atexit_callback(cls):
"""Create Python script copies with updated baselines.
For any baseline that had a miscompare, make a copy of the
source file which contained the baseline and update the
baseline with the new string value.
:returns:
record of every Python ... | Create Python script copies with updated baselines.
For any baseline that had a miscompare, make a copy of the
source file which contained the baseline and update the
baseline with the new string value.
:returns:
record of every Python file update (key=path,
val... |
def addDocs(self, docs):
"""docs is a list of fields that are a dictionary of name:value for a record."""
lst = ['<add>']
for fields in docs:
self.__add(lst, fields)
lst.append('</add>')
xstr = ''.join(lst)
return self.doUpdateXML(xstr) | docs is a list of fields that are a dictionary of name:value for a record. |
def as_artist(self, origin=(0, 0), **kwargs):
"""
Matplotlib patch object for this region (`matplotlib.patches.Circle`)
Parameters
----------
origin : array_like, optional
The ``(x, y)`` pixel position of the origin of the displayed image.
Default is (0, ... | Matplotlib patch object for this region (`matplotlib.patches.Circle`)
Parameters
----------
origin : array_like, optional
The ``(x, y)`` pixel position of the origin of the displayed image.
Default is (0, 0).
kwargs : `dict`
All keywords that a `~matp... |
def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York',
ax=None, **kwargs):
"""
Plots a histogram of transaction times, binning the times into
buckets of a given duration.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of e... | Plots a histogram of transaction times, binning the times into
buckets of a given duration.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full explanation in tears.create_full_tear_sheet.
bin_minutes : float, optio... |
def getPosArgs(self):
""" Return a list, in order, of any parameters marked with "pos=N" in
the .cfgspc file. """
if len(self._posArgs) < 1: return []
# The first item in the tuple is the index, so we now sort by it
self._posArgs.sort()
# Build a return list
r... | Return a list, in order, of any parameters marked with "pos=N" in
the .cfgspc file. |
def iter_leaves(self, is_leaf_fn=None):
""" Returns an iterator over the leaves under this node."""
for n in self.traverse(strategy="preorder", is_leaf_fn=is_leaf_fn):
if not is_leaf_fn:
if n.is_leaf():
yield n
else:
if is_leaf_... | Returns an iterator over the leaves under this node. |
def _segment_lengths(self, relative=False, n=20):
""" Returns a list with the lengths of each segment in the path.
"""
# From nodebox_gl
lengths = []
first = True
for el in self._get_elements():
if first is True:
close_x, close_y = el.x, el.y
... | Returns a list with the lengths of each segment in the path. |
def exe_to_egg(self, dist_filename, egg_tmp):
"""Extract a bdist_wininst to the directories an egg would use"""
# Check for .pth file and set up prefix translations
prefixes = get_exe_prefixes(dist_filename)
to_compile = []
native_libs = []
top_level = {}
def pro... | Extract a bdist_wininst to the directories an egg would use |
def _context_menu_make(self, pos):
""" Reimplemented to add an action for raw copy.
"""
menu = super(FrontendWidget, self)._context_menu_make(pos)
for before_action in menu.actions():
if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
QtGui... | Reimplemented to add an action for raw copy. |
def do_unmute(self, sender, body, args):
"""Unmutes the chatroom for a user"""
if sender.get('MUTED'):
sender['MUTED'] = False
self.broadcast('%s has unmuted this chatroom' % (sender['NICK'],))
for msg in sender.get('QUEUED_MESSAGES', []):
self.send_me... | Unmutes the chatroom for a user |
def handle_publish(self, package, _):
'''
Get something from epull, publish it out epub, and return the package (or None)
'''
try:
self.publisher.publish(package)
return package
# Add an extra fallback in case a forked process leeks through
except ... | Get something from epull, publish it out epub, and return the package (or None) |
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None):
""" Generates random values for sequence-like objects
@struct: the sequence-like structure you want to fill with random
data
@size: #int number of random values to include in each @tree_depth
... | Generates random values for sequence-like objects
@struct: the sequence-like structure you want to fill with random
data
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|(value1, v... |
def pwm_array2pssm_array(arr, background_probs=DEFAULT_BASE_BACKGROUND):
"""Convert pwm array to pssm array
"""
b = background_probs2array(background_probs)
b = b.reshape([1, 4, 1])
return np.log(arr / b).astype(arr.dtype) | Convert pwm array to pssm array |
def material_roughness(ID, D=None, optimism=None):
r'''Searches through either a dict of clean pipe materials or used pipe
materials and conditions and returns the ID of the nearest material.
Search is performed with either the standard library's difflib or with
the fuzzywuzzy module if available.
... | r'''Searches through either a dict of clean pipe materials or used pipe
materials and conditions and returns the ID of the nearest material.
Search is performed with either the standard library's difflib or with
the fuzzywuzzy module if available.
Parameters
----------
ID : str
Search t... |
def get_object(self, name, *argv, **kwargs):
"""
Get url object tuple for url
:param name: url regexp from
:type name: str
:param argv: overrided args
:param kwargs: overrided kwargs
:return: url object
:rtype: django.conf.urls.url
"""
reg... | Get url object tuple for url
:param name: url regexp from
:type name: str
:param argv: overrided args
:param kwargs: overrided kwargs
:return: url object
:rtype: django.conf.urls.url |
def cancel(self, event):
"""AlertManager event handler for incoming events
:param event with incoming AlertManager message
"""
topic = event.data.get('topic', None)
if topic is None:
self.log('No alert topic to cancel', lvl=warn)
return
self._can... | AlertManager event handler for incoming events
:param event with incoming AlertManager message |
def watch(self, flag):
"""True if the MessageHandler is being watched."""
lib.EnvSetDefmessageHandlerWatch(
self._env, int(flag), self._cls, self._idx) | True if the MessageHandler is being watched. |
def serialize(message):
"""
Serialize a message to a udp packet
:type message: Message
:param message: the message to be serialized
:rtype: stream of byte
:return: the message serialized
"""
fmt = "!BBH"
if message.token is None or message.token ... | Serialize a message to a udp packet
:type message: Message
:param message: the message to be serialized
:rtype: stream of byte
:return: the message serialized |
def parse_arguments():
"""Collect command-line arguments. Let the caller run parse_args(), as
sphinx-argparse requires a function that returns an instance of
argparse.ArgumentParser
"""
# Pull a few settings from the environment, should they exist
base_dn = os.environ['PUDL_BASE_DN'] if 'PUDL_B... | Collect command-line arguments. Let the caller run parse_args(), as
sphinx-argparse requires a function that returns an instance of
argparse.ArgumentParser |
def all(cls, otp=False, ccid=False, u2f=False):
"""Returns a set of all USB modes, with optional filtering"""
modes = set([
cls.OTP,
cls.CCID,
cls.OTP_CCID,
cls.U2F,
cls.OTP_U2F,
cls.U2F_CCID,
cls.OTP_U2F_CCID
])... | Returns a set of all USB modes, with optional filtering |
def log_iter(self, maxentries=None, template=None, **kwargs):
"""
Run the repository log command, parse, and yield log tuples
Yields:
tuple: self._tuple
"""
# op = self.sh((
# "hg log %s --template"
# % (maxentries and ('-l%d' % maxentries) or '')... | Run the repository log command, parse, and yield log tuples
Yields:
tuple: self._tuple |
def set(self, request_url, response_json):
"""
Checks if the maximum size of the cache has been reached and in case
discards the least recently used item from 'usage_recency' and 'table';
then adds the response_json to be cached to the 'table' dict using as
a lookup key the reque... | Checks if the maximum size of the cache has been reached and in case
discards the least recently used item from 'usage_recency' and 'table';
then adds the response_json to be cached to the 'table' dict using as
a lookup key the request_url of the request that generated the value;
finally... |
def copy(self):
"""Return a shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv | Return a shallow copy of the instance. |
def list_tables(self, dataset):
"""Returns the list of tables in a given dataset.
:param dataset:
:type dataset: BQDataset
"""
request = self.client.tables().list(projectId=dataset.project_id,
datasetId=dataset.dataset_id,
... | Returns the list of tables in a given dataset.
:param dataset:
:type dataset: BQDataset |
def hash_coloured_escapes(text):
"""Return the ANSI hash colour prefix and suffix for a given text"""
ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230
prefix, suffix = colored('SPLIT', ansi_code=ansi_code).split('SPLIT')
return prefix, suffix | Return the ANSI hash colour prefix and suffix for a given text |
def remove_star(self, component=None, **kwargs):
"""
[NOT IMPLEMENTED]
Shortcut to :meth:`remove_component` but with kind='star'
"""
kwargs.setdefault('kind', 'star')
return self.remove_component(component, **kwargs) | [NOT IMPLEMENTED]
Shortcut to :meth:`remove_component` but with kind='star' |
def set_fan(self, fan):
"""Set the fan config.
:param fan: Value to set the fan
:type fan: int [0-10]
:returns: None
:raises: InvalidInput
"""
if type(fan) != int and fan not in range(0, 11):
raise InvalidInput("Fan value must be int between 0-10")
... | Set the fan config.
:param fan: Value to set the fan
:type fan: int [0-10]
:returns: None
:raises: InvalidInput |
def to_feather(df, path):
"""
Write a DataFrame to the feather-format
Parameters
----------
df : DataFrame
path : string file path, or file-like object
"""
path = _stringify_path(path)
if not isinstance(df, DataFrame):
raise ValueError("feather only support IO with DataFram... | Write a DataFrame to the feather-format
Parameters
----------
df : DataFrame
path : string file path, or file-like object |
def plot_total(self, colorbar=True, cb_orientation='vertical',
cb_label='$|B|$, nT', ax=None, show=True, fname=None,
**kwargs):
"""
Plot the total magnetic intensity.
Usage
-----
x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar,
... | Plot the total magnetic intensity.
Usage
-----
x.plot_total([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientation, cb_label, show, fname, **kwargs])
Parameters
----------
tick_interval : list or tuple, optional, default = [30, 30]
... |
def _bucket_events(self, event_iterable):
"""
Convert an iterable of events into an iterable of lists of events
per bucket.
"""
current_bucket_time = None
current_bucket_events = None
for event in event_iterable:
event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD])
if c... | Convert an iterable of events into an iterable of lists of events
per bucket. |
def _hack_namedtuple(cls):
""" Make class generated by namedtuple picklable """
name = cls.__name__
fields = cls._fields
def __reduce__(self):
return (_restore, (name, fields, tuple(self)))
cls.__reduce__ = __reduce__
cls._is_namedtuple_ = True
return cls | Make class generated by namedtuple picklable |
def boot(app_name) -> Rinzler:
"""
Start Rinzler App
:param app_name: str Application's identifier
:return: dict
"""
app = Rinzler(app_name)
app.log.info("App booted =)")
return app | Start Rinzler App
:param app_name: str Application's identifier
:return: dict |
def _parse_executable_spec(src_dir, json_file_name, parser):
"""
Returns the parsed contents of a json specification.
Raises WorkflowBuilderException (exit code 3) if this cannot be done.
"""
if not os.path.isdir(src_dir):
parser.error("{} is not a directory".format(src_dir))
if not os.... | Returns the parsed contents of a json specification.
Raises WorkflowBuilderException (exit code 3) if this cannot be done. |
def setInputs(self, inputs):
"""
Sets self.input to inputs. Load order is by default random. Use setOrderedInputs() to order inputs.
"""
if not self.verifyArguments(inputs) and not self.patterned:
raise NetworkError('setInputs() requires [[...],[...],...] or [{"layerName": [.... | Sets self.input to inputs. Load order is by default random. Use setOrderedInputs() to order inputs. |
def update_dict(d, u):
""" Recursively updates nested dict d from nested dict u
"""
for key, val in u.items():
if isinstance(val, collections.Mapping):
d[key] = update_dict(d.get(key, {}), val)
else:
d[key] = u[key]
return d | Recursively updates nested dict d from nested dict u |
async def listen(self):
""" Waits to receive a payload from the Lavalink server and processes it. """
while not self._shutdown:
try:
data = json.loads(await self._ws.recv())
except websockets.ConnectionClosed as error:
log.warning('Disconnect... | Waits to receive a payload from the Lavalink server and processes it. |
def ParseFileObject(self, parser_mediator, file_object):
"""Parses a plist file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
Un... | Parses a plist file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
UnableToParseFile: when the file cannot be parsed. |
def setup_alignak_logger(self):
""" Setup alignak logger:
- with the daemon log configuration properties
- configure the global daemon handler (root logger)
- log the daemon Alignak header
- configure the global Alignak monitoring log
This function is called very early ... | Setup alignak logger:
- with the daemon log configuration properties
- configure the global daemon handler (root logger)
- log the daemon Alignak header
- configure the global Alignak monitoring log
This function is called very early on daemon start. The daemon is not yet forke... |
def role_add(user, role):
'''
Add role to user
user : string
username
role : string
role name
CLI Example:
.. code-block:: bash
salt '*' rbac.role_add martine netcfg
salt '*' rbac.role_add martine netcfg,zfssnap
'''
ret = {}
## validate roles
... | Add role to user
user : string
username
role : string
role name
CLI Example:
.. code-block:: bash
salt '*' rbac.role_add martine netcfg
salt '*' rbac.role_add martine netcfg,zfssnap |
def fillna(
self,
value=None,
method=None,
axis=None,
inplace=False,
limit=None,
downcast=None,
**kwargs
):
"""Fill NA/NaN values using the specified method.
Args:
value: Value to use to fill holes. This value ... | Fill NA/NaN values using the specified method.
Args:
value: Value to use to fill holes. This value cannot be a list.
method: Method to use for filling holes in reindexed Series pad.
ffill: propagate last valid observation forward to next valid
bac... |
def rndmask(shp, frc, dtype=None):
r"""Return random mask image with values in :math:`\{0,1\}`.
Parameters
----------
s : tuple
Mask array shape
frc : float
Desired fraction of zero pixels
dtype : data-type or None, optional (default None)
Data type of mask array
Returns
... | r"""Return random mask image with values in :math:`\{0,1\}`.
Parameters
----------
s : tuple
Mask array shape
frc : float
Desired fraction of zero pixels
dtype : data-type or None, optional (default None)
Data type of mask array
Returns
-------
msk : ndarray
Mas... |
def cluster(args):
"""
%prog cluster gffile
Given a gff file of gene structures (multiple transcripts per gene locus),
cluster/consolidate all transcripts based on shared splicing structure.
If `slop` is enabled, clustering/consolidation will collapse any variation
in terminal UTR lengths, kee... | %prog cluster gffile
Given a gff file of gene structures (multiple transcripts per gene locus),
cluster/consolidate all transcripts based on shared splicing structure.
If `slop` is enabled, clustering/consolidation will collapse any variation
in terminal UTR lengths, keeping only the longest as repres... |
def _add_crc(self, frame):
"""Add CRC to modbus frame (for RTU mode)
:param frame: modbus RTU frame
:type frame: str (Python2) or class bytes (Python3)
:returns: modbus RTU frame with CRC
:rtype: str (Python2) or class bytes (Python3)
"""
crc = struct.pack('<H', ... | Add CRC to modbus frame (for RTU mode)
:param frame: modbus RTU frame
:type frame: str (Python2) or class bytes (Python3)
:returns: modbus RTU frame with CRC
:rtype: str (Python2) or class bytes (Python3) |
def parse() -> dict:
"""Parse command line arguments"""
parser = ArgumentParser()
parser.add_argument('-p', '--publish', action='store_true', default=False)
return vars(parser.parse_args()) | Parse command line arguments |
async def fetchrow(self, *args, timeout=None):
"""Execute the statement and return the first row.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: The first row as a :class:`Record` instance.
"""... | Execute the statement and return the first row.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: The first row as a :class:`Record` instance. |
def plot_emg_graphical_statistical(time, signal, max_sample_value, min_sample_value, avg_sample_value,
std_sample_value):
"""
-----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average sample
values registered on... | -----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average sample
values registered on the entire EMG acquisition.
-----------
Description
-----------
Function intended to generate a single Bokeh figure with graphically describing and ide... |
def create_database(self, name, character_set=None, collate=None):
"""
Creates a database with the specified name. If a database with
that name already exists, a BadRequest (400) exception will
be raised.
"""
if character_set is None:
character_set = "utf8"
... | Creates a database with the specified name. If a database with
that name already exists, a BadRequest (400) exception will
be raised. |
def _read(self):
""" check ep for data, add it to queue and sleep for interval """
while self._rxactive:
try:
rv = self._ep_in.read(self._ep_in.wMaxPacketSize)
if self._isFTDI:
status = rv[:2] # FTDI prepends 2 flow control characters,
... | check ep for data, add it to queue and sleep for interval |
def version(**kwargs):
"""
Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True.
"""
retry = kwargs.get("retry")
if retry:
click.echo('Retrying publication of the same version...')
else:
click.ec... | Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True. |
def action_findip(reader, *args):
"""Find Flow Log records involving a specific IP or IPs."""
target_ips = set(args)
for record in reader:
if (record.srcaddr in target_ips) or (record.dstaddr in target_ips):
print(record.to_message()) | Find Flow Log records involving a specific IP or IPs. |
def predict(self, eval_data, num_batch=None, merge_batches=True, reset=True,
always_output_list=False, sparse_row_id_fn=None):
"""Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, wher... | Runs prediction and collects the outputs.
When `merge_batches` is ``True`` (by default), the return value will be a list
``[out1, out2, out3]``, where each element is formed by concatenating the outputs for
all the mini-batches. When `always_output_list` is ``False`` (as by default),
th... |
def _destructively_move(self, dest_doc):
''' Move all data in this doc to the dest_doc, leaving this doc empty.
Args:
dest_doc (Document) :
The Bokeh document to populate with data from this one
Returns:
None
'''
if dest_doc is self:
... | Move all data in this doc to the dest_doc, leaving this doc empty.
Args:
dest_doc (Document) :
The Bokeh document to populate with data from this one
Returns:
None |
def segment_lengths(neurites, neurite_type=NeuriteType.all):
'''Lengths of the segments in a collection of neurites'''
def _seg_len(sec):
'''list of segment lengths of a section'''
return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1)
return map_segments(_seg_len, neurites... | Lengths of the segments in a collection of neurites |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.