positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def packSeptets(octets, padBits=0):
""" Packs the specified octets into septets
Typically the output of encodeGsm7 would be used as input to this function. The resulting
bytearray contains the original GSM-7 characters packed into septets ready for transmission.
:rtype: bytearray
"""
r... | Packs the specified octets into septets
Typically the output of encodeGsm7 would be used as input to this function. The resulting
bytearray contains the original GSM-7 characters packed into septets ready for transmission.
:rtype: bytearray |
def get_smart_contract(self, hex_contract_address: str, is_full: bool = False) -> dict:
"""
This interface is used to get the information of smart contract based on the specified hexadecimal hash value.
:param hex_contract_address: str, a hexadecimal hash value.
:param is_full:
... | This interface is used to get the information of smart contract based on the specified hexadecimal hash value.
:param hex_contract_address: str, a hexadecimal hash value.
:param is_full:
:return: the information of smart contract in dictionary form. |
def scores2recos(self, scores, candidates, rev=False):
"""Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (#... | Get recommendation list for a user u_index based on scores.
Args:
scores (numpy array; (n_target_items,)):
Scores for the target items. Smaller score indicates a promising item.
candidates (numpy array; (# target items, )): Target items' indices. Only these items are con... |
def clitable_to_dict(cli_table):
"""Converts TextFSM cli_table object to list of dictionaries."""
objs = []
for row in cli_table:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[cli_table.header[index].lower()] = element
objs.append(temp_dict)
return ob... | Converts TextFSM cli_table object to list of dictionaries. |
def _make_node_str_list(l):
"""Take a list of python objects and make a MPV string node array from it.
As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
struct mpv_node {
.format = MPV_NODE_ARRAY,
.u.list = *(struct mpv_n... | Take a list of python objects and make a MPV string node array from it.
As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
struct mpv_node {
.format = MPV_NODE_ARRAY,
.u.list = *(struct mpv_node_array){
.num = ... |
def has_no_dangling_branch(neuron):
'''Check if the neuron has dangling neurites'''
soma_center = neuron.soma.points[:, COLS.XYZ].mean(axis=0)
recentered_soma = neuron.soma.points[:, COLS.XYZ] - soma_center
radius = np.linalg.norm(recentered_soma, axis=1)
soma_max_radius = radius.max()
def is_d... | Check if the neuron has dangling neurites |
def hashVariantAnnotation(cls, gaVariant, gaVariantAnnotation):
"""
Produces an MD5 hash of the gaVariant and gaVariantAnnotation objects
"""
treffs = [treff.id for treff in gaVariantAnnotation.transcript_effects]
return hashlib.md5(
"{}\t{}\t{}\t".format(
... | Produces an MD5 hash of the gaVariant and gaVariantAnnotation objects |
def _get_jid_snapshots(jid, config='root'):
'''
Returns pre/post snapshots made by a given Salt jid
Looks for 'salt_jid' entries into snapshots userdata which are created
when 'snapper.run' is executed.
'''
jid_snapshots = [x for x in list_snapshots(config) if x['userdata'].get("salt_jid") == j... | Returns pre/post snapshots made by a given Salt jid
Looks for 'salt_jid' entries into snapshots userdata which are created
when 'snapper.run' is executed. |
def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string URI that is used to
instantiate the class, such as '2018-01-08-georgia'.
"""
if self._away_points is None and self._home_points ... | Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string URI that is used to
instantiate the class, such as '2018-01-08-georgia'. |
def construct_notebook_index(title, pthlst, pthidx):
"""
Construct a string containing a markdown format index for the list
of paths in `pthlst`. The title for the index is in `title`, and
`pthidx` is a dict giving label text for each path.
"""
# Insert title text
txt = '"""\n## %s\n"""\n\... | Construct a string containing a markdown format index for the list
of paths in `pthlst`. The title for the index is in `title`, and
`pthidx` is a dict giving label text for each path. |
def axis_as_object(arr, axis=-1):
"""cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
arr... | cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
array to view as void object type
axis :... |
def Not(x, simplify=True):
"""Expression negation operator
If *simplify* is ``True``, return a simplified expression.
"""
x = Expression.box(x).node
y = exprnode.not_(x)
if simplify:
y = y.simplify()
return _expr(y) | Expression negation operator
If *simplify* is ``True``, return a simplified expression. |
def _destroy(self):
"""Destruction code to decrement counters"""
self.unuse_region()
if self._rlist is not None:
# Actual client count, which doesn't include the reference kept by the manager, nor ours
# as we are about to be deleted
try:
if l... | Destruction code to decrement counters |
def _isomorphisms(q, g, check_varprops=True):
"""
Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300
"""
# convert MRSs to be more graph-like, and add some indices
qig = _IsoGraph(q, varprops=check_varprops) # qig = q isograph
gig = _IsoGraph(g, varprops=check_varprops) # gig = q... | Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300 |
def clear_callbacks(obj):
"""Remove all callbacks from an object."""
callbacks = obj._callbacks
if isinstance(callbacks, dllist):
# Help the garbage collector by clearing all links.
callbacks.clear()
obj._callbacks = None | Remove all callbacks from an object. |
def keep_sources(self, keep):
"""Keep only the specified sources in the decomposition.
"""
if self.unmixing_ is None or self.mixing_ is None:
raise RuntimeError("No sources available (run do_mvarica first)")
n_sources = self.mixing_.shape[0]
self.remove_sources(np.set... | Keep only the specified sources in the decomposition. |
def build_table(self, table, force=False):
"""Build all of the sources for a table """
sources = self._resolve_sources(None, [table])
for source in sources:
self.build_source(None, source, force=force)
self.unify_partitions() | Build all of the sources for a table |
def x10_unitcode(self):
"""Emit the X10 unit code."""
unitcode = None
if self.is_x10:
unitcode = insteonplm.utils.byte_to_unitcode(self.addr[2])
return unitcode | Emit the X10 unit code. |
def start_state_id(self, start_state_id, to_outcome=None):
"""Set the start state of the container state
See property
:param start_state_id: The state id of the state which should be executed first in the Container state
:raises exceptions.ValueError: if the start_state_id does not exi... | Set the start state of the container state
See property
:param start_state_id: The state id of the state which should be executed first in the Container state
:raises exceptions.ValueError: if the start_state_id does not exist in
:py:attr:`rafcon.core.states... |
def xml_report(self, file_path):
"""Generate and save XML report"""
self.logger.debug('Generating XML report')
report = self.zap.core.xmlreport()
self._write_report(report, file_path) | Generate and save XML report |
def print_status(total, current, start_time=None):
"""
Show how much work was done / how much work is remaining.
Parameters
----------
total : float
The total amount of work
current : float
The work that has been done so far
start_time : int
The start time in seconds... | Show how much work was done / how much work is remaining.
Parameters
----------
total : float
The total amount of work
current : float
The work that has been done so far
start_time : int
The start time in seconds since 1970 to estimate the remaining time. |
def Rzderiv(self,R,Z,phi=0.,t=0.):
"""
NAME:
Rzderiv
PURPOSE:
evaluate the mixed R,z derivative
INPUT:
R - Galactocentric radius (can be Quantity)
Z - vertical height (can be Quantity)
phi - Galactocentric azimuth (can be Quan... | NAME:
Rzderiv
PURPOSE:
evaluate the mixed R,z derivative
INPUT:
R - Galactocentric radius (can be Quantity)
Z - vertical height (can be Quantity)
phi - Galactocentric azimuth (can be Quantity)
t - time (can be Quantity)
O... |
def update_mode(arg_namespace):
"""Check command line arguments and run update function."""
try:
updater.update(custom_sources=arg_namespace.custom)
except (PermissionError, FileNotFoundError) as exception:
if isinstance(exception, PermissionError):
print('No write permission for... | Check command line arguments and run update function. |
def parse_args():
''' Parse the script arguments
'''
parser = optparse.OptionParser()
parser.add_option("-v", "--verbose", action="store_true")
mode_group = optparse.OptionGroup(parser, "Program Mode")
mode_group.add_option("-u", "--update-status", action="store_const",
dest="mode"... | Parse the script arguments |
def unpack_all(self, all_packed, devices):
"""
Args:
all_packed: K lists of packed gradients.
"""
all_grads = [] # #GPU x #Var
for dev, packed_grads_single_device in zip(devices, all_packed):
with tf.device(dev):
all_grads.append(self.unpa... | Args:
all_packed: K lists of packed gradients. |
def wait_for_element(self, timeout=None, message='', *args, **kwds):
"""
Shortcut for waiting for element. If it not ends with exception, it
returns that element. Detault timeout is `~.default_wait_timeout`.
Same as following:
.. code-block:: python
selenium.webdriv... | Shortcut for waiting for element. If it not ends with exception, it
returns that element. Detault timeout is `~.default_wait_timeout`.
Same as following:
.. code-block:: python
selenium.webdriver.support.wait.WebDriverWait(driver, timeout).until(lambda driver: driver.get_elm(...))
... |
def _get_cache_dates(self):
"""
Get s list of dates (:py:class:`datetime.datetime`) present in cache,
beginning with the longest contiguous set of dates that isn't missing
more than one date in series.
:return: list of datetime objects for contiguous dates in cache
:rtyp... | Get s list of dates (:py:class:`datetime.datetime`) present in cache,
beginning with the longest contiguous set of dates that isn't missing
more than one date in series.
:return: list of datetime objects for contiguous dates in cache
:rtype: ``list`` |
def compute_ranges(self, obj, key, ranges):
"""
Given an object, a specific key, and the normalization options,
this method will find the specified normalization options on
the appropriate OptionTree, group the elements according to
the selected normalization option (i.e. either ... | Given an object, a specific key, and the normalization options,
this method will find the specified normalization options on
the appropriate OptionTree, group the elements according to
the selected normalization option (i.e. either per frame or
over the whole animation) and finally compu... |
def set(self, name, value, **kw):
"""Set the field to the given value.
The keyword arguments represent the other field values
to integrate constraints to other values.
"""
# fetch the field by name
field = api.get_field(self.context, name)
# bail out if we have... | Set the field to the given value.
The keyword arguments represent the other field values
to integrate constraints to other values. |
def update_selection_sm_prior(self):
"""State machine prior update of tree selection"""
if self._do_selection_update:
return
self._do_selection_update = True
tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
if tree_sele... | State machine prior update of tree selection |
def _encode_codepage(codepage, text):
"""
Args:
codepage (int)
text (text)
Returns:
`bytes`
Encode text using the given code page. Will not fail if a char
can't be encoded using that codepage.
"""
assert isinstance(text, text_type)
if not text:
return b... | Args:
codepage (int)
text (text)
Returns:
`bytes`
Encode text using the given code page. Will not fail if a char
can't be encoded using that codepage. |
async def _replace(self, key: Text, data: Dict[Text, Any]) -> None:
"""
Replace the register with a new value.
"""
with await self.pool as r:
await r.set(self.register_key(key), ujson.dumps(data)) | Replace the register with a new value. |
def gui():
"""Main function"""
global SCREEN_SIZE
# #######
# setup all objects
# #######
os.environ['SDL_VIDEO_CENTERED'] = '1' # centers the windows
screen = new_screen()
pygame.display.set_caption('Empty project')
pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN])
... | Main function |
def file_exists(original_file):
"""
Validate the original file is in the S3 bucket
"""
s3 = boto3.resource('s3')
bucket_name, object_key = _parse_s3_file(original_file)
bucket = s3.Bucket(bucket_name)
bucket_iterator = bucket.objects.filter(Prefix=object_key)
bucket_list = [x for x in bu... | Validate the original file is in the S3 bucket |
def run_activity(self):
"""
runs the method that referenced from current task
"""
activity = self.current.activity
if activity:
if activity not in self.wf_activities:
self._load_activity(activity)
self.current.log.debug(
"Ca... | runs the method that referenced from current task |
def explode(self, vector=None, origin=None):
"""
Explode a scene around a point and vector.
Parameters
-----------
vector : (3,) float or float
Explode radially around a direction vector or spherically
origin : (3,) float
Point to explode around
... | Explode a scene around a point and vector.
Parameters
-----------
vector : (3,) float or float
Explode radially around a direction vector or spherically
origin : (3,) float
Point to explode around |
def _create_ec2_instance():
"""
Creates EC2 Instance
"""
print(_yellow("Creating instance"))
conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=fabconf['AWS_ACCESS_KEY'], aws_secret_access_key=fabconf['AWS_SECRET_KEY'])
image = conn.get_all_images(ec2_amis)
reservation = image... | Creates EC2 Instance |
def options(self, context, module_options):
'''
PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject into (default: current powershell process)
'''
if not 'PATH' in module_options:
context.log.error('PATH option is requir... | PATH Path to the file containing raw shellcode to inject
PROCID Process ID to inject into (default: current powershell process) |
def closest_point_naive(mesh, points):
"""
Given a mesh and a list of points find the closest point
on any triangle.
Does this by constructing a very large intermediate array and
comparing every point to every triangle.
Parameters
----------
mesh : Trimesh
Takes mesh to have same... | Given a mesh and a list of points find the closest point
on any triangle.
Does this by constructing a very large intermediate array and
comparing every point to every triangle.
Parameters
----------
mesh : Trimesh
Takes mesh to have same interfaces as `closest_point`
points : (m, 3) ... |
def read_data(archive, arc_type, day, stachans, length=86400):
"""
Function to read the appropriate data from an archive for a day.
:type archive: str
:param archive:
The archive source - if arc_type is seishub, this should be a url,
if the arc_type is FDSN then this can be either a url... | Function to read the appropriate data from an archive for a day.
:type archive: str
:param archive:
The archive source - if arc_type is seishub, this should be a url,
if the arc_type is FDSN then this can be either a url or a known obspy
client. If arc_type is day_vols, then this is th... |
def virtual_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory
'''
if p... | .. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory |
def model_actions(self):
""" Estimate state-value of the transition next state """
observations = self.get('rollout:observations')
model_action = self.model.action(observations)
return model_action | Estimate state-value of the transition next state |
def plot_doc_topic_heatmap(fig, ax, doc_topic_distrib, doc_labels, topic_labels=None,
which_documents=None, which_document_indices=None,
which_topics=None, which_topic_indices=None,
xaxislabel=None, yaxislabel=None,
... | Plot a heatmap for a document-topic distribution `doc_topic_distrib` to a matplotlib Figure `fig` and Axes `ax`
using `doc_labels` as document labels on the y-axis and topics from 1 to `n_topics=doc_topic_distrib.shape[1]` on
the x-axis.
Custom topic labels can be passed as `topic_labels`.
A subset of d... |
def parameter_from_numpy(self, name, array):
""" Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.glu... | Create parameter with its value initialized according to a numpy tensor
Parameters
----------
name : str
parameter name
array : np.ndarray
initiation value
Returns
-------
mxnet.gluon.parameter
a parameter object |
def create_container(self, image, name=None, **kwargs):
"""
Identical to :meth:`docker.api.container.ContainerApiMixin.create_container` with additional logging.
"""
name_str = " '{0}'".format(name) if name else ""
self.push_log("Creating container{0} from image '{1}'.".format(na... | Identical to :meth:`docker.api.container.ContainerApiMixin.create_container` with additional logging. |
def advance_dialog(self, *args):
"""Try to display the next dialog described in my ``todo``."""
self.clear_widgets()
try:
self._update_dialog(self.todo[self.idx])
except IndexError:
pass | Try to display the next dialog described in my ``todo``. |
def main():
"""Main"""
opts = dict(
name="clamavmirror",
version='0.0.4',
description="ClamAV Signature Mirroring Tool",
long_description=get_readme(),
keywords="clamav mirror mirroring mirror-tool signatures",
author="Andrew Colin Kissa",
author_email="a... | Main |
def AExn(mt, x, n):
""" AExn : Returns the EPV of a endowment insurance.
An endowment insurance provides a combination of a term insurance and a pure endowment
"""
return (mt.Mx[x] - mt.Mx[x + n]) / mt.Dx[x] + mt.Dx[x + n] / mt.Dx[x] | AExn : Returns the EPV of a endowment insurance.
An endowment insurance provides a combination of a term insurance and a pure endowment |
def plot_before_after_filter(signal, sr, band_begin, band_end, order=1, x_lim=[], y_lim=[],
orientation="hor", show_plot=False, file_name=None):
"""
-----
Brief
-----
The use of the current function is very useful for comparing two power spectrum's (before and
after ... | -----
Brief
-----
The use of the current function is very useful for comparing two power spectrum's (before and
after filtering the signal).
This function invokes "plot_informational_band" in order to get the power spectrum before
applying the signal to the lowpass filter.
-----------
D... |
async def _trigger_event(self, event, *args, **kwargs):
"""Invoke an event handler."""
run_async = kwargs.pop('run_async', False)
ret = None
if event in self.handlers:
if asyncio.iscoroutinefunction(self.handlers[event]) is True:
if run_async:
... | Invoke an event handler. |
def _onerror(cls, kmsg, result):
""" To execute on execution failure
:param kser.schemas.Message kmsg: Kafka message
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result
"""
logger.error(
"{}.Failed: ... | To execute on execution failure
:param kser.schemas.Message kmsg: Kafka message
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result |
def set_base_path(self, value):
"""Munge in the base path into the configuration values
:param str value: The path value
"""
if config.PATHS not in self.config.application:
self.config.application[config.PATHS] = dict()
if config.BASE not in self.config.application... | Munge in the base path into the configuration values
:param str value: The path value |
def range(self, start, end=None, step=1, numPartitions=None):
"""
Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param start: the sta... | Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param start: the start value
:param end: the end value (exclusive)
:param step: the in... |
def StdStringVector_2_seq(vec, seq=None):
"""Converts a :class:`tango.StdStringVector` to a python sequence<str>
:param seq: the :class:`tango.StdStringVector`
:type seq: :class:`tango.StdStringVector`
:param vec: (optional, default is None) a python sequence to be filled.
... | Converts a :class:`tango.StdStringVector` to a python sequence<str>
:param seq: the :class:`tango.StdStringVector`
:type seq: :class:`tango.StdStringVector`
:param vec: (optional, default is None) a python sequence to be filled.
If None is given, a new list is created
... |
def reverse(self):
"""
Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>.
"""
for key in si... | Reverse the order of all items in the dictionary.
Example:
omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
omd.reverse()
omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]
Returns: <self>. |
def sent_tokenize(self, text, **kwargs):
"""Returns a list of sentences.
Each sentence is a space-separated string of tokens (words).
Handles common cases of abbreviations (e.g., etc., ...).
Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence.
... | Returns a list of sentences.
Each sentence is a space-separated string of tokens (words).
Handles common cases of abbreviations (e.g., etc., ...).
Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence.
Headings without an ending period are inferred by ... |
def run_job(self, **kwds):
"""
Create a DRMAA job template, populate with specified properties,
run the job, and return the external_job_id.
"""
template = DrmaaSession.session.createJobTemplate()
try:
for key in kwds:
setattr(template, key, kw... | Create a DRMAA job template, populate with specified properties,
run the job, and return the external_job_id. |
def plotgwsrc(gwb):
"""
Plot a GWB source population as a mollweide projection.
"""
theta, phi, omega, polarization = gwb.gw_dist()
rho = phi-N.pi
eta = 0.5*N.pi - theta
# I don't know how to get rid of the RuntimeWarning -- RvH, Oct 10, 2014:
# /Users/vhaaster/env/dev/lib/python2.... | Plot a GWB source population as a mollweide projection. |
def could_be_unfinished_char(seq, encoding):
"""Whether seq bytes might create a char in encoding if more bytes were added"""
if decodable(seq, encoding):
return False # any sensible encoding surely doesn't require lookahead (right?)
# (if seq bytes encoding a character, adding another byte shou... | Whether seq bytes might create a char in encoding if more bytes were added |
async def set_chat_photo(self, chat_id: typing.Union[base.Integer, base.String],
photo: base.InputFile) -> base.Boolean:
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
The bot must be an administrator in the ch... | Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Adm... |
def sign_message(body: ByteString, secret: Text) -> Text:
"""
Compute a message's signature.
"""
return 'sha1={}'.format(
hmac.new(secret.encode(), body, sha1).hexdigest()
) | Compute a message's signature. |
def _notebook(trigger, note_store):
"""
:param trigger: trigger object
:param note_store: note_store object
:return: note object
"""
note = Types.Note()
if trigger.notebook:
# get the notebookGUID ...
notebook_id = EvernoteMgr.get_notebook(... | :param trigger: trigger object
:param note_store: note_store object
:return: note object |
def set_right_margin(self, right_margin):
"""
Set the right margin of the menu. This will determine the number of spaces between the right edge of the
screen and the right menu border.
:param right_margin: an integer value
"""
self.__header.style.margins.right = right_ma... | Set the right margin of the menu. This will determine the number of spaces between the right edge of the
screen and the right menu border.
:param right_margin: an integer value |
def in_array_list(array_list, a, tol=1e-5):
"""
Extremely efficient nd-array comparison using numpy's broadcasting. This
function checks if a particular array a, is present in a list of arrays.
It works for arrays of any size, e.g., even matrix searches.
Args:
array_list ([array]): A list o... | Extremely efficient nd-array comparison using numpy's broadcasting. This
function checks if a particular array a, is present in a list of arrays.
It works for arrays of any size, e.g., even matrix searches.
Args:
array_list ([array]): A list of arrays to compare to.
a (array): The test arra... |
def run(self, forever=True):
"""start the bot"""
loop = self.create_connection()
self.add_signal_handlers()
if forever:
loop.run_forever() | start the bot |
def get_genomic_seq_for_transcript(self, transcript_id, expand):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/sequence/id/{0}?type=genomic;expand_3prime={1};expand_5prime={1}".f... | obtain the sequence for a transcript from ensembl |
def do_access_control(self):
"""`before_request` handler to check if user should be redirected to
login page."""
from abilian.services import get_service
if current_app.testing and current_app.config.get("NO_LOGIN"):
# Special case for tests
user = User.query.get... | `before_request` handler to check if user should be redirected to
login page. |
def get_queryset(self):
'''
This is overwritten in order to not exclude drafts
and pages submitted for moderation
'''
request = self.request
# Allow pages to be filtered to a specific type
if 'type' not in request.GET:
model = Page
else:
... | This is overwritten in order to not exclude drafts
and pages submitted for moderation |
def _perform_validation(self, path, value, results):
"""
Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new ... | Validates a given value against the schema and configured validation rules.
:param path: a dot notation path to the value.
:param value: a value to be validated.
:param results: a list with validation results to add new results. |
def text(self, value):
"""Set the text value.
Args:
value (str): Text value.
"""
self._text = value
self.timestamps.edited = datetime.datetime.utcnow()
self.touch(True) | Set the text value.
Args:
value (str): Text value. |
def colormapper(value, lower=0, upper=1, cmap=None):
"""
Maps values to colors by normalizing within [a,b], obtaining rgba from the
given matplotlib color map for heatmap polygon coloring.
Parameters
----------
value: float
The value to be colormapped
lower: float
Lower boun... | Maps values to colors by normalizing within [a,b], obtaining rgba from the
given matplotlib color map for heatmap polygon coloring.
Parameters
----------
value: float
The value to be colormapped
lower: float
Lower bound of colors
upper: float
Upper bound of colors
cm... |
def _construct_as_path_attr(self, as_path_attr, as4_path_attr):
"""Marge AS_PATH and AS4_PATH attribute instances into
a single AS_PATH instance."""
def _listify(li):
"""Reconstruct AS_PATH list.
Example::
>>> _listify([[1, 2, 3], {4, 5}, [6, 7]])
... | Marge AS_PATH and AS4_PATH attribute instances into
a single AS_PATH instance. |
def determine_extra_packages(self, packages):
""" Return all packages that are installed, but missing from "packages".
Return value is a tuple of the package names """
args = [
"pip",
"freeze",
]
installed = subprocess.check_output(args, universal_new... | Return all packages that are installed, but missing from "packages".
Return value is a tuple of the package names |
def setup_exchange(self):
"""Declare the exchange
When completed, the on_exchange_declareok method will be invoked by pika.
"""
logger.debug('Declaring exchange %s', self._exchange)
self._channel.exchange_declare(self.on_exchange_declareok,
... | Declare the exchange
When completed, the on_exchange_declareok method will be invoked by pika. |
def is_visible(self):
"""
see also :meth:`visible_if`
:return: whether this parameter is currently visible (and
therefore shown in ParameterSets and visible to :meth:`ParameterSet.filter`)
:rtype: bool
"""
def is_visible_single(visible_if):
# visi... | see also :meth:`visible_if`
:return: whether this parameter is currently visible (and
therefore shown in ParameterSets and visible to :meth:`ParameterSet.filter`)
:rtype: bool |
def execute(self):
"""
Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None
"""
role_name = self._command_args['role_name']
role_directory = os.getcwd()
msg = 'Initializing new role {}...'.format(role_name)
... | Execute the actions necessary to perform a `molecule init role` and
returns None.
:return: None |
def add_edge_by_index(self, source_index: int, target_index: int,
weight: float, save_to_cache: bool = True) -> None:
"""
Adds an edge between the nodes with the specified indices to the graph.
Arguments:
source_index (int): The index of the source no... | Adds an edge between the nodes with the specified indices to the graph.
Arguments:
source_index (int): The index of the source node of the edge to add.
target_index (int): The index of the target node of the edge to add.
weight (float): The weight of the edge.
... |
def after(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If gi... | Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method w... |
def readWarp(self):
""" Read the warp element
::
<warp>
<axis name="weight">
<map input="0" output="0" />
<map input="500" output="200" />
<map input="1000" output="1000" />
</axis>
</war... | Read the warp element
::
<warp>
<axis name="weight">
<map input="0" output="0" />
<map input="500" output="200" />
<map input="1000" output="1000" />
</axis>
</warp> |
def get_instance(self, payload):
"""
Build an instance of TaskQueueRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance
:rtype: ... | Build an instance of TaskQueueRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_q... |
def parity(num: int) -> int:
"""Return the parity of a non-negative integer.
For example, here are the parities of the first ten integers:
>>> [parity(n) for n in range(10)]
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
This function is undefined for negative integers:
>>> parity(-1)
Traceback (most re... | Return the parity of a non-negative integer.
For example, here are the parities of the first ten integers:
>>> [parity(n) for n in range(10)]
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0]
This function is undefined for negative integers:
>>> parity(-1)
Traceback (most recent call last):
...
Val... |
def reset(cls, *args, **kwargs):
"""Undo call to prepare, useful for testing."""
cls.local.tchannel = None
cls.args = None
cls.kwargs = None
cls.prepared = False | Undo call to prepare, useful for testing. |
def get_events(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:issue_number/events <http://developer.github.com/v3/issues/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueEvent.IssueEvent`
"""
return github.PaginatedList.PaginatedList(
... | :calls: `GET /repos/:owner/:repo/issues/:issue_number/events <http://developer.github.com/v3/issues/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueEvent.IssueEvent` |
def rename_file(self, old_save_name, new_save_name, new_path):
"""This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else.
"""
if old_save_name in self._files:
del ... | This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else. |
def cmd_iter_no_block(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
show_jid=False,
verbose=False,
**kwargs):
'''
Yields the individual minion... | Yields the individual minion returns as they come in, or None
when no returns are available.
The function signature is the same as :py:meth:`cmd` with the
following exceptions.
:returns: A generator yielding the individual minion returns, or None
when no returns are ava... |
def set_preferences(self, user=None, **kwargs):
"""Set preferences from keyword arguments."""
if user is None:
user = current_user
d = {pref.key: pref for pref in user.preferences}
for k, v in kwargs.items():
if k in d:
d[k].value = v
... | Set preferences from keyword arguments. |
def spy(iterable, n=1):
"""Return a 2-tuple with a list containing the first *n* elements of
*iterable*, and an iterator with the same items as *iterable*.
This allows you to "look ahead" at the items in the iterable without
advancing it.
There is one item in the list by default:
>>> itera... | Return a 2-tuple with a list containing the first *n* elements of
*iterable*, and an iterator with the same items as *iterable*.
This allows you to "look ahead" at the items in the iterable without
advancing it.
There is one item in the list by default:
>>> iterable = 'abcdefg'
>>> hea... |
def getattrd(obj, name, default=sentinel):
"""
Same as getattr(), but allows dot notation lookup
Source: http://stackoverflow.com/a/14324459
"""
try:
return functools.reduce(getattr, name.split("."), obj)
except AttributeError as e:
if default is not sentinel:
return ... | Same as getattr(), but allows dot notation lookup
Source: http://stackoverflow.com/a/14324459 |
def submit(self, pixels, queue=None, debug=False, configfile=None):
"""
Submit the likelihood job for the given pixel(s).
"""
# For backwards compatibility
batch = self.config['scan'].get('batch',self.config['batch'])
queue = batch['cluster'] if queue is None else queue
... | Submit the likelihood job for the given pixel(s). |
def resample(self,N,minval=None,maxval=None,log=False,res=1e4):
"""Returns random samples generated according to the distribution
Mirrors basic functionality of `rvs` method for `scipy.stats`
random variates. Implemented by mapping uniform numbers onto the
inverse CDF using a closest-m... | Returns random samples generated according to the distribution
Mirrors basic functionality of `rvs` method for `scipy.stats`
random variates. Implemented by mapping uniform numbers onto the
inverse CDF using a closest-matching grid approach.
Parameters
----------
N : i... |
def skip(self, content):
"""
Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
... | Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
@rtype: bool |
def results(self, Pc):
r"""
"""
p_inv, t_inv = super().results(Pc).values()
phase = self.project.find_phase(self)
quantity = self.settings['quantity'].split('.')[-1]
lpf = np.array([1])
if self.settings['pore_partial_filling']:
# Set pressure on phase ... | r""" |
def incidence(boundary):
"""
given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib
"""
return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1]) | given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib |
def _get_no_rowscols(self, bbox):
"""Returns tuple of number of rows and cols from bbox"""
if bbox is None:
return 1, 1
else:
(bb_top, bb_left), (bb_bottom, bb_right) = bbox
if bb_top is None:
bb_top = 0
if bb_left is None:
... | Returns tuple of number of rows and cols from bbox |
def up(self, migration_id=None, fake=False):
"""Executes migrations."""
if not self.check_directory():
return
for migration in self.get_migrations_to_up(migration_id):
logger.info('Executing migration: %s' % migration.filename)
migration_module = self.load_m... | Executes migrations. |
def get(self, path, data=None):
"""Executes a GET.
'path' may not be None. Should include the full path to the
resource.
'data' may be None or a dictionary. These values will be
appended to the path as key/value pairs.
Returns a named tuple that includes:
statu... | Executes a GET.
'path' may not be None. Should include the full path to the
resource.
'data' may be None or a dictionary. These values will be
appended to the path as key/value pairs.
Returns a named tuple that includes:
status: the HTTP status code
json: the r... |
def validate_overlap(comp1, comp2, force):
"""Validate the overlap between the wavelength sets
of the two given components.
Parameters
----------
comp1, comp2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Source spectrum and bandpass of an observation.
... | Validate the overlap between the wavelength sets
of the two given components.
Parameters
----------
comp1, comp2 : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Source spectrum and bandpass of an observation.
force : {'extrap', 'taper', `None`}
If no... |
def get_collections(self, pattern="*", libtype="*"):
"""Returns a list of collection name/summary tuples"""
sql = """SELECT collection.collection_id, collection.name, collection.doc,
collection.type, collection.path
FROM collection_table as collection
... | Returns a list of collection name/summary tuples |
def _make_timestamps(start_time, minimum, maximum, steps):
"""Create timestamps on x-axis, every so often.
Parameters
----------
start_time : instance of datetime
actual start time of the dataset
minimum : int
start time of the recording from start_time, in s
maximum : int
... | Create timestamps on x-axis, every so often.
Parameters
----------
start_time : instance of datetime
actual start time of the dataset
minimum : int
start time of the recording from start_time, in s
maximum : int
end time of the recording from start_time, in s
steps : int... |
def validate_uuid_representation(dummy, value):
"""Validate the uuid representation option selected in the URI.
"""
try:
return _UUID_REPRESENTATIONS[value]
except KeyError:
raise ValueError("%s is an invalid UUID representation. "
"Must be one of "
... | Validate the uuid representation option selected in the URI. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.