code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def insert(self, database, key, value, callback=None):
"""
Insert an item into the given database.
:param database: The database into which to insert the value.
:type database: .BlobDatabaseID
:param key: The key to insert.
:type key: uuid.UUID
:param value: The ... | Insert an item into the given database.
:param database: The database into which to insert the value.
:type database: .BlobDatabaseID
:param key: The key to insert.
:type key: uuid.UUID
:param value: The value to insert.
:type value: bytes
:param callback: A call... |
def _check_build_input(self, image, args_path):
"""
Internal method, validate provided args.
:param image: str
:param args_path: str, path dir which is mounter inside container
:return: None
:raises RuntimeError
"""
try:
with open(os.path.join... | Internal method, validate provided args.
:param image: str
:param args_path: str, path dir which is mounter inside container
:return: None
:raises RuntimeError |
def set_fill_color(self,r,g=-1,b=-1):
"Set color for all filling operations"
if((r==0 and g==0 and b==0) or g==-1):
self.fill_color=sprintf('%.3f g',r/255.0)
else:
self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_colo... | Set color for all filling operations |
def commit(self, sourcedir, targetdir, abs_config, abs_sourcedir,
abs_targetdir):
"""
Commit project structure and configuration file
Args:
sourcedir (string): Source directory path.
targetdir (string): Compiled files target directory path.
abs... | Commit project structure and configuration file
Args:
sourcedir (string): Source directory path.
targetdir (string): Compiled files target directory path.
abs_config (string): Configuration file absolute path.
abs_sourcedir (string): ``sourcedir`` expanded as abs... |
def cred_def_id(issuer_did: str, schema_seq_no: int) -> str:
"""
Return credential definition identifier for input issuer DID and schema sequence number.
:param issuer_did: DID of credential definition issuer
:param schema_seq_no: schema sequence number
:return: credential definition identifier
... | Return credential definition identifier for input issuer DID and schema sequence number.
:param issuer_did: DID of credential definition issuer
:param schema_seq_no: schema sequence number
:return: credential definition identifier |
def clean_cache(cached, **kwargs):
" Generate cache key and clean cached value. "
if isinstance(cached, basestring):
cached = _str_to_model(cached)
cache_key = generate_cache_key(cached, **kwargs)
cache.delete(cache_key) | Generate cache key and clean cached value. |
def nEx(mt, x, n):
""" nEx : Returns the EPV of a pure endowment (deferred capital).
Pure endowment benefits are conditional on the survival of the policyholder. (v^n * npx) """
return mt.Dx[x + n] / mt.Dx[x] | nEx : Returns the EPV of a pure endowment (deferred capital).
Pure endowment benefits are conditional on the survival of the policyholder. (v^n * npx) |
def list_image(root, recursive, exts):
"""Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path
... | Traverses the root of directory that contains images and
generates image list iterator.
Parameters
----------
root: string
recursive: bool
exts: string
Returns
-------
image iterator that contains all the image under the specified path |
def _validate(instance):
"""Validate the internal representation of the instance."""
try:
_ = instance.schema.validate(instance.to_dict())
except ValidationError as ex:
raise ModelValidationError(
ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwarg... | Validate the internal representation of the instance. |
def preview(ident):
'''Preview an harvesting for a given source'''
source = get_source(ident)
cls = backends.get(current_app, source.backend)
max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']
backend = cls(source, dryrun=True, max_items=max_items)
return backend.harvest() | Preview an harvesting for a given source |
def current_custom_claims():
"""
This method returns any custom claims in the current jwt
"""
jwt_data = get_jwt_data_from_app_context()
return {k: v for (k, v) in jwt_data.items() if k not in RESERVED_CLAIMS} | This method returns any custom claims in the current jwt |
def clear_attendance(self):
"""
clear all attendance record
:return: bool
"""
command = const.CMD_CLEAR_ATTLOG
cmd_response = self.__send_command(command)
if cmd_response.get('status'):
return True
else:
raise ZKErrorResponse("Can'... | clear all attendance record
:return: bool |
def S(self):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
if self.data.day in (11, 12, 13): # Special case
return u'th'
last = self.data.day % 10
if last == 1:
return u'st'
if last == 2:
return u'nd'
if last == 3:
return u... | English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th |
def s3_connection(self):
"""
Connect to the Amazon S3 API.
If the connection attempt fails because Boto can't find credentials the
attempt is retried once with an anonymous connection.
Called on demand by :attr:`s3_bucket`.
:returns: A :class:`boto.s3.connection.S3Conn... | Connect to the Amazon S3 API.
If the connection attempt fails because Boto can't find credentials the
attempt is retried once with an anonymous connection.
Called on demand by :attr:`s3_bucket`.
:returns: A :class:`boto.s3.connection.S3Connection` object.
:raises: :exc:`.Cache... |
def _sigma_pi_hiE(self, Tp, a):
"""
General expression for Tp > 5 GeV (Eq 7)
"""
m_p = self._m_p
csip = (Tp - 3.0) / m_p
m1 = a[0] * csip ** a[3] * (1 + np.exp(-a[1] * csip ** a[4]))
m2 = 1 - np.exp(-a[2] * csip ** 0.25)
multip = m1 * m2
return sel... | General expression for Tp > 5 GeV (Eq 7) |
def _get_local_dirs(sub):
""" Get all the directories """
path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp")
dirs = path.split(",")
if len(dirs) > 1:
# different order in different processes and instances
rnd = random.Random(os.getpid() + id(dirs))
random.shuffle(dirs, rnd.random)... | Get all the directories |
def process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs):
''' Process a text file's content. If the file name ends with .gz, read it as gzip file '''
if mode not in ('rU', 'rt', 'rb', 'r'):
raise Exception("Invalid file reading mode")
with open(path, encoding=encoding, mode=mo... | Process a text file's content. If the file name ends with .gz, read it as gzip file |
def put(self, accountId):
"""Update an account"""
self.reqparse.add_argument('accountName', type=str, required=True)
self.reqparse.add_argument('accountType', type=str, required=True)
self.reqparse.add_argument('contacts', type=dict, required=True, action='append')
self.reqparse.... | Update an account |
def handle_user(self, data):
'''
Insert user informations in data
Override it to add extra user attributes.
'''
# Default to unauthenticated anonymous user
data['user'] = {
'username': '',
'is_authenticated': False,
'is_staff': False,
... | Insert user informations in data
Override it to add extra user attributes. |
def disable_cpu(self, rg):
'''
Disable cpus
rg: range or list of threads to disable
'''
if type(rg) == int:
rg= [rg]
to_disable= set(rg) & set(self.__get_ranges("online"))
for cpu in to_disable:
fpath = path.join("cpu%i"%cpu,"online")
... | Disable cpus
rg: range or list of threads to disable |
def write_script(self, script_name, contents, mode="t", *ignored):
"""Write an executable file to the scripts directory"""
from setuptools.command.easy_install import chmod, current_umask
log.info("Installing %s script to %s", script_name, self.install_dir)
target = os.path.join(self.ins... | Write an executable file to the scripts directory |
def binary_annotation_list_builder(binary_annotations, host):
"""
Reformat binary annotations dict to return list of zipkin_core objects. The
value of the binary annotations MUST be in string format.
:param binary_annotations: dict with key, value being the name and value
... | Reformat binary annotations dict to return list of zipkin_core objects. The
value of the binary annotations MUST be in string format.
:param binary_annotations: dict with key, value being the name and value
of the binary annotation being logged.
:type host: :class:`zipkin_cor... |
def avi(self, path, filtered=True, override=False):
"""Exports filtered event images to an avi file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
filtered: bool
If set to `True`, only the filtered data (index... | Exports filtered event images to an avi file
Parameters
----------
path: str
Path to a .tsv file. The ending .tsv is added automatically.
filtered: bool
If set to `True`, only the filtered data (index in ds._filter)
are used.
override: bool
... |
def jsonise(dic):
"""Renvoie un dictionnaire dont les champs dont compatibles avec SQL
Utilise Json. Attention à None : il faut laisser None et non pas null"""
d = {}
for k, v in dic.items():
if type(v) in abstractRequetesSQL.TYPES_PERMIS:
d[k] = v
... | Renvoie un dictionnaire dont les champs dont compatibles avec SQL
Utilise Json. Attention à None : il faut laisser None et non pas null |
def install(path, restart=False):
'''
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.... | Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``
will add ... |
def consume_file(self, filename):
"""Counts all kmers in all sequences in a FASTA/FASTQ file."""
with screed.open(filename) as sequences:
for seq in sequences:
self.consume(seq['sequence']) | Counts all kmers in all sequences in a FASTA/FASTQ file. |
def and_(*fs):
"""Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments
"""... | Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments |
def get_suggested_filename(metadata):
"""Generate a filename for a song based on metadata.
Parameters:
metadata (dict): A metadata dict.
Returns:
A filename.
"""
if metadata.get('title') and metadata.get('track_number'):
suggested_filename = '{track_number:0>2} {title}'.format(**metadata)
elif metadata.g... | Generate a filename for a song based on metadata.
Parameters:
metadata (dict): A metadata dict.
Returns:
A filename. |
def to_dict(self, split_structs_bit=False):
""" Converts prefeters to a dictionary.
Children Pref can be optionally separated """
pref_dict = {}
struct_dict = {}
for (key, val) in six.iteritems(self):
if split_structs_bit and isinstance(val, Pref):
str... | Converts prefeters to a dictionary.
Children Pref can be optionally separated |
def py_doc_trim(docstring):
"""Trim a python doc string.
This example is nipped from https://www.python.org/dev/peps/pep-0257/,
which describes how to conventionally format and trim docstrings.
It has been modified to replace single newlines with a space, but leave
multiple consecutive newlines in... | Trim a python doc string.
This example is nipped from https://www.python.org/dev/peps/pep-0257/,
which describes how to conventionally format and trim docstrings.
It has been modified to replace single newlines with a space, but leave
multiple consecutive newlines in tact. |
def remove_role(self, groups=None, role_type=RoleTypes.admin):
"""
Remove user from a role (typically admin) of some groups.
:param groups: list of group names the user should NOT have this role for
:param role_type: the type of role (defaults to "admin")
:return: the User, so yo... | Remove user from a role (typically admin) of some groups.
:param groups: list of group names the user should NOT have this role for
:param role_type: the type of role (defaults to "admin")
:return: the User, so you can do User(...).remove_role(...).remove_from_groups(...) |
def exists(self):
"""Check whether the instance already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_instance_exists]
:end-before: [END bigtable_check_instance_exists]
:rtype: bool
:returns: True if the table ... | Check whether the instance already exists.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_check_instance_exists]
:end-before: [END bigtable_check_instance_exists]
:rtype: bool
:returns: True if the table exists, else False. |
def _destroy(self, target_position_groups):
"""Destroy indicated position groups, handle any chain destructions,
and return all destroyed groups."""
target_position_groups = list(target_position_groups) # work on a copy
destroyed_tile_groups = list()
blank = Tile.singleton('.')
... | Destroy indicated position groups, handle any chain destructions,
and return all destroyed groups. |
def frames_to_ms(frames, fps):
"""
Convert frame-based duration to milliseconds.
Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of milliseconds (rounded to int).
Raises:
V... | Convert frame-based duration to milliseconds.
Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of milliseconds (rounded to int).
Raises:
ValueError: fps was negative or zero. |
def id2rel(self, xs):
"""Map id(s) to relation(s)
Parameters
----------
xs : int
id or a list of ids
Returns
-------
str or list
relation or a list of relations
"""
if isinstance(xs, list):
return [self._id2rel... | Map id(s) to relation(s)
Parameters
----------
xs : int
id or a list of ids
Returns
-------
str or list
relation or a list of relations |
def _start_retransmission(self, transaction, message):
"""
Start the retransmission task.
:type transaction: Transaction
:param transaction: the transaction that owns the message that needs retransmission
:type message: Message
:param message: the message that needs the ... | Start the retransmission task.
:type transaction: Transaction
:param transaction: the transaction that owns the message that needs retransmission
:type message: Message
:param message: the message that needs the retransmission task |
def _next_of_kin(self, pos):
"""
looks up the next sibling of the closest ancestor with not-None next
siblings.
"""
candidate = None
parent = self.parent_position(pos)
if parent is not None:
candidate = self.next_sibling_position(parent)
if... | looks up the next sibling of the closest ancestor with not-None next
siblings. |
def from_mask_and_sub_grid_size(cls, mask, sub_grid_size=1):
"""Setup a sub-grid of the unmasked pixels, using a mask and a specified sub-grid size. The center of \
every unmasked pixel's sub-pixels give the grid's (y,x) arc-second coordinates.
Parameters
-----------
mask : Mask... | Setup a sub-grid of the unmasked pixels, using a mask and a specified sub-grid size. The center of \
every unmasked pixel's sub-pixels give the grid's (y,x) arc-second coordinates.
Parameters
-----------
mask : Mask
The mask whose masked pixels are used to setup the sub-pixe... |
def download(self, url):
"""
Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage
"""
try:
yt = YouTube(url)
except Rege... | Downloads a MP4 or WebM file that is associated with the video at the URL passed.
:param str url: URL of the video to be downloaded
:return str: Filename of the file in local storage |
def fix_e225(self, result):
"""Fix missing whitespace around operator."""
target = self.source[result['line'] - 1]
offset = result['column'] - 1
fixed = target[:offset] + ' ' + target[offset:]
# Only proceed if non-whitespace characters match.
# And make sure we don't br... | Fix missing whitespace around operator. |
def extend(ol,nl,**kwargs):
'''
from elist.elist import *
ol = [1,2,3,4]
nl = [5,6,7,8]
id(ol)
extend(ol,nl,mode="original")
ol
id(ol)
####
ol = [1,2,3,4]
nl = [5,6,7,8]
id(ol)
new = extend(ol,nl)
new
id(... | from elist.elist import *
ol = [1,2,3,4]
nl = [5,6,7,8]
id(ol)
extend(ol,nl,mode="original")
ol
id(ol)
####
ol = [1,2,3,4]
nl = [5,6,7,8]
id(ol)
new = extend(ol,nl)
new
id(new) |
def get(self, session, discount_id=None, ext_fields=None):
'''taobao.fenxiao.discounts.get 获取折扣信息
查询折扣信息'''
request = TOPRequest('taobao.fenxiao.discounts.get')
if discount_id!=None: request['discount_id'] = discount_id
if ext_fields!=None: request['ext_fields'] = ext_fi... | taobao.fenxiao.discounts.get 获取折扣信息
查询折扣信息 |
def get_maximum_range(self, hmm):
'''
If no maximum range has been specified, and if using a hmm search, a
maximum range can be determined by using the length of the HMM
Parameters
----------
hmm : str
path to hmm profile
Returns
-------
... | If no maximum range has been specified, and if using a hmm search, a
maximum range can be determined by using the length of the HMM
Parameters
----------
hmm : str
path to hmm profile
Returns
-------
Length to search to when linking hits on a single ... |
def _write_line(self, indent_string, entry, this_entry, comment):
"""Write an individual line, for the write method"""
# NOTE: the calls to self._quote here handles non-StringType values.
if not self.unrepr:
val = self._decode_element(self._quote(this_entry))
else:
... | Write an individual line, for the write method |
def main(doc, tool, dispatch_only=None):
"""gcdt tools parametrized main function to initiate gcdt lifecycle.
:param doc: docopt string
:param tool: gcdt tool (gcdt, kumo, tenkai, ramuda, yugen)
:param dispatch_only: list of commands which do not use gcdt lifecycle
:return: exit_code
"""
# ... | gcdt tools parametrized main function to initiate gcdt lifecycle.
:param doc: docopt string
:param tool: gcdt tool (gcdt, kumo, tenkai, ramuda, yugen)
:param dispatch_only: list of commands which do not use gcdt lifecycle
:return: exit_code |
def differentiate(self, n=1):
"""
n-th derivative, default 1.
"""
ak = self.coefficients()
a_, b_ = self.domain()
for _ in range(n):
ak = self.differentiator(ak)
return self.from_coeff((2./(b_-a_))**n*ak, domain=self.domain()) | n-th derivative, default 1. |
def user_registries(fs0, fs1):
"""Returns the list of user registries present on both FileSystems."""
for user in fs0.ls('{}Users'.format(fs0.fsroot)):
for path in user_registries_path(fs0.fsroot, user):
if fs1.exists(path):
yield path | Returns the list of user registries present on both FileSystems. |
def _transform_chrom(chrom):
"""Helper function to obtain specific sort order."""
try:
c = int(chrom)
except:
if chrom in ['X', 'Y']:
return chrom
elif chrom == 'MT':
return '_MT' # sort to the end
else:
return '__' + chrom # sort to the v... | Helper function to obtain specific sort order. |
def _notify_change(self):
"""
Notify user from external change if autoReloadChangedFiles is False
then reload the changed file in the editor
"""
def inner_action(*args):
""" Inner action: open file """
# cache cursor position before reloading so that the c... | Notify user from external change if autoReloadChangedFiles is False
then reload the changed file in the editor |
def runQuery(self, *args, **kwargs):
"""
Execute an SQL query and return the result.
:param args: additional positional arguments to be passed to cursor execute method
:param kwargs: keyword arguments to be passed to cursor execute method
:return: <defer>
"""
try... | Execute an SQL query and return the result.
:param args: additional positional arguments to be passed to cursor execute method
:param kwargs: keyword arguments to be passed to cursor execute method
:return: <defer> |
def summary(self):
"""Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : DataFrame
Contains columns coef, np.exp(coef), se(coef), z, p, lower, upper"""
ci = 1 - self.alpha
with np.errstate(inva... | Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : DataFrame
Contains columns coef, np.exp(coef), se(coef), z, p, lower, upper |
def inverse(self):
r"""Return the pseudo-inverse filter bank.
The pseudo-inverse of the *analysis filter bank* :math:`g` is the
*synthesis filter bank* :math:`g^+` such that
.. math:: g(L)^+ g(L) = I,
where :math:`I` is the identity matrix, and the *synthesis operator*
... | r"""Return the pseudo-inverse filter bank.
The pseudo-inverse of the *analysis filter bank* :math:`g` is the
*synthesis filter bank* :math:`g^+` such that
.. math:: g(L)^+ g(L) = I,
where :math:`I` is the identity matrix, and the *synthesis operator*
.. math:: g(L)^+ = (g(L)\... |
def register(self, src, trg, trg_mask=None, src_mask=None):
""" Implementation of pair-wise registration and warping using Enhanced Correlation Coefficient
This function estimates an Euclidean transformation (x,y translation + rotation) using the intensities of the
pair of images to be register... | Implementation of pair-wise registration and warping using Enhanced Correlation Coefficient
This function estimates an Euclidean transformation (x,y translation + rotation) using the intensities of the
pair of images to be registered. The similarity metric is a modification of the cross-correlation met... |
def transitions(self, current=True):
"""
Returns available transitions for the current state, as a dictionary of
name: :class:`StateTransitionWrapper`.
:param bool current: Limit to transitions available in ``obj.``
:meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access`
... | Returns available transitions for the current state, as a dictionary of
name: :class:`StateTransitionWrapper`.
:param bool current: Limit to transitions available in ``obj.``
:meth:`~coaster.sqlalchemy.mixins.RoleMixin.current_access` |
def addRNAQuantification(self, datafields):
"""
Adds an RNAQuantification to the db. Datafields is a tuple in the
order:
id, feature_set_ids, description, name,
read_group_ids, programs, biosample_id
"""
self._rnaValueList.append(datafields)
if len(self._... | Adds an RNAQuantification to the db. Datafields is a tuple in the
order:
id, feature_set_ids, description, name,
read_group_ids, programs, biosample_id |
def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False):
"""Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param meth... | Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default G... |
def clean(self, *args, **kwargs):
""" validation """
self._validate_backend()
self._validate_config()
self._validate_netengine()
self._validate_duplicates() | validation |
def check_required_fields(method, uri, body, field_names):
"""
Check required fields in the request body.
Raises:
BadRequestError with reason 3: Missing request body
BadRequestError with reason 5: Missing required field in request body
"""
# Check presence of request body
if body i... | Check required fields in the request body.
Raises:
BadRequestError with reason 3: Missing request body
BadRequestError with reason 5: Missing required field in request body |
def get_pepproteins(line):
"""Returns from a PSM line peptide sequence,
and other information about the PSM.
Return values:
psm_id - str
proteins - list of str
"""
psm_id = get_psm_id(line)
proteins = get_proteins_from_psm(line)
return psm_id, proteins | Returns from a PSM line peptide sequence,
and other information about the PSM.
Return values:
psm_id - str
proteins - list of str |
def _interp_total_size(interp):
"""
Compute total load size of interpreter.
:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int
"""
load_segs = [x for x in interp.iter_segments() if x.header.p_type == 'PT_LO... | Compute total load size of interpreter.
:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int |
def _PPIGuessPayloadClass(p, **kargs):
""" This function tells the PacketListField how it should extract the
TLVs from the payload. We pass cls only the length string
pfh_len says it needs. If a payload is returned, that means
part of the sting was unused. This converts to a Raw layer... | This function tells the PacketListField how it should extract the
TLVs from the payload. We pass cls only the length string
pfh_len says it needs. If a payload is returned, that means
part of the sting was unused. This converts to a Raw layer, and
the remainder of p is added as Ra... |
def browse(self, wait=True, tempname="/tmp/seltable"):
""" Browse a table using casabrowser or a simple wxwidget
based browser.
By default the casabrowser is used if it can be found (in your PATH).
Otherwise the wxwidget one is used if wx can be loaded.
The casabrowser can only... | Browse a table using casabrowser or a simple wxwidget
based browser.
By default the casabrowser is used if it can be found (in your PATH).
Otherwise the wxwidget one is used if wx can be loaded.
The casabrowser can only browse tables that are persistent on disk.
This gives prob... |
def clear_caches(self):
""" Clears the Caches for all model elements """
for element_name in dir(self.components):
element = getattr(self.components, element_name)
if hasattr(element, 'cache_val'):
delattr(element, 'cache_val') | Clears the Caches for all model elements |
def validate_signature_fragments(
fragments,
hash_,
public_key,
sponge_type=Kerl,
):
# type: (Sequence[TryteString], Hash, TryteString, type) -> bool
"""
Returns whether a sequence of signature fragments is valid.
:param fragments:
Sequence of signature fragments (... | Returns whether a sequence of signature fragments is valid.
:param fragments:
Sequence of signature fragments (usually
:py:class:`iota.transaction.Fragment` instances).
:param hash_:
Hash used to generate the signature fragments (usually a
:py:class:`iota.transaction.BundleHash` instan... |
def setCurrentAction(self, action):
"""
Sets the current action for this button to the inputed action.
:param action | <QAction> || <str>
"""
self._actionGroup.blockSignals(True)
for act in self._actionGroup.actions():
act.setChecked(act ... | Sets the current action for this button to the inputed action.
:param action | <QAction> || <str> |
def match_handle(loc, tokens):
"""Process match blocks."""
if len(tokens) == 4:
matches, match_type, item, stmts = tokens
cond = None
elif len(tokens) == 5:
matches, match_type, item, cond, stmts = tokens
else:
raise CoconutInternalException("invalid match statement token... | Process match blocks. |
def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
config: Pull the data from the system configuration file
instead of the live data.
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
ret = {}
if config_file:
# If the ... | Return a list of sysctl parameters for this minion
config: Pull the data from the system configuration file
instead of the live data.
CLI Example:
.. code-block:: bash
salt '*' sysctl.show |
def insert_unique(self, table_name, data, unique_fields=None, *, raise_if_found=False):
"""Insert `data` into `table` ensuring that data has unique values
in `table` for the fields listed in `unique_fields`.
If `raise_if_found` is True, will raise an NotUniqueItemError if
another item w... | Insert `data` into `table` ensuring that data has unique values
in `table` for the fields listed in `unique_fields`.
If `raise_if_found` is True, will raise an NotUniqueItemError if
another item with the same `unique_fields` values are found
previously in `table`.
If False, will... |
def filterResults(results, filter):
"""
Filter results containing the given condition
:param results: list of experiments returned by `suite.get_exps`
:param filter: list of conditions on the experiment parameters. For example:
["dropout0.0", "dropout0.50"]
:return: filtered results
"""
r... | Filter results containing the given condition
:param results: list of experiments returned by `suite.get_exps`
:param filter: list of conditions on the experiment parameters. For example:
["dropout0.0", "dropout0.50"]
:return: filtered results |
def get_build_params(metadata):
'''get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build
:param metadata: a list, each item a dictionary of metadata, in format:
metadata = [{'key': 'repo_url', 'value': repo_url },
{'key': 'repo_id', 'value': repo_id ... | get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build
:param metadata: a list, each item a dictionary of metadata, in format:
metadata = [{'key': 'repo_url', 'value': repo_url },
{'key': 'repo_id', 'value': repo_id },
{'key': 'credential'... |
def from_scene_coords(self, x=0, y=0):
"""Converts x, y given in the scene coordinates to sprite's local ones
coordinates"""
matrix = self.get_matrix()
matrix.invert()
return matrix.transform_point(x, y) | Converts x, y given in the scene coordinates to sprite's local ones
coordinates |
def get_same_container_repos(app_or_library_name):
"""Given the name of an app or library, returns all repos that are guaranteed
to live in the same container"""
specs = get_expanded_libs_specs()
spec = specs.get_app_or_lib(app_or_library_name)
return get_same_container_repos_from_spec(spec) | Given the name of an app or library, returns all repos that are guaranteed
to live in the same container |
def make_postcard(self, npix=300, shape=(1070, 1132), buffer_size=15):
"""
Develop a "postcard" region around the target star.
Other stars in this postcard will be used as possible reference stars.
Args:
npix: The size of the postcard region. The region will be a sq... | Develop a "postcard" region around the target star.
Other stars in this postcard will be used as possible reference stars.
Args:
npix: The size of the postcard region. The region will be a square with sides npix pixels
(default: ``300``)
shape: The size ... |
def universal_transformer_basic(layer_inputs,
step, hparams,
ffn_unit,
attention_unit):
"""Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layer... | Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layers. For some tasks, this simple idea brings a
generalization that is not achievable by playing with the size of the model
or drop_out parameters in the vanilla transformer.
Args:
... |
def mask_by_ind(self, inds):
"""Create a new image by zeroing out data at locations not in the
given indices.
Parameters
----------
inds : :obj:`numpy.ndarray` of int
A 2D ndarray whose first entry is the list of row indices
and whose second entry is the ... | Create a new image by zeroing out data at locations not in the
given indices.
Parameters
----------
inds : :obj:`numpy.ndarray` of int
A 2D ndarray whose first entry is the list of row indices
and whose second entry is the list of column indices.
The ... |
def parse_columns(lines):
"""Parse list of lines with columns description from SOFT file.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Columns description.
"""
data = []
index = []
for line in lines:
line = line.rstrip()... | Parse list of lines with columns description from SOFT file.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Columns description. |
def _get_customjs(self, change, p_name):
"""
Returns a CustomJS callback that can be attached to send the
widget state across the notebook comms.
"""
data_template = "data = {{p_name: '{p_name}', value: cb_obj['{change}']}};"
fetch_data = data_template.format(change=chang... | Returns a CustomJS callback that can be attached to send the
widget state across the notebook comms. |
def convert_videos_to_summaries(input_videos, output_videos, target_videos,
tag, decode_hparams,
display_ground_truth=False):
"""Converts input, output and target videos into video summaries.
Args:
input_videos: 5-D NumPy array, (NTHWC) conditioni... | Converts input, output and target videos into video summaries.
Args:
input_videos: 5-D NumPy array, (NTHWC) conditioning frames.
output_videos: 5-D NumPy array, (NTHWC) model predictions.
target_videos: 5-D NumPy array, (NTHWC) target frames.
tag: tf summary tag.
decode_hparams: HParams.
disp... |
def take_until(condition):
"""
>>> [1, 4, 6, 4, 1] > take_until(X > 5) | list
[1, 4]
>>> [1, 4, 6, 4, 1] > take_until(X > 5).including | list
[1, 4, 6]
"""
f = partial(takewhile, pipe | condition | operator.not_)
f.attrs = {'including': take_until_including(condition)}
return f | >>> [1, 4, 6, 4, 1] > take_until(X > 5) | list
[1, 4]
>>> [1, 4, 6, 4, 1] > take_until(X > 5).including | list
[1, 4, 6] |
def main():
"""
GATK germline pipeline with variant filtering and annotation.
"""
# Define Parser object and add to jobTree
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
# Generate subparsers
subparsers = parser.add_subparsers(dest='com... | GATK germline pipeline with variant filtering and annotation. |
def _get_mid_and_update_msg(self, msg, use_mid):
"""Get message ID for current request and assign to msg.mid if needed.
Parameters
----------
msg : katcp.Message ?request message
use_mid : bool or None
If msg.mid is None, a new message ID will be created. msg.mid will b... | Get message ID for current request and assign to msg.mid if needed.
Parameters
----------
msg : katcp.Message ?request message
use_mid : bool or None
If msg.mid is None, a new message ID will be created. msg.mid will be
filled with this ID if use_mid is True or if use_m... |
def std(data, channels=None):
"""
Calculate the standard deviation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or ... | Calculate the standard deviation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optiona... |
def parameter_struct_dict(self):
"""Dictionary containing PyAtomData structs for the force field."""
if self._parameter_struct_dict is None:
self._parameter_struct_dict = self._make_ff_params_dict()
elif self.auto_update_f_params:
new_hash = hash(
tuple([t... | Dictionary containing PyAtomData structs for the force field. |
def resultsFor( self, ps ):
"""Retrieve a list of all results associated with the given parameters.
:param ps: the parameters
:returns: a list of results, which may be empty"""
k = self._parametersAsIndex(ps)
if k in self._results.keys():
# filter out pending job ids... | Retrieve a list of all results associated with the given parameters.
:param ps: the parameters
:returns: a list of results, which may be empty |
def query(self, variables, evidence=None, elimination_order=None, joint=True):
"""
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
... | Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
elimination_order: list
order of variable elim... |
def run(self,
job_name,
handler_spec,
input_reader_spec,
output_writer_spec=None,
params=None,
shards=None,
base_path=None):
"""Start a mapreduce job.
Args:
job_name: mapreduce name. Only for display purpose.
handler_spec: fully ... | Start a mapreduce job.
Args:
job_name: mapreduce name. Only for display purpose.
handler_spec: fully qualified name to your map function/class.
input_reader_spec: fully qualified name to input reader class.
output_writer_spec: fully qualified name to output writer class.
params: a dic... |
def getProfileInfo(exp):
"""
Prints profiling information.
Parameters:
----------------------------
@param reset (bool)
If set to True, the profiling will be reset.
"""
totalTime = 0.000001
for region in exp.network.regions.values():
timer = region.getComputeTimer()
totalTime += ... | Prints profiling information.
Parameters:
----------------------------
@param reset (bool)
If set to True, the profiling will be reset. |
def main(args=[], prog_name=sys.argv[0]):
"""Figure out which of the two options was used (build, get) and dispatch.
:param args: the arguments for this script, as a list of string. Should
already have had the script name stripped, so we expect the
first item in this li... | Figure out which of the two options was used (build, get) and dispatch.
:param args: the arguments for this script, as a list of string. Should
already have had the script name stripped, so we expect the
first item in this list to specify the mode ('build' an
... |
def cbpdnmd_ystep(k):
"""Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
if mp_W.shape[0] > 1:
W = mp_W[k]
else:
W = mp_W
AXU0 = mp_DX[k] - mp_S[k] + mp_Z... | Do the Y step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. |
def euclidean(a, b):
"""
Euclidean distance between vectors a and b.
Parameters
------------
a : (n,) float
First vector
b : (n,) float
Second vector
Returns
------------
distance : float
Euclidean distance between A and B
"""
a = np.asanyarray(a, dtyp... | Euclidean distance between vectors a and b.
Parameters
------------
a : (n,) float
First vector
b : (n,) float
Second vector
Returns
------------
distance : float
Euclidean distance between A and B |
def make_links(self):
"""
Create symbolic links to the output files produced by the other tasks.
.. warning::
This method should be called only when the calculation is READY because
it uses a heuristic approach to find the file to link.
"""
for dep in se... | Create symbolic links to the output files produced by the other tasks.
.. warning::
This method should be called only when the calculation is READY because
it uses a heuristic approach to find the file to link. |
def _merge_before_set(self, key, existing, value, is_secret):
"""Merge the new value being set with the existing value before set"""
def _log_before_merging(_value):
self.logger.debug(
"Merging existing %s: %s with new: %s", key, existing, _value
)
def _... | Merge the new value being set with the existing value before set |
def from_dict(d):
"""Transform the dict to a response object and return the response."""
warnings_ = d.get('warnings', [])
query = d.get('query') or None
if query:
query = Person.from_dict(query)
person = d.get('person') or None
if person:
... | Transform the dict to a response object and return the response. |
def show_buff(self, pos):
"""
Return the display of the instruction
:rtype: string
"""
buff = self.get_name() + " "
buff += "%x:" % self.first_key
for i in self.targets:
buff += " %x" % i
return buff | Return the display of the instruction
:rtype: string |
def dynamic_instantiate_middleware(name, args, expand=None):
"""Import a class and instantiate with custom args.
Example:
name = "my.module.Foo"
args_dict = {
"bar": 42,
"baz": "qux"
}
=>
from my.module import Foo
return Foo(bar=42, ba... | Import a class and instantiate with custom args.
Example:
name = "my.module.Foo"
args_dict = {
"bar": 42,
"baz": "qux"
}
=>
from my.module import Foo
return Foo(bar=42, baz="qux") |
def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None):
"""
Check if database contains any tables.
:param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument
is a boolean flag specifying if t... | Check if database contains any tables.
:param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument
is a boolean flag specifying if the database is empty or not
:param failHandler: <function(<str>)> method called if int... |
def needed(name, required):
"""
RETURN SUBSET IF name IN REQUIRED
"""
return [
relative_field(r, name) if r and startswith_field(r, name) else None
for r in required
] | RETURN SUBSET IF name IN REQUIRED |
def status(self, core=None):
"""http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953"""
params = {
'action': 'STATUS',
}
if core is not None:
params.update(core=core)
return self._get_url(self.url, params=params) | http://wiki.apache.org/solr/CoreAdmin#head-9be76f5a459882c5c093a7a1456e98bea7723953 |
def copytree(self, dest_dir, src=None, newname=None,
exclude=None, overwrite=False):
"""
Copy this directory or just one contained object into another
directory.
Parameters
----------
dest_dir : string or Directory
The destination directory.... | Copy this directory or just one contained object into another
directory.
Parameters
----------
dest_dir : string or Directory
The destination directory.
src : string, optional (default=None)
If ``src`` is None then this entire directory is copied recurs... |
def __get_values(self):
"""Retrieve value information either via describe or point value listing. MUST be called within lock."""
values = []
if self.__remote:
description = self.__client.describe(self.__point)
if description is not None:
if description['t... | Retrieve value information either via describe or point value listing. MUST be called within lock. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.