code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def message(self, value):
"""The message property.
Args:
value (string). the property value.
"""
if value == self._defaults['message'] and 'message' in self._values:
del self._values['message']
else:
self._values['message'] = value | The message property.
Args:
value (string). the property value. |
def parse_midi_event(self, fp):
"""Parse a MIDI event.
Return a dictionary and the number of bytes read.
"""
chunk_size = 0
try:
ec = self.bytes_to_int(fp.read(1))
chunk_size += 1
self.bytes_read += 1
except:
raise IOError(... | Parse a MIDI event.
Return a dictionary and the number of bytes read. |
def gzip_open_text(path, encoding=None):
"""Opens a plain-text file that may be gzip'ed.
Parameters
----------
path : str
The file.
encoding : str, optional
The encoding to use.
Returns
-------
file-like
A file-like object.
Notes
-----
Generally, re... | Opens a plain-text file that may be gzip'ed.
Parameters
----------
path : str
The file.
encoding : str, optional
The encoding to use.
Returns
-------
file-like
A file-like object.
Notes
-----
Generally, reading gzip'ed files with gzip.open is very slow,... |
def _set_snps(self, snps, build=37):
""" Set `_snps` and `_build` properties of this ``Individual``.
Notes
-----
Intended to be used internally to `lineage`.
Parameters
----------
snps : pandas.DataFrame
individual's genetic data normalized for use w... | Set `_snps` and `_build` properties of this ``Individual``.
Notes
-----
Intended to be used internally to `lineage`.
Parameters
----------
snps : pandas.DataFrame
individual's genetic data normalized for use with `lineage`
build : int
bui... |
def _compare_or_regex_search(a, b, regex=False):
"""
Compare two array_like inputs of the same shape or two scalar values
Calls operator.eq or re.search, depending on regex argument. If regex is
True, perform an element-wise regex matching.
Parameters
----------
a : array_like or scalar
... | Compare two array_like inputs of the same shape or two scalar values
Calls operator.eq or re.search, depending on regex argument. If regex is
True, perform an element-wise regex matching.
Parameters
----------
a : array_like or scalar
b : array_like or scalar
regex : bool, default False
... |
def video_pixel_noise_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for video."""
input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25)
inputs = x
if model_hparams.mode == tf.estimator.ModeKeys.TRAIN:
background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3])
i... | Bottom transformation for video. |
def get_grade_systems(self):
"""Gets the grade system list resulting from the search.
return: (osid.grading.GradeSystemList) - the grade system list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.*
"""
if self.ret... | Gets the grade system list resulting from the search.
return: (osid.grading.GradeSystemList) - the grade system list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.* |
def precision(y, y_pred):
"""Precision score
precision = true_positives / (true_positives + false_positives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
preci... | Precision score
precision = true_positives / (true_positives + false_positives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
precision : float |
def create_user(self, Name, EmailAddress, **kwargs):
""" Create user (undocumented API feature).
:param Name: User name (login for privileged, required)
:param EmailAddress: Email address (required)
:param kwargs: Optional fields to set (see edit_user)
:returns: ID of new user o... | Create user (undocumented API feature).
:param Name: User name (login for privileged, required)
:param EmailAddress: Email address (required)
:param kwargs: Optional fields to set (see edit_user)
:returns: ID of new user or False when create fails
:raises BadRequest: When user a... |
def url_to_string(url):
"""
Return the contents of a web site url as a string.
"""
try:
page = urllib2.urlopen(url)
except (urllib2.HTTPError, urllib2.URLError) as err:
ui.error(c.MESSAGES["url_unreachable"], err)
sys.exit(1)
return page | Return the contents of a web site url as a string. |
def tableExists(self, login, tableName):
"""
Parameters:
- login
- tableName
"""
self.send_tableExists(login, tableName)
return self.recv_tableExists() | Parameters:
- login
- tableName |
def subproc_call(cmd, timeout=None):
"""
Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1.
"""
try:
output = s... | Execute a command with timeout, and return STDOUT and STDERR
Args:
cmd(str): the command to execute.
timeout(float): timeout in seconds.
Returns:
output(bytes), retcode(int). If timeout, retcode is -1. |
def div_img(img1, div2):
""" Pixelwise division or divide by a number """
if is_img(div2):
return img1.get_data()/div2.get_data()
elif isinstance(div2, (float, int)):
return img1.get_data()/div2
else:
raise NotImplementedError('Cannot divide {}({}) by '
... | Pixelwise division or divide by a number |
def combination_step(self):
"""Build next update by a smart combination of previous updates.
(standard FISTA :cite:`beck-2009-fast`).
"""
# Update t step
tprv = self.t
self.t = 0.5 * float(1. + np.sqrt(1. + 4. * tprv**2))
# Update Y
if not self.opt['Fast... | Build next update by a smart combination of previous updates.
(standard FISTA :cite:`beck-2009-fast`). |
def uniq(seq):
""" Return a copy of seq without duplicates. """
seen = set()
return [x for x in seq if str(x) not in seen and not seen.add(str(x))] | Return a copy of seq without duplicates. |
def visit(self, func):
"""Run ``func`` on each object's path.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr... | Run ``func`` on each object's path.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
... |
def genchanges(self):
"""Generate a .changes file for this package."""
chparams = self.params.copy()
debpath = os.path.join(self.buildroot, self.rule.output_files[0])
chparams.update({
'fullversion': '{epoch}:{version}-{release}'.format(**chparams),
'metahash': se... | Generate a .changes file for this package. |
def hook(self, function, dependencies=None):
"""Tries to load a hook
Args:
function (func): Function that will be called when the event is called
Kwargs:
dependencies (str): String or Iterable with modules whose hooks should be called before this one
Raises:
... | Tries to load a hook
Args:
function (func): Function that will be called when the event is called
Kwargs:
dependencies (str): String or Iterable with modules whose hooks should be called before this one
Raises:
:class:TypeError
Note that the depend... |
def spin_in_system(incl, long_an):
"""
Spin in the plane of sky of a star given its inclination and "long_an"
incl - inclination of the star in the plane of sky
long_an - longitude of ascending node (equator) of the star in the plane of sky
Return:
spin - in plane of sky
"""
... | Spin in the plane of sky of a star given its inclination and "long_an"
incl - inclination of the star in the plane of sky
long_an - longitude of ascending node (equator) of the star in the plane of sky
Return:
spin - in plane of sky |
def rpm_versioned_name(cls, name, version, default_number=False):
"""Properly versions the name.
For example:
rpm_versioned_name('python-foo', '26') will return python26-foo
rpm_versioned_name('pyfoo, '3') will return python3-pyfoo
If version is same as settings.DEFAULT_PYTHON_V... | Properly versions the name.
For example:
rpm_versioned_name('python-foo', '26') will return python26-foo
rpm_versioned_name('pyfoo, '3') will return python3-pyfoo
If version is same as settings.DEFAULT_PYTHON_VERSION, no change
is done.
Args:
name: name to v... |
def _convert_localized_value(value: LocalizedValue) -> LocalizedIntegerValue:
"""Converts from :see:LocalizedValue to :see:LocalizedIntegerValue."""
integer_values = {}
for lang_code, _ in settings.LANGUAGES:
local_value = value.get(lang_code, None)
if local_value is Non... | Converts from :see:LocalizedValue to :see:LocalizedIntegerValue. |
def set_password(cls, instance, raw_password):
"""
sets new password on a user using password manager
:param instance:
:param raw_password:
:return:
"""
# support API for both passlib 1.x and 2.x
hash_callable = getattr(
instance.passwordmanag... | sets new password on a user using password manager
:param instance:
:param raw_password:
:return: |
def visit_ifexp(self, node, parent):
"""visit a IfExp node by returning a fresh instance of it"""
newnode = nodes.IfExp(node.lineno, node.col_offset, parent)
newnode.postinit(
self.visit(node.test, newnode),
self.visit(node.body, newnode),
self.visit(node.orel... | visit a IfExp node by returning a fresh instance of it |
def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'tes... | Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'test'))
>>> cluster == ['base', 'local', 'test... |
def validate_href(image_href):
"""Validate HTTP image reference.
:param image_href: Image reference.
:raises: exception.ImageRefValidationFailed if HEAD request failed or
returned response code not equal to 200.
:returns: Response to HEAD request.
"""
try:
... | Validate HTTP image reference.
:param image_href: Image reference.
:raises: exception.ImageRefValidationFailed if HEAD request failed or
returned response code not equal to 200.
:returns: Response to HEAD request. |
async def connect(
cls, url, *, apikey=None, insecure=False):
"""Make an `Origin` by connecting with an apikey.
:return: A tuple of ``profile`` and ``origin``, where the former is an
unsaved `Profile` instance, and the latter is an `Origin` instance
made using the pr... | Make an `Origin` by connecting with an apikey.
:return: A tuple of ``profile`` and ``origin``, where the former is an
unsaved `Profile` instance, and the latter is an `Origin` instance
made using the profile. |
def crop_to_bounding_box(image, offset_height, offset_width, target_height,
target_width, dynamic_shape=False):
"""Crops an image to a specified bounding box.
This op cuts a rectangular part out of `image`. The top-left corner of the
returned image is at `offset_height, offset_width` in ... | Crops an image to a specified bounding box.
This op cuts a rectangular part out of `image`. The top-left corner of the
returned image is at `offset_height, offset_width` in `image`, and its
lower-right corner is at
`offset_height + target_height, offset_width + target_width`.
Args:
image: 3-D tensor wit... |
def format_box(title, ch="*"):
"""
Encloses title in a box. Result is a list
>>> for line in format_box("Today's TODO list"):
... print(line)
*************************
*** Today's TODO list ***
*************************
"""
lt = len(title)
return [(ch * (lt + 8)),... | Encloses title in a box. Result is a list
>>> for line in format_box("Today's TODO list"):
... print(line)
*************************
*** Today's TODO list ***
************************* |
def format_error(module, error):
"""Format the error for the given module."""
logging.error(module)
# Beautify JSON error
print error.message
print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': '))
exit(1) | Format the error for the given module. |
def with_retry(cls, methods):
"""
Wraps the given list of methods in a class with an exponential-back
retry mechanism.
"""
retry_with_backoff = retry(
retry_on_exception=lambda e: isinstance(e, BotoServerError),
wait_exponential_multiplier=1000,
wait_exponential_max=10000
... | Wraps the given list of methods in a class with an exponential-back
retry mechanism. |
def get_value(self, name):
"""Get the value of a variable"""
ns = self._get_current_namespace()
value = ns[name]
try:
self.send_spyder_msg('data', data=value)
except:
# * There is no need to inform users about
# these errors.
# * ... | Get the value of a variable |
def mrc_to_marc(mrc):
"""
Convert MRC data format to MARC XML.
Args:
mrc (str): MRC as string.
Returns:
str: XML with MARC.
"""
# ignore blank lines
lines = [
line
for line in mrc.splitlines()
if line.strip()
]
def split_to_parts(lines):
... | Convert MRC data format to MARC XML.
Args:
mrc (str): MRC as string.
Returns:
str: XML with MARC. |
def wait(self):
"""wait until all jobs finish and return a list of pids
"""
finished_pids = [ ]
while self.running_procs:
finished_pids.extend(self.poll())
return finished_pids | wait until all jobs finish and return a list of pids |
def initialize(self, conf, ctx):
"""Initialization steps:
1. Prepare elasticsearch connection, including details for indexing.
"""
config = get_config()['ElasticsearchIndexBolt']
elasticsearch_class = import_name(config['elasticsearch_class'])
self.es = elasticsearch_cla... | Initialization steps:
1. Prepare elasticsearch connection, including details for indexing. |
def k_weights_int(self):
"""
Returns
-------
ndarray
Geometric k-point weights (number of arms of k-star in BZ).
dtype='intc'
shape=(irreducible_kpoints,)
"""
nk = np.prod(self.k_mesh)
_weights = self.k_weights * nk
wei... | Returns
-------
ndarray
Geometric k-point weights (number of arms of k-star in BZ).
dtype='intc'
shape=(irreducible_kpoints,) |
def update_screen_id(self):
"""
Sends a getMdxSessionStatus to get the screenId and waits for response.
This function is blocking
If connected we should always get a response
(send message will launch app if it is not running).
"""
self.status_update_event.clear()... | Sends a getMdxSessionStatus to get the screenId and waits for response.
This function is blocking
If connected we should always get a response
(send message will launch app if it is not running). |
def list_objects(self):
''' list the entire of objects with their (id, serialized_form, actual_value) '''
for i in self._execute('select * from objects'):
_id, code = i
yield _id, code, self.deserialize(code) | list the entire of objects with their (id, serialized_form, actual_value) |
def _example_short_number(region_code):
"""Gets a valid short number for the specified region.
Arguments:
region_code -- the region for which an example short number is needed.
Returns a valid short number for the specified region. Returns an empty
string when the metadata does not contain such in... | Gets a valid short number for the specified region.
Arguments:
region_code -- the region for which an example short number is needed.
Returns a valid short number for the specified region. Returns an empty
string when the metadata does not contain such information. |
def move_committees(src, dest):
"""
Import stupid yaml files, convert to something useful.
"""
comm, sub_comm = import_committees(src)
save_committees(comm, dest)
save_subcommittees(comm, dest) | Import stupid yaml files, convert to something useful. |
def createTemporaryCredentials(clientId, accessToken, start, expiry, scopes, name=None):
""" Create a set of temporary credentials
Callers should not apply any clock skew; clock drift is accounted for by
auth service.
clientId: the issuing clientId
accessToken: the issuer's accessToken
start: ... | Create a set of temporary credentials
Callers should not apply any clock skew; clock drift is accounted for by
auth service.
clientId: the issuing clientId
accessToken: the issuer's accessToken
start: start time of credentials (datetime.datetime)
expiry: expiration time of credentials, (dateti... |
async def fetch_bikes() -> List[dict]:
"""
Gets the full list of bikes from the bikeregister site.
The data is hidden behind a form post request and so
we need to extract an xsrf and session token with bs4.
todo add pytest tests
:return: All the currently registered bikes.
:raise ApiError:... | Gets the full list of bikes from the bikeregister site.
The data is hidden behind a form post request and so
we need to extract an xsrf and session token with bs4.
todo add pytest tests
:return: All the currently registered bikes.
:raise ApiError: When there was an error connecting to the API. |
def add_dashboard_tag(self, id, tag_value, **kwargs): # noqa: E501
"""Add a tag to a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_da... | Add a tag to a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_dashboard_tag(id, tag_value, async_req=True)
>>> result = thread.get()
... |
def _process_callback(self, statefield):
"""
Exchange the auth code for actual credentials,
then redirect to the originally requested page.
"""
# retrieve session and callback variables
try:
session_csrf_token = session.get('oidc_csrf_token')
stat... | Exchange the auth code for actual credentials,
then redirect to the originally requested page. |
def chipqc(bam_file, sample, out_dir):
"""Attempt code to run ChIPQC bioconductor packate in one sample"""
sample_name = dd.get_sample_name(sample)
logger.warning("ChIPQC is unstable right now, if it breaks, turn off the tool.")
if utils.file_exists(out_dir):
return _get_output(out_dir)
with... | Attempt code to run ChIPQC bioconductor packate in one sample |
def i2c_master_read(self, addr, length, flags=I2C_NO_FLAGS):
"""Make an I2C read access.
The given I2C device is addressed and clock cycles for `length` bytes
are generated. A short read will occur if the device generates an early
NAK.
The transaction is finished with an I2C st... | Make an I2C read access.
The given I2C device is addressed and clock cycles for `length` bytes
are generated. A short read will occur if the device generates an early
NAK.
The transaction is finished with an I2C stop condition unless the
I2C_NO_STOP flag is set. |
def imshow(self, array, *args, **kwargs):
"""Display an image, i.e. data on a 2D regular raster.
If ``array`` is a :class:`~gwpy.types.Array2D` (e.g. a
:class:`~gwpy.spectrogram.Spectrogram`), then the defaults are
_different_ to those in the upstream
:meth:`~matplotlib.axes.Axe... | Display an image, i.e. data on a 2D regular raster.
If ``array`` is a :class:`~gwpy.types.Array2D` (e.g. a
:class:`~gwpy.spectrogram.Spectrogram`), then the defaults are
_different_ to those in the upstream
:meth:`~matplotlib.axes.Axes.imshow` method. Namely, the defaults are
-... |
def sys_path(self):
"""
The system path inside the environment
:return: The :data:`sys.path` from the environment
:rtype: list
"""
from .vendor.vistir.compat import JSONDecodeError
current_executable = vistir.compat.Path(sys.executable).as_posix()
if not... | The system path inside the environment
:return: The :data:`sys.path` from the environment
:rtype: list |
def buildDQMasks(imageObjectList,configObj):
""" Build DQ masks for all input images.
"""
# Insure that input imageObject is a list
if not isinstance(imageObjectList, list):
imageObjectList = [imageObjectList]
for img in imageObjectList:
img.buildMask(configObj['single'], configObj[... | Build DQ masks for all input images. |
def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool:
"""
Return true if the given class node is subclass of
exceptions.Exception.
"""
ancestors = node.ancestors() if hasattr(node, "ancestors") else []
for ancestor in itertools.chain([node], ancestors):
if (
anc... | Return true if the given class node is subclass of
exceptions.Exception. |
def _Kw(rho, T):
"""Equation for the ionization constant of ordinary water
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
pKw : float
Ionization constant in -log10(kw), [-]
Notes
------
Raise :class:`No... | Equation for the ionization constant of ordinary water
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
Returns
-------
pKw : float
Ionization constant in -log10(kw), [-]
Notes
------
Raise :class:`NotImplementedError` if in... |
def import_class(clspath):
"""Given a clspath, returns the class.
Note: This is a really simplistic implementation.
"""
modpath, clsname = split_clspath(clspath)
__import__(modpath)
module = sys.modules[modpath]
return getattr(module, clsname) | Given a clspath, returns the class.
Note: This is a really simplistic implementation. |
def get_next_holiday(self, division=None, date=None):
"""
Returns the next known bank holiday
:param division: see division constants; defaults to common holidays
:param date: search starting from this date; defaults to today
:return: dict
"""
date = date or datet... | Returns the next known bank holiday
:param division: see division constants; defaults to common holidays
:param date: search starting from this date; defaults to today
:return: dict |
def extraSelections(self):
""" In normal mode - QTextEdit.ExtraSelection which highlightes the cursor
"""
if not isinstance(self._mode, Normal):
return []
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(QColor('#ffcc22'))
selection.forma... | In normal mode - QTextEdit.ExtraSelection which highlightes the cursor |
def data_complete(datadir, sitedir, get_container_name):
"""
Return True if the directories and containers we're expecting
are present in datadir, sitedir and containers
"""
if any(not path.isdir(sitedir + x)
for x in ('/files', '/run', '/solr')):
return False
if docker.is_b... | Return True if the directories and containers we're expecting
are present in datadir, sitedir and containers |
def scansion_prepare(self,meter=None,conscious=False):
"""Print out header column for line-scansions for a given meter. """
import prosodic
config=prosodic.config
if not meter:
if not hasattr(self,'_Text__bestparses'): return
x=getattr(self,'_Text__bestparses')
if not x.keys(): return
meter=x.keys(... | Print out header column for line-scansions for a given meter. |
def _get_anchor_data(anchor_data, glyphSet, components, anchor_name):
"""Get data for an anchor from a list of components."""
anchors = []
for component in components:
for anchor in glyphSet[component.baseGlyph].anchors:
if anchor.name == anchor_name:
anchors.append((anc... | Get data for an anchor from a list of components. |
def to_uri(url):
""" Converts a url to an ascii %-encoded form
where:
- scheme is ascii,
- host is punycode,
- and remainder is %-encoded
Not using urlsplit to also decode partially encoded
scheme urls
"""
parts = WbUrl.FIRST_PATH.split(url, 1)
... | Converts a url to an ascii %-encoded form
where:
- scheme is ascii,
- host is punycode,
- and remainder is %-encoded
Not using urlsplit to also decode partially encoded
scheme urls |
def swipe(self, p1, p2=None, direction=None, duration=2.0):
"""
Perform swipe action on target device from point to point given by start point and end point, or by the
direction vector. At least one of the end point or direction must be provided.
The coordinates (x, y) definition for po... | Perform swipe action on target device from point to point given by start point and end point, or by the
direction vector. At least one of the end point or direction must be provided.
The coordinates (x, y) definition for points is the same as for ``click`` event. The components of the
direction... |
def GetEntries(self, cut=None, weighted_cut=None, weighted=False):
"""
Get the number of (weighted) entries in the Tree
Parameters
----------
cut : str or rootpy.tree.cut.Cut, optional (default=None)
Only entries passing this cut will be included in the count
... | Get the number of (weighted) entries in the Tree
Parameters
----------
cut : str or rootpy.tree.cut.Cut, optional (default=None)
Only entries passing this cut will be included in the count
weighted_cut : str or rootpy.tree.cut.Cut, optional (default=None)
Apply ... |
def update_job(job_id):
"""Updates a job."""
data = request.get_json(force=True)
try:
current_app.apscheduler.modify_job(job_id, **data)
job = current_app.apscheduler.get_job(job_id)
return jsonify(job)
except JobLookupError:
return jsonify(dict(error_message='Job %s no... | Updates a job. |
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None:
"Callback function that writes epoch end appropriate data to Tensorboard."
self._write_metrics(iteration=iteration, last_metrics=last_metrics) | Callback function that writes epoch end appropriate data to Tensorboard. |
def _knn(self, i, X, high_dim=True):
"""Performs KNN search based on high/low-dimensional similarity/distance measurement"""
knns = []
for j in range(X.shape[0]):
if j != i:
if high_dim:
distance = self._high_dim_sim(X[i], X[j], idx=i)
... | Performs KNN search based on high/low-dimensional similarity/distance measurement |
def set_debug(self, debug=1):
"""
Set the debug level.
:type debug: int
:param debug: The debug level.
"""
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug | Set the debug level.
:type debug: int
:param debug: The debug level. |
def _configure_node():
"""Exectutes chef-solo to apply roles and recipes to a node"""
print("")
msg = "Cooking..."
if env.parallel:
msg = "[{0}]: {1}".format(env.host_string, msg)
print(msg)
# Backup last report
with settings(hide('stdout', 'warnings', 'running'), warn_only=True):
... | Exectutes chef-solo to apply roles and recipes to a node |
def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0... | Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None |
def value_compare(left, right, ordering=1):
"""
SORT VALUES, NULL IS THE LEAST VALUE
:param left: LHS
:param right: RHS
:param ordering: (-1, 0, 1) TO AFFECT SORT ORDER
:return: The return value is negative if x < y, zero if x == y and strictly positive if x > y.
"""
try:
ltype ... | SORT VALUES, NULL IS THE LEAST VALUE
:param left: LHS
:param right: RHS
:param ordering: (-1, 0, 1) TO AFFECT SORT ORDER
:return: The return value is negative if x < y, zero if x == y and strictly positive if x > y. |
async def download_media(self, *args, **kwargs):
"""
Downloads the media contained in the message, if any. Shorthand
for `telethon.client.downloads.DownloadMethods.download_media`
with the ``message`` already set.
"""
return await self._client.download_media(self, *args, ... | Downloads the media contained in the message, if any. Shorthand
for `telethon.client.downloads.DownloadMethods.download_media`
with the ``message`` already set. |
def _removeOldBackRefs(senderkey, signal, receiver, receivers):
"""Kill old sendersBack references from receiver
This guards against multiple registration of the same
receiver for a given signal and sender leaking memory
as old back reference records build up.
Also removes old receiver instance fr... | Kill old sendersBack references from receiver
This guards against multiple registration of the same
receiver for a given signal and sender leaking memory
as old back reference records build up.
Also removes old receiver instance from receivers |
def min_item(self):
"""Get item with min key of tree, raises ValueError if tree is empty."""
if self.is_empty():
raise ValueError("Tree is empty")
node = self._root
while node.left is not None:
node = node.left
return node.key, node.value | Get item with min key of tree, raises ValueError if tree is empty. |
def update(self, retry=2) -> None:
"""Synchronize state with switch."""
try:
_LOGGER.debug("Updating device state.")
key = ON_KEY if not self._flip_on_off else OFF_KEY
self.state = self._device.readCharacteristic(HANDLE) == key
except (bluepy.btle.BTLEExceptio... | Synchronize state with switch. |
def frombed(args):
"""
%prog frombed bedfile
Generate AGP file based on bed file. The bed file must have at least 6
columns. With the 4-th column indicating the new object.
"""
p = OptionParser(frombed.__doc__)
p.add_option("--gapsize", default=100, type="int",
help="Insert... | %prog frombed bedfile
Generate AGP file based on bed file. The bed file must have at least 6
columns. With the 4-th column indicating the new object. |
def __get_extra_extension_classes(paths):
"""
Banana banana
"""
extra_classes = []
wset = pkg_resources.WorkingSet([])
distributions, _ = wset.find_plugins(pkg_resources.Environment(paths))
for dist in distributions:
sys.path.append(dist.location)
wset.add(dist)
for ent... | Banana banana |
def keyring_parser(path):
"""
This is a very, very, dumb parser that will look for `[entity]` sections
and return a list of those sections. It is not possible to parse this with
ConfigParser even though it is almost the same thing.
Since this is only used to spit out warnings, it is OK to just be n... | This is a very, very, dumb parser that will look for `[entity]` sections
and return a list of those sections. It is not possible to parse this with
ConfigParser even though it is almost the same thing.
Since this is only used to spit out warnings, it is OK to just be naive
about the parsing. |
def shelter_find(self, **kwargs):
"""
shelter.find wrapper. Returns a generator of shelter record dicts
matching your search criteria.
:rtype: generator
:returns: A generator of shelter record dicts.
:raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have
... | shelter.find wrapper. Returns a generator of shelter record dicts
matching your search criteria.
:rtype: generator
:returns: A generator of shelter record dicts.
:raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have
reached the maximum number of records your cr... |
def login(self, params):
"""Login either with resume token or password."""
if 'password' in params:
return self.login_with_password(params)
elif 'resume' in params:
return self.login_with_resume_token(params)
else:
self.auth_failed(**params) | Login either with resume token or password. |
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
return self.show_page(course, web.input()) | GET request |
def delete_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
"""Remove a subscription # noqa: E501
To remove an existing subscription from a resource path. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{r... | Remove a subscription # noqa: E501
To remove an existing subscription from a resource path. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a ... |
def K(self):
"""
Get the intrinsic matrix for the Camera object.
Returns
-----------
K : (3, 3) float
Intrinsic matrix for camera
"""
K = np.eye(3, dtype=np.float64)
K[0, 0] = self.focal[0]
K[1, 1] = self.focal[1]
K[0, 2] = self.... | Get the intrinsic matrix for the Camera object.
Returns
-----------
K : (3, 3) float
Intrinsic matrix for camera |
def save_genome_fitness(self,
delimiter=' ',
filename='fitness_history.csv',
with_cross_validation=False):
""" Saves the population's best and average fitness. """
with open(filename, 'w') as f:
w = csv.write... | Saves the population's best and average fitness. |
def alterar(self, id_logicalenvironment, name):
"""Change Logical Environment from by the identifier.
:param id_logicalenvironment: Identifier of the Logical Environment. Integer value and greater than zero.
:param name: Logical Environment name. String with a minimum 2 and maximum of 80 charac... | Change Logical Environment from by the identifier.
:param id_logicalenvironment: Identifier of the Logical Environment. Integer value and greater than zero.
:param name: Logical Environment name. String with a minimum 2 and maximum of 80 characters
:return: None
:raise InvalidParamete... |
def get_output_file(self, in_file, instance, field, **kwargs):
"""Creates a temporary file. With regular `FileSystemStorage` it does not
need to be deleted, instaed file is safely moved over. With other cloud
based storage it is a good idea to set `delete=True`."""
return NamedTemporary... | Creates a temporary file. With regular `FileSystemStorage` it does not
need to be deleted, instaed file is safely moved over. With other cloud
based storage it is a good idea to set `delete=True`. |
def create_csr(ca_name,
bits=2048,
CN='localhost',
C='US',
ST='Utah',
L='Salt Lake City',
O='SaltStack',
OU=None,
emailAddress=None,
subjectAltName=None,
cacert_path=None... | Create a Certificate Signing Request (CSR) for a
particular Certificate Authority (CA)
ca_name
name of the CA
bits
number of RSA key bits, default is 2048
CN
common name in the request, default is "localhost"
C
country, default is "US"
ST
state, default i... |
def greedy(problem, graph_search=False, viewer=None):
'''
Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic.
'''
return _search(problem,
... | Greedy search.
If graph_search=True, will avoid exploring repeated states.
Requires: SearchProblem.actions, SearchProblem.result,
SearchProblem.is_goal, SearchProblem.cost, and SearchProblem.heuristic. |
def infer_module_name(filename, fspath):
"""Convert a python filename to a module relative to pythonpath."""
filename, _ = os.path.splitext(filename)
for f in fspath:
short_name = f.relative_path(filename)
if short_name:
# The module name for __init__.py files is the directory.
... | Convert a python filename to a module relative to pythonpath. |
def sign(hash,priv,k=0):
'''
Returns a DER-encoded signature from a input of a hash and private
key, and optionally a K value.
Hash and private key inputs must be 64-char hex strings,
k input is an int/long.
>>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e'
>>> p =... | Returns a DER-encoded signature from a input of a hash and private
key, and optionally a K value.
Hash and private key inputs must be 64-char hex strings,
k input is an int/long.
>>> h = 'f7011e94125b5bba7f62eb25efe23339eb1637539206c87df3ee61b5ec6b023e'
>>> p = 'c05694a7af0e01dceb63e5912a415c28d3f... |
def parse(self, *args, **kw):
"""Parse command line, fill `fuse_args` attribute."""
ev = 'errex' in kw and kw.pop('errex')
if ev and not isinstance(ev, int):
raise TypeError("error exit value should be an integer")
try:
self.cmdline = self.parser.parse_args(*arg... | Parse command line, fill `fuse_args` attribute. |
def get_conversation_reference(activity: Activity) -> ConversationReference:
"""
Returns the conversation reference for an activity. This can be saved as a plain old JSON
object and then later used to message the user proactively.
Usage Example:
reference = TurnContext.get_conve... | Returns the conversation reference for an activity. This can be saved as a plain old JSON
object and then later used to message the user proactively.
Usage Example:
reference = TurnContext.get_conversation_reference(context.request)
:param activity:
:return: |
def stop(self):
"""
Stops this QEMU VM.
"""
yield from self._stop_ubridge()
with (yield from self._execute_lock):
# stop the QEMU process
self._hw_virtualization = False
if self.is_running():
log.info('Stopping QEMU VM "{}" PID... | Stops this QEMU VM. |
def glob_by_extensions(directory, extensions):
""" Returns files matched by all extensions in the extensions list """
directorycheck(directory)
files = []
xt = files.extend
for ex in extensions:
xt(glob.glob('{0}/*.{1}'.format(directory, ex)))
return files | Returns files matched by all extensions in the extensions list |
def add(self, steamid_or_accountname_or_email):
"""
Add/Accept a steam user to be your friend.
When someone sends you an invite, use this method to accept it.
:param steamid_or_accountname_or_email: steamid, account name, or email
:type steamid_or_accountname_or_email: :class:`i... | Add/Accept a steam user to be your friend.
When someone sends you an invite, use this method to accept it.
:param steamid_or_accountname_or_email: steamid, account name, or email
:type steamid_or_accountname_or_email: :class:`int`, :class:`.SteamID`, :class:`.SteamUser`, :class:`str`
.... |
def killCellRegion(self, centerColumn, radius):
"""
Kill cells around a centerColumn, within radius
"""
self.deadCols = topology.wrappingNeighborhood(centerColumn,
radius,
self._columnDimensions)
self.deadColumnInput... | Kill cells around a centerColumn, within radius |
def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs):
"""
Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_n... | Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_namespaced_custom_object(group, version, namespace, plural, name, async_req=True)
>>> result = thread.ge... |
def train_rf_classifier(
collected_features,
test_fraction=0.25,
n_crossval_iterations=20,
n_kfolds=5,
crossval_scoring_metric='f1',
classifier_to_pickle=None,
nworkers=-1,
):
'''This gets the best RF classifier after running cross-validation.
- splits t... | This gets the best RF classifier after running cross-validation.
- splits the training set into test/train samples
- does `KFold` stratified cross-validation using `RandomizedSearchCV`
- gets the `RandomForestClassifier` with the best performance after CV
- gets the confusion matrix for the test set
... |
def efficient_risk(self, target_risk, risk_free_rate=0.02, market_neutral=False):
"""
Calculate the Sharpe-maximising portfolio for a given volatility (i.e max return
for a target risk).
:param target_risk: the desired volatility of the resulting portfolio.
:type target_risk: fl... | Calculate the Sharpe-maximising portfolio for a given volatility (i.e max return
for a target risk).
:param target_risk: the desired volatility of the resulting portfolio.
:type target_risk: float
:param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02
:type... |
def integrate(self, min, max, attr=None, info={}):
""" Calculate the total number of points between [min, max).
If attr is given, also calculate the sum of the weight.
This is a M log(N) operation, where M is the number of min/max
queries and N is number of points.
... | Calculate the total number of points between [min, max).
If attr is given, also calculate the sum of the weight.
This is a M log(N) operation, where M is the number of min/max
queries and N is number of points. |
def c_metadata(api, args, verbose=False):
"""
Set or get metadata associated with an object::
usage: cdstar metadata <URL> [<JSON>]
<JSON> Path to metadata in JSON, or JSON literal.
"""
obj = api.get_object(args['<URL>'].split('/')[-1])
if not set_metadata(args['<JSON>'], obj):
return jso... | Set or get metadata associated with an object::
usage: cdstar metadata <URL> [<JSON>]
<JSON> Path to metadata in JSON, or JSON literal. |
def transcripts(self):
"""
Property which dynamically construct transcript objects for all
transcript IDs associated with this gene.
"""
transcript_id_results = self.db.query(
select_column_names=['transcript_id'],
filter_column='gene_id',
filt... | Property which dynamically construct transcript objects for all
transcript IDs associated with this gene. |
def thread_partition_array(x):
"Partition work arrays for multithreaded addition and multiplication"
n_threads = get_threadpool_size()
if len(x.shape) > 1:
maxind = x.shape[1]
else:
maxind = x.shape[0]
bounds = np.array(np.linspace(0, maxind, n_threads + 1), dtype='int')
cmin = b... | Partition work arrays for multithreaded addition and multiplication |
def parseline(self, line: str) -> Tuple[str, str, str]:
"""Parse the line into a command name and a string containing the arguments.
NOTE: This is an override of a parent class method. It is only used by other parent class methods.
Different from the parent class method, this ignores self.ide... | Parse the line into a command name and a string containing the arguments.
NOTE: This is an override of a parent class method. It is only used by other parent class methods.
Different from the parent class method, this ignores self.identchars.
:param line: line read by readline
:retur... |
def NetshStaticIp(interface,
ip=u'127.0.0.9',
subnet=u'255.255.255.255',
gw=u'127.0.0.1'):
"""Changes interface to a staticly set IP.
Sets IP configs to local if no paramaters passed.
Args:
interface: Name of the interface.
ip: IP address.
subnet... | Changes interface to a staticly set IP.
Sets IP configs to local if no paramaters passed.
Args:
interface: Name of the interface.
ip: IP address.
subnet: Subnet mask.
gw: IP address of the default gateway.
Returns:
A tuple of stdout, stderr, exit_status. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.