code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def cli(ctx, feature_id, description, organism="", sequence=""):
"""Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]})
"""
return ctx.gi.annotations.set_description(feature_id, description, organism=organism, sequence=sequence) | Set a feature's description
Output:
A standard apollo feature dictionary ({"features": [{...}]}) |
def addField(self, name, fieldParams, encoderParams):
"""Add a single field to the dataset.
Parameters:
-------------------------------------------------------------------
name: The user-specified name of the field
fieldSpec: A list of one or more dictionaries specifying parameter... | Add a single field to the dataset.
Parameters:
-------------------------------------------------------------------
name: The user-specified name of the field
fieldSpec: A list of one or more dictionaries specifying parameters
to be used for dataClass initializati... |
def _apply_uncertainty_to_mfd(self, mfd, value):
"""
Modify ``mfd`` object with uncertainty value ``value``.
"""
if self.uncertainty_type == 'abGRAbsolute':
a, b = value
mfd.modify('set_ab', dict(a_val=a, b_val=b))
elif self.uncertainty_type == 'bGRRelati... | Modify ``mfd`` object with uncertainty value ``value``. |
def ColumnToIndex (col):
"""convert column to index. Eg: ConvertInIndex("AB") = 28"""
ndx = 0
for c in col:
ndx = ndx * 26 + ord(c.upper()) - 64
return ndx | convert column to index. Eg: ConvertInIndex("AB") = 28 |
def init_associations(self, hdr_only=False, prt=sys.stdout):
"""Read GPAD file. HTTP address okay. GZIPPED/BZIPPED file okay."""
import timeit
import datetime
associations = []
tic = timeit.default_timer()
if self.filename is None:
return associations
... | Read GPAD file. HTTP address okay. GZIPPED/BZIPPED file okay. |
def AsHandler(request=None, modules=None, **kw):
'''Dispatch from within ModPython.'''
ps = ParsedSoap(request)
kw['request'] = request
_Dispatch(ps, modules, _ModPythonSendXML, _ModPythonSendFault, **kw) | Dispatch from within ModPython. |
def recognize_byte(self, image, timeout=10):
"""Process a byte image buffer."""
result = []
alpr = subprocess.Popen(
self._cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL
)
# send image
try:
... | Process a byte image buffer. |
def sklearn2pmml(pipeline, pmml, user_classpath = [], with_repr = False, debug = False, java_encoding = "UTF-8"):
"""Converts a fitted Scikit-Learn pipeline to PMML.
Parameters:
----------
pipeline: PMMLPipeline
The pipeline.
pmml: string
The path to where the PMML document should be stored.
user_classpath... | Converts a fitted Scikit-Learn pipeline to PMML.
Parameters:
----------
pipeline: PMMLPipeline
The pipeline.
pmml: string
The path to where the PMML document should be stored.
user_classpath: list of strings, optional
The paths to JAR files that provide custom Transformer, Selector and/or Estimator conver... |
def string_xor(a, b):
'''Computes the XOR operator between two byte strings. If the strings are
of different lengths, the result string is as long as the shorter.
'''
if sys.version_info[0] < 3:
return ''.join((chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)))
else:
return bytes(x ^ ... | Computes the XOR operator between two byte strings. If the strings are
of different lengths, the result string is as long as the shorter. |
def set_storage_account(
self, vault_base_url, storage_account_name, resource_id, active_key_name, auto_regenerate_key, regeneration_period=None, storage_account_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config):
"""Creates or updates a new storage account. This operati... | Creates or updates a new storage account. This operation requires the
storage/set permission.
:param vault_base_url: The vault name, for example
https://myvault.vault.azure.net.
:type vault_base_url: str
:param storage_account_name: The name of the storage account.
:typ... |
def _run(broker, graph=None, root=None, context=None, inventory=None):
"""
run is a general interface that is meant for stand alone scripts to use
when executing insights components.
Args:
root (str): None will causes a host collection in which command and
file specs are run. A dire... | run is a general interface that is meant for stand alone scripts to use
when executing insights components.
Args:
root (str): None will causes a host collection in which command and
file specs are run. A directory or archive path will cause
collection from the directory or archi... |
def decrypt(payload, private_key):
"""Decrypt an encrypted JSON payload and return the Magic Envelope document inside."""
cipher = PKCS1_v1_5.new(private_key)
aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None)
aes_key = json.loads(aes_key_str.decode("utf-8"))
... | Decrypt an encrypted JSON payload and return the Magic Envelope document inside. |
def create_vacation(body):
"""
Create a vacation.
"""
arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '200':
_LOGGER.error("Failed to create vacation. " + status_code)
... | Create a vacation. |
def _apply_final_rules(self, phonetic, final_rules, language_arg, strip):
"""Apply a set of final rules to the phonetic encoding.
Parameters
----------
phonetic : str
The term to which to apply the final rules
final_rules : tuple
The set of final phonetic... | Apply a set of final rules to the phonetic encoding.
Parameters
----------
phonetic : str
The term to which to apply the final rules
final_rules : tuple
The set of final phonetic transform regexps
language_arg : int
An integer representing the... |
def delete(self, album, **kwds):
"""
Endpoint: /album/<id>/delete.json
Deletes an album.
Returns True if successful.
Raises a TroveboxError if not.
"""
return self._client.post("/album/%s/delete.json" %
self._extract_id(album),
... | Endpoint: /album/<id>/delete.json
Deletes an album.
Returns True if successful.
Raises a TroveboxError if not. |
def cleaned_date(day, keep_datetime=False):
"""
Return a "clean" date type.
* keep a `date` unchanged
* convert a datetime into a date,
* convert any "duck date" type into a date using its `date()` method.
"""
if not isinstance(day, (date, datetime)):
raise UnsupportedDateType(
... | Return a "clean" date type.
* keep a `date` unchanged
* convert a datetime into a date,
* convert any "duck date" type into a date using its `date()` method. |
def find(im_source, im_search):
'''
Only find maximum one object
'''
r = find_all(im_source, im_search, maxcnt=1)
return r[0] if r else None | Only find maximum one object |
def restore(self):
"""
This method constructs the restoring beam and then adds the convolution to the residual.
"""
clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2)
if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)):
... | This method constructs the restoring beam and then adds the convolution to the residual. |
def annotate(self, records, **kwargs):
"""Annotate a set of records with stored fields.
Args:
records: A list or iterator (can be a Query object)
chunk_size: The number of records to annotate at once (max 500).
Returns:
A generator that yields one annotated ... | Annotate a set of records with stored fields.
Args:
records: A list or iterator (can be a Query object)
chunk_size: The number of records to annotate at once (max 500).
Returns:
A generator that yields one annotated record at a time. |
def fetch_query_from_pgdb(self, qname, query, con, cxn, limit=None, force=False):
"""
Supply either an already established connection, or connection parameters.
The supplied connection will override any separate cxn parameter
:param qname: The name of the query to save the output to
... | Supply either an already established connection, or connection parameters.
The supplied connection will override any separate cxn parameter
:param qname: The name of the query to save the output to
:param query: The SQL query itself
:param con: The already-established connection
... |
def register(name=EopDb.DEFAULT_DBNAME):
"""Decorator for registering an Eop Database
Example:
.. code-block:: python
@register
class SqliteEnvDatabase:
# sqlite implementation
# this database will be known as 'default'
@register('json')
class Json... | Decorator for registering an Eop Database
Example:
.. code-block:: python
@register
class SqliteEnvDatabase:
# sqlite implementation
# this database will be known as 'default'
@register('json')
class JsonEnvDatabase:
# JSON implementation
... |
def get_forced_variation(self, experiment_key, user_id):
""" Gets the forced variation for a given user and experiment.
Args:
experiment_key: A string key identifying the experiment.
user_id: The user ID.
Returns:
The forced variation key. None if no forced variation key.
"""
if... | Gets the forced variation for a given user and experiment.
Args:
experiment_key: A string key identifying the experiment.
user_id: The user ID.
Returns:
The forced variation key. None if no forced variation key. |
def get_term_category_frequencies(self, scatterchartdata):
'''
Applies the ranker in scatterchartdata to term-category frequencies.
Parameters
----------
scatterchartdata : ScatterChartData
Returns
-------
pd.DataFrame
'''
term_ranker = s... | Applies the ranker in scatterchartdata to term-category frequencies.
Parameters
----------
scatterchartdata : ScatterChartData
Returns
-------
pd.DataFrame |
def __shpFileLength(self):
"""Calculates the file length of the shp file."""
# Remember starting position
start = self.shp.tell()
# Calculate size of all shapes
self.shp.seek(0,2)
size = self.shp.tell()
# Calculate size as 16-bit words
size //= 2
... | Calculates the file length of the shp file. |
def append(self,*args,toSection=None,**kwargs):
"""Append a new section
If toSection is None, section is appended to the main section/subs list.
Else if toSection is int or (int,int,...), it gets added to the subs (subsection)
list of the specified section.
*args* and *kwargs* a... | Append a new section
If toSection is None, section is appended to the main section/subs list.
Else if toSection is int or (int,int,...), it gets added to the subs (subsection)
list of the specified section.
*args* and *kwargs* are processed by Section class initiation |
def extractblocks(img, blksz, stpsz=None):
"""Extract blocks from an ndarray signal into an ndarray.
Parameters
----------
img : ndarray or tuple of ndarrays
nd array of images, or tuple of images
blksz : tuple
tuple of block sizes, blocks are taken starting from the first index
o... | Extract blocks from an ndarray signal into an ndarray.
Parameters
----------
img : ndarray or tuple of ndarrays
nd array of images, or tuple of images
blksz : tuple
tuple of block sizes, blocks are taken starting from the first index
of img
stpsz : tuple, optional (default None, c... |
def any_shared(enum_one, enum_two):
'''
Truthy if any element in enum_one is present in enum_two
'''
if not is_collection(enum_one) or not is_collection(enum_two):
return False
enum_one = enum_one if isinstance(enum_one, (set, dict)) else set(enum_one)
enum_two = enum_two if isins... | Truthy if any element in enum_one is present in enum_two |
def to_sparse(self, fill_value=None, kind='block'):
"""
Convert to SparseDataFrame.
Implement the sparse version of the DataFrame meaning that any data
matching a specific value it's omitted in the representation.
The sparse DataFrame allows for a more efficient storage.
... | Convert to SparseDataFrame.
Implement the sparse version of the DataFrame meaning that any data
matching a specific value it's omitted in the representation.
The sparse DataFrame allows for a more efficient storage.
Parameters
----------
fill_value : float, default None... |
def get_update_io_tiles(self, params, values):
"""
Get the tiles corresponding to a particular section of image needed to
be updated. Inputs are the parameters and values. Returned is the
padded tile, inner tile, and slicer to go between, but accounting for
wrap with the edge of ... | Get the tiles corresponding to a particular section of image needed to
be updated. Inputs are the parameters and values. Returned is the
padded tile, inner tile, and slicer to go between, but accounting for
wrap with the edge of the image as necessary. |
def replace(self, resource, id_, document):
"""Replace document in index."""
args = self._es_args(resource, refresh=True)
document.pop('_id', None)
document.pop('_type', None)
self._update_parent_args(resource, args, document)
return self.elastic(resource).index(body=docu... | Replace document in index. |
def filter_noexpand_columns(columns):
"""Return columns not containing and containing the noexpand prefix.
Parameters
----------
columns: sequence of str
A sequence of strings to be split
Returns
-------
Two lists, the first containing strings without the noexpand prefix, the
... | Return columns not containing and containing the noexpand prefix.
Parameters
----------
columns: sequence of str
A sequence of strings to be split
Returns
-------
Two lists, the first containing strings without the noexpand prefix, the
second containing those that do with the pre... |
def _get_pc_covered_str(self):
"""Returns the percent covered, as a string, without a percent sign.
Note that "0" is only returned when the value is truly zero, and "100"
is only returned when the value is truly 100. Rounding can never
result in either "0" or "100".
"""
... | Returns the percent covered, as a string, without a percent sign.
Note that "0" is only returned when the value is truly zero, and "100"
is only returned when the value is truly 100. Rounding can never
result in either "0" or "100". |
def align_circulation_with_z(self, circulation=None):
"""
If the input orbit is a tube orbit, this function aligns the circulation
axis with the z axis and returns a copy.
Parameters
----------
circulation : array_like (optional)
Array of bits that specify th... | If the input orbit is a tube orbit, this function aligns the circulation
axis with the z axis and returns a copy.
Parameters
----------
circulation : array_like (optional)
Array of bits that specify the axis about which the orbit
circulates. If not provided, will... |
def current() -> 'Process':
"""
Returns the instance of the process that is executing at the current moment.
"""
curr = greenlet.getcurrent()
if not isinstance(curr, Process):
raise TypeError("Current greenlet does not correspond to a Process instance.")
retur... | Returns the instance of the process that is executing at the current moment. |
def set(self, value: int):
"""
Set the immediate to a value. This function checks if the value is valid and will raise an
:class:`InvalidImmediateException` if it doesn't.
:param value: Value to set the immediate to
:type value: int
:raises InvalidImmediateException: va... | Set the immediate to a value. This function checks if the value is valid and will raise an
:class:`InvalidImmediateException` if it doesn't.
:param value: Value to set the immediate to
:type value: int
:raises InvalidImmediateException: value does not match immediate |
def make_into_gene(self):
'''Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple (new sequence, strand, frame) if it was successful. Otherwise returns None.'''
for reverse in [True, False]:
for frame in range(3):
new_seq = copy... | Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple (new sequence, strand, frame) if it was successful. Otherwise returns None. |
def init_UI(self):
"""
Set display variables (font, resolution of GUI, sizer proportions)
then builds the Side bar panel, Top bar panel, and Plots scrolleing
panel which are then placed placed together in a sizer and fit to
the GUI wx.Frame
"""
# -------------------------... | Set display variables (font, resolution of GUI, sizer proportions)
then builds the Side bar panel, Top bar panel, and Plots scrolleing
panel which are then placed placed together in a sizer and fit to
the GUI wx.Frame |
def import_string(name):
""" import module
"""
mod = fp = None
# code below, please refer to
# https://docs.python.org/2/library/imp.html
# for details
try:
return sys.modules[name]
except KeyError:
pass
try:
fp, pathname, desc = imp.find_module(name)
... | import module |
def get(name=None):
"""
Return a named Palette, or None if no such name exists.
If ``name`` is omitted, the default value is used.
"""
if name is None or name == 'default':
return _DEFAULT_PALETTE
if isinstance(name, str):
return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES.... | Return a named Palette, or None if no such name exists.
If ``name`` is omitted, the default value is used. |
def register(app_name, modules):
"""
simple module registering for later usage
we don't want to import admin.py in models.py
"""
global INSTALLED_APPS_REGISTER
mod_list = INSTALLED_APPS_REGISTER.get(app_name, [])
if isinstance(modules, basestring):
mod_list.append(modules)
elif ... | simple module registering for later usage
we don't want to import admin.py in models.py |
def _mirbase_stats(data, out_dir):
"""Create stats from miraligner"""
utils.safe_makedir(out_dir)
out_file = os.path.join(out_dir, "%s_bcbio_mirbase.txt" % dd.get_sample_name(data))
out_file_novel = os.path.join(out_dir, "%s_bcbio_mirdeeep2.txt" % dd.get_sample_name(data))
mirbase_fn = data.get("seq... | Create stats from miraligner |
def NewFromCmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF):
'''Create a new instance based on the specifed CMY values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:alpha:
The ... | Create a new instance based on the specifed CMY values.
Parameters:
:c:
The Cyan component value [0...1]
:m:
The Magenta component value [0...1]
:y:
The Yellow component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
... |
def search(self, **kwargs):
"""
Method to search ipv6's based on extends search.
:param search: Dict containing QuerySets to find ipv6's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:para... | Method to search ipv6's based on extends search.
:param search: Dict containing QuerySets to find ipv6's.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to override d... |
def upload_from_url_sync(cls, url, timeout=30, interval=0.3,
until_ready=False, store=None, filename=None):
"""Uploads file from given url and returns ``File`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the... | Uploads file from given url and returns ``File`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not store file
- True - st... |
def from_compact_str(cls, str_pauli_term):
"""Construct a PauliTerm from the result of str(pauli_term)
"""
coef_str, str_pauli_term = str_pauli_term.split('*')
try:
coef = int(coef_str)
except ValueError:
try:
coef = float(coef_str)
... | Construct a PauliTerm from the result of str(pauli_term) |
def block_cm(cm):
"""Return whether ``cm`` can be arranged as a block connectivity matrix.
If so, the corresponding mechanism/purview is trivially reducible.
Technically, only square matrices are "block diagonal", but the notion of
connectivity carries over.
We test for block connectivity by tryin... | Return whether ``cm`` can be arranged as a block connectivity matrix.
If so, the corresponding mechanism/purview is trivially reducible.
Technically, only square matrices are "block diagonal", but the notion of
connectivity carries over.
We test for block connectivity by trying to grow a block of node... |
def resolve(str_or_obj):
"""Returns object from string"""
from rope.base.utils.pycompat import string_types
if not isinstance(str_or_obj, string_types):
return str_or_obj
if '.' not in str_or_obj:
str_or_obj += '.'
mod_name, obj_name = str_or_obj.rsplit('.', 1)
__import__(mod_nam... | Returns object from string |
def internal_error(exception, template_path, is_admin, db=None):
"""
Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whethe... | Render an "internal error" page. The following variables will be populated when rendering the
template:
title: The page title
message: The body of the error message to display to the user
preformat: Boolean stating whether to wrap the error message in a pre
As well as rendering the error mess... |
def update_journals(self):
"""773 journal translations."""
for field in record_get_field_instances(self.record, '773'):
subs = field_get_subfield_instances(field)
new_subs = []
volume_letter = ""
journal_name = ""
for idx, (key, value) in enume... | 773 journal translations. |
def vertex_neighbors(self):
"""
The vertex neighbors of each vertex of the mesh, determined from
the cached vertex_adjacency_graph, if already existent.
Returns
----------
vertex_neighbors : (len(self.vertices),) int
Represents immediate neighbors of each verte... | The vertex neighbors of each vertex of the mesh, determined from
the cached vertex_adjacency_graph, if already existent.
Returns
----------
vertex_neighbors : (len(self.vertices),) int
Represents immediate neighbors of each vertex along
the edge of a triangle
... |
def listEverything(matching=False):
"""Prints every page in the project to the console.
Args:
matching (str, optional): if given, only return names with this string in it
"""
pages=pageNames()
if matching:
pages=[x for x in pages if matching in x]
for i,page in enumerate(pages)... | Prints every page in the project to the console.
Args:
matching (str, optional): if given, only return names with this string in it |
def molecular_diameter(Tc=None, Pc=None, Vc=None, Zc=None, omega=None,
Vm=None, Vb=None, CASRN='', AvailableMethods=False, Method=None):
r'''This function handles the retrieval or calculation a chemical's
L-J molecular diameter. Values are available from one source with lookup
based on CASRNs, or ... | r'''This function handles the retrieval or calculation a chemical's
L-J molecular diameter. Values are available from one source with lookup
based on CASRNs, or can be estimated from 9 CSP methods.
Will automatically select a data source to use if no Method is provided;
returns None if the data is not a... |
def _parse_desc(node):
""" A quick'n'dirty description parser """
desc = ''
if len(node) == 0:
return '<p>' + node.text + '</p>'
for n in node:
if n.tag == 'p':
desc += '<p>' + _join_lines(n.text) + '</p>'
elif n.tag == 'ol' or n.tag == 'ul':
desc += '<ul>... | A quick'n'dirty description parser |
def isTrackedDeviceConnected(self, unDeviceIndex):
"""Returns true if there is a device connected in this slot."""
fn = self.function_table.isTrackedDeviceConnected
result = fn(unDeviceIndex)
return result | Returns true if there is a device connected in this slot. |
def process_IN_IGNORED(self, raw_event):
"""
The watch descriptor raised by this event is now ignored (forever),
it can be safely deleted from the watch manager dictionary.
After this event we can be sure that neither the event queue nor
the system will raise an event associated ... | The watch descriptor raised by this event is now ignored (forever),
it can be safely deleted from the watch manager dictionary.
After this event we can be sure that neither the event queue nor
the system will raise an event associated to this wd again. |
def cached_path(self, path_or_url):
"""
When downloading remote files, the default behavior is to name local
files the same as their remote counterparts.
"""
assert path_or_url, "Expected non-empty string for path_or_url"
remote_filename = split(path_or_url)[1]
if... | When downloading remote files, the default behavior is to name local
files the same as their remote counterparts. |
def unpacktar(tarfile, destdir):
""" Unpack given tarball into the specified dir """
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("unpack tar %s into %s", tarfile, destdir)
try:
check_call([TAR, '-xzf', tarfile], cwd=destdir,
stdout=... | Unpack given tarball into the specified dir |
def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that properties make sense
self.sanitize()
# Start with the type
bitstream = BitArray('uint:4=%d' % self.message_type)
# Add the flags
bitstream += BitArray('bool=%d' % self.proxy_... | Create bytes from properties |
def next_tick(date, interval=15):
'''
Only return when we reach given datetime
'''
# Intuition works with utc dates, conversion are made for I/O
now = dt.datetime.now(pytz.utc)
live = False
# Sleep until we reach the given date
while now < date:
time.sleep(interval)
# Upd... | Only return when we reach given datetime |
def clearAndSetComboBoxes(self, axesNames):
""" Removes all comboboxes.
"""
logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames))
check_is_a_sequence(axesNames)
row = 0
self._deleteComboBoxes(row)
self.clear()
self._setAxesNames(axesNames)
... | Removes all comboboxes. |
def check_package(self, package, package_dir):
"""Check namespace packages' __init__ for declare_namespace"""
try:
return self.packages_checked[package]
except KeyError:
pass
init_py = orig.build_py.check_package(self, package, package_dir)
self.packages_... | Check namespace packages' __init__ for declare_namespace |
def disable(self):
"""
Disable all the widgets in this container
"""
self._enabled = False
for child in self.children:
if isinstance(child, (Container, Widget)):
child.disable() | Disable all the widgets in this container |
def multipart_etag(digests):
"""
Computes etag for multipart uploads
:type digests: list of hex-encoded md5 sums (string)
:param digests: The list of digests for each individual chunk.
:rtype: string
:returns: The etag computed from the individual chunks.
"""
etag = hashlib.md5()
co... | Computes etag for multipart uploads
:type digests: list of hex-encoded md5 sums (string)
:param digests: The list of digests for each individual chunk.
:rtype: string
:returns: The etag computed from the individual chunks. |
def draw_rand_pos(self, radius, z_min, z_max,
min_r=np.array([0]), min_cell_interdist=10., **args):
"""
Draw some random location within radius, z_min, z_max,
and constrained by min_r and the minimum cell interdistance.
Returned argument is a list of dicts [{'xpos',... | Draw some random location within radius, z_min, z_max,
and constrained by min_r and the minimum cell interdistance.
Returned argument is a list of dicts [{'xpos', 'ypos', 'zpos'},].
Parameters
----------
radius : float
Radius of population.
z_min : float
... |
def run_command(self, command, shell=True, env=None, execute='/bin/bash',
return_code=None):
"""Run a shell command.
The options available:
* ``shell`` to be enabled or disabled, which provides the ability
to execute arbitrary stings or not. if disabled co... | Run a shell command.
The options available:
* ``shell`` to be enabled or disabled, which provides the ability
to execute arbitrary stings or not. if disabled commands must be
in the format of a ``list``
* ``env`` is an environment override and or manipulati... |
def get_checkers(self):
"""return all available checkers as a list"""
return [self] + [
c
for _checkers in self._checkers.values()
for c in _checkers
if c is not self
] | return all available checkers as a list |
def friendships(user_id, level=2):
"""
Pass in a user_id and you will be returned a generator of friendship
tuples (user_id, friend_id). By default it will return the friend
of a friend network (level=2), but you can expand this by settings the
level parameter to either another number. But beware,... | Pass in a user_id and you will be returned a generator of friendship
tuples (user_id, friend_id). By default it will return the friend
of a friend network (level=2), but you can expand this by settings the
level parameter to either another number. But beware, it could run for a
while! |
def detach(self, listener):
"""Detach a listening object so that it won't receive any events
anymore."""
if listener in self.listeners:
self.listeners.remove(listener) | Detach a listening object so that it won't receive any events
anymore. |
def add_account(self, account):
'portfolio add a account/stratetgy'
if account.account_cookie not in self.account_list:
if self.cash_available > account.init_cash:
account.portfolio_cookie = self.portfolio_cookie
account.user_cookie = self.user_cookie
... | portfolio add a account/stratetgy |
def reduce_(self):
r"""Return a degree-reduced version of the current curve.
.. _pseudo-inverse:
https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse
Does this by converting the current nodes :math:`v_0, \ldots, v_n`
to new nodes :math:`w_0, \ldots, w_{n - 1}` ... | r"""Return a degree-reduced version of the current curve.
.. _pseudo-inverse:
https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse
Does this by converting the current nodes :math:`v_0, \ldots, v_n`
to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to
... |
def complete(self):
"""Gets a list of completion objects for the symbol under the cursor."""
if self._possible is None:
self._possible = []
for possible in self.names:
c = Completion(self.context, self.names[possible], len(self.context.symbol))
sel... | Gets a list of completion objects for the symbol under the cursor. |
def as_id_dict(self):
"""
Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
"""
d = {}
for row in self:
if row.experiment_id not in d:
d[row.experiment_id] = {}
if (row.time_slide_id, row.veto_def_name, row.datatyp... | Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id. |
def register_for_json(*args, **kwargs) -> Any:
"""
Class decorator to register classes with our JSON system.
- If method is ``'provides_init_args_kwargs'``, the class provides a
function
.. code-block:: python
def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]]
that ... | Class decorator to register classes with our JSON system.
- If method is ``'provides_init_args_kwargs'``, the class provides a
function
.. code-block:: python
def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]]
that returns an ``(args, kwargs)`` tuple, suitable for passing t... |
def energy(self):
"""Compute the energy of the system"""
result = 0.0
for index1 in range(self.numc):
for index2 in range(index1):
if self.scaling[index1, index2] > 0:
for se, ve in self.yield_pair_energies(index1, index2):
... | Compute the energy of the system |
def common_parent_go_ids(goids, godag):
'''
This function finds the common ancestors in the GO
tree of the list of goids in the input.
'''
# Find candidates from first
rec = godag[goids[0]]
candidates = rec.get_all_parents()
candidates.update({goids[0]})
# Find intersection ... | This function finds the common ancestors in the GO
tree of the list of goids in the input. |
def ip_rtm_config_route_static_route_oif_vrf_static_route_next_vrf_dest(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns="... | Auto Generated Code |
def block_resource_fitnesses(self, block: block.Block):
"""Returns a map of nodename to average fitness value for this block.
Assumes that required resources have been checked on all nodes."""
# Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where
# t... | Returns a map of nodename to average fitness value for this block.
Assumes that required resources have been checked on all nodes. |
def get_dimensions(js_dict, naming):
"""Get dimensions from input data.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
naming (string, optional): dimension naming. Possible values: 'label' \
or 'id'.
Returns:
dimensions (list): lis... | Get dimensions from input data.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
naming (string, optional): dimension naming. Possible values: 'label' \
or 'id'.
Returns:
dimensions (list): list of pandas data frames with dimension \
... |
async def genKeys(self, schemaId: ID, p_prime=None, q_prime=None) -> (
PublicKey, RevocationPublicKey):
"""
Generates and submits keys (both public and secret, primary and
non-revocation).
:param schemaId: The schema ID (reference to claim
definition schema)
... | Generates and submits keys (both public and secret, primary and
non-revocation).
:param schemaId: The schema ID (reference to claim
definition schema)
:param p_prime: optional p_prime parameter
:param q_prime: optional q_prime parameter
:return: Submitted Public keys (bo... |
def after_feature(context, feature):
""" stop all Patronis, remove their data directory and cleanup the keys in etcd """
context.pctl.stop_all()
shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data'))
context.dcs_ctl.cleanup_service_tree()
if feature.status == 'failed':
shutil.copytre... | stop all Patronis, remove their data directory and cleanup the keys in etcd |
def _get_pkg_info(*packages, **kwargs):
'''
Return list of package information. If 'packages' parameter is empty,
then data about all installed packages will be returned.
:param packages: Specified packages.
:param failhard: Throw an exception if no packages found.
:return:
'''
kwargs =... | Return list of package information. If 'packages' parameter is empty,
then data about all installed packages will be returned.
:param packages: Specified packages.
:param failhard: Throw an exception if no packages found.
:return: |
def Levenshtein_Distance(w1, w2):
"""
Computes Levenshtein Distance between two words
Args:
:param w1: str
:param w2: str
:return: int
Examples:
>>> Levenshtein.Levenshtein_Distance('noctis', 'noctem')
2
>>> Leve... | Computes Levenshtein Distance between two words
Args:
:param w1: str
:param w2: str
:return: int
Examples:
>>> Levenshtein.Levenshtein_Distance('noctis', 'noctem')
2
>>> Levenshtein.Levenshtein_Distance('nox', 'nochem')
... |
def attach_virtual_server(self, ticket_id=None, virtual_id=None):
"""Attach a virtual server to a ticket.
:param integer ticket_id: the id of the ticket to attach to
:param integer virtual_id: the id of the virtual server to attach
:returns: dict -- The new ticket attachment
""... | Attach a virtual server to a ticket.
:param integer ticket_id: the id of the ticket to attach to
:param integer virtual_id: the id of the virtual server to attach
:returns: dict -- The new ticket attachment |
def extension_supported(extension_name, request):
"""Determine if nova supports a given extension name.
Example values for the extension_name include AdminActions, ConsoleOutput,
etc.
"""
for ext in list_extensions(request):
if ext.name == extension_name:
return True
return ... | Determine if nova supports a given extension name.
Example values for the extension_name include AdminActions, ConsoleOutput,
etc. |
def wrapJobFn(fn, *args, **kwargs):
"""
Makes a Job out of a job function. \
Convenience function for constructor of :class:`toil.job.JobFunctionWrappingJob`.
:param fn: Job function to be run with ``*args`` and ``**kwargs`` as arguments. \
See toil.job.JobFunctionWrappingJob fo... | Makes a Job out of a job function. \
Convenience function for constructor of :class:`toil.job.JobFunctionWrappingJob`.
:param fn: Job function to be run with ``*args`` and ``**kwargs`` as arguments. \
See toil.job.JobFunctionWrappingJob for reserved keyword arguments used \
to specify r... |
def _set_ethernet_interface(self, v, load=False):
"""
Setter method for ethernet_interface, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/ethernet_interface (container)
If this variable is read-only (config: false) in the
... | Setter method for ethernet_interface, mapped from YANG variable /rbridge_id/router/router_bgp/router_bgp_attributes/neighbor/neighbor_ips/neighbor_addr/update_source/ethernet_interface (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet_interface is considered a... |
def reqAccountSummary(self, reqId, groupName, tags):
"""reqAccountSummary(EClient self, int reqId, IBString const & groupName, IBString const & tags)"""
return _swigibpy.EClient_reqAccountSummary(self, reqId, groupName, tags) | reqAccountSummary(EClient self, int reqId, IBString const & groupName, IBString const & tags) |
def invoke(awsclient, function_name, payload, invocation_type=None,
alias_name=ALIAS_NAME, version=None, outfile=None):
"""Send a ping request to a lambda function.
:param awsclient:
:param function_name:
:param payload:
:param invocation_type:
:param alias_name:
:param version:
... | Send a ping request to a lambda function.
:param awsclient:
:param function_name:
:param payload:
:param invocation_type:
:param alias_name:
:param version:
:param outfile: write response to file
:return: ping response payload |
def combine_quantities(data, units='units', magnitude='magnitude',
list_of_dicts=False):
""" combine <unit,magnitude> pairs into pint.Quantity objects
Parameters
----------
data : dict
units : str
name of units key
magnitude : str
name of magnitude key
... | combine <unit,magnitude> pairs into pint.Quantity objects
Parameters
----------
data : dict
units : str
name of units key
magnitude : str
name of magnitude key
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint i... |
def is_lock(lock):
"""
Tests if the given lock is an instance of a lock class
"""
if lock is None:
# Don't do useless tests
return False
for attr in "acquire", "release", "__enter__", "__exit__":
if not hasattr(lock, attr):
# Missing something
return ... | Tests if the given lock is an instance of a lock class |
def enable(name, start_type='auto', start_delayed=False, **kwargs):
'''
Enable the named service to start at boot
Args:
name (str): The name of the service to enable.
start_type (str): Specifies the service start type. Valid options are as
follows:
- boot: Device d... | Enable the named service to start at boot
Args:
name (str): The name of the service to enable.
start_type (str): Specifies the service start type. Valid options are as
follows:
- boot: Device driver that is loaded by the boot loader
- system: Device driver that... |
def structured_mesh(shape = (2,2,2), dim = (1.,1.,1.)):
"""
Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH for... | Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH for mesh generation.
>>> import argiope as ag
>>> mesh =... |
def search_exoplanet(exoplanet):
'''
It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com
http://star-api.herokuapp.com/api/v1/exo_planets/11 Com
'''
base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/"
if not isins... | It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com
http://star-api.herokuapp.com/api/v1/exo_planets/11 Com |
def _assert_relation_does_not_exists(self):
"""
Check if a relation with the current related_name doesn't already exists
for the related model
"""
relations = self.database._relations[self.related_to]
existing = [r for r in relations if r[2] == self.related_name]
... | Check if a relation with the current related_name doesn't already exists
for the related model |
def set_rate(self, rate):
"""
Set the playback rate of the video as a multiple of the default playback speed
Examples:
>>> player.set_rate(2)
# Will play twice as fast as normal speed
>>> player.set_rate(0.5)
# Will play half speed
"""
... | Set the playback rate of the video as a multiple of the default playback speed
Examples:
>>> player.set_rate(2)
# Will play twice as fast as normal speed
>>> player.set_rate(0.5)
# Will play half speed |
def wnsumd(window):
"""
Summarize the contents of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html
:param window: Window to be summarized.
:type window: spiceypy.utils.support_types.SpiceCell
:return:
Total measure of intervals in wi... | Summarize the contents of a double precision window.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html
:param window: Window to be summarized.
:type window: spiceypy.utils.support_types.SpiceCell
:return:
Total measure of intervals in window,
Average measur... |
def get_smtlib_script_satisfiability(self, extra_constraints=(), extra_variables=()):
"""
Return an smt-lib script that check the satisfiability of the current constraints
:return string: smt-lib script
"""
try:
e_csts = self._solver_backend.convert_list(extra_constr... | Return an smt-lib script that check the satisfiability of the current constraints
:return string: smt-lib script |
def fig_to_src(figure, image_format='png', dpi=80):
"""Convert a matplotlib figure to an inline HTML image.
:param matplotlib.figure.Figure figure: Figure to display.
:param str image_format: png (default) or svg
:param int dpi: dots-per-inch for raster graphics.
:rtype: str
"""
if image_fo... | Convert a matplotlib figure to an inline HTML image.
:param matplotlib.figure.Figure figure: Figure to display.
:param str image_format: png (default) or svg
:param int dpi: dots-per-inch for raster graphics.
:rtype: str |
def maybe_reexec_pex(compatibility_constraints):
"""
Handle environment overrides for the Python interpreter to use when executing this pex.
This function supports interpreter filtering based on interpreter constraints stored in PEX-INFO
metadata. If PEX_PYTHON is set in a pexrc, it attempts to obtain the bina... | Handle environment overrides for the Python interpreter to use when executing this pex.
This function supports interpreter filtering based on interpreter constraints stored in PEX-INFO
metadata. If PEX_PYTHON is set in a pexrc, it attempts to obtain the binary location of the
interpreter specified by PEX_PYTHON.... |
def platform_config_dir():
"""
Returns a directory which should be writable for any application
This should be used for persistent configuration files.
Returns:
PathLike : path to the cahce dir used by the current operating system
"""
if LINUX: # nocover
dpath_ = os.environ.get... | Returns a directory which should be writable for any application
This should be used for persistent configuration files.
Returns:
PathLike : path to the cahce dir used by the current operating system |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.