code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def __add_parameter(self, param, path_parameters, params):
"""Adds all parameters in a field to a method parameters descriptor.
Simple fields will only have one parameter, but a message field 'x' that
corresponds to a message class with fields 'y' and 'z' will result in
parameters 'x.y' and 'x.z', for ... | Adds all parameters in a field to a method parameters descriptor.
Simple fields will only have one parameter, but a message field 'x' that
corresponds to a message class with fields 'y' and 'z' will result in
parameters 'x.y' and 'x.z', for example. The mapping from field to
parameters is mostly handle... |
def site_config_dirs(appname):
"""Return a list of potential user-shared config dirs for this application.
"appname" is the name of application.
Typical user config directories are:
Mac OS X: /Library/Application Support/<AppName>/
Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ f... | Return a list of potential user-shared config dirs for this application.
"appname" is the name of application.
Typical user config directories are:
Mac OS X: /Library/Application Support/<AppName>/
Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ for each value in
$... |
def chdir(self, dir, change_os_dir=0):
"""Change the current working directory for lookups.
If change_os_dir is true, we will also change the "real" cwd
to match.
"""
curr=self._cwd
try:
if dir is not None:
self._cwd = dir
if ch... | Change the current working directory for lookups.
If change_os_dir is true, we will also change the "real" cwd
to match. |
def get_urls(self, order="total_clicks desc", offset=None, count=None):
"""Returns a list of URLs you've included in messages.
List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items.
"""
req_data = [ None, orde... | Returns a list of URLs you've included in messages.
List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items. |
def _open(filename, mode='r', buffering=0):
"""read only version of open()"""
if mode not in ('r', 'rb', 'rU'):
raise RuntimeError("Invalid open file mode, must be 'r', 'rb', or 'rU'")
if buffering > MAX_OPEN_BUFFER:
raise RuntimeError("Invalid buffering value, max buffer size is {}".format(... | read only version of open() |
def fingerprint(txt):
"""
takes a string and truncates to standard form for data matching.
Based on the spec at OpenRefine
https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint
- remove leading and trailing whitespace
- change all characters to their lowercase representation
- remo... | takes a string and truncates to standard form for data matching.
Based on the spec at OpenRefine
https://github.com/OpenRefine/OpenRefine/wiki/Clustering-In-Depth#fingerprint
- remove leading and trailing whitespace
- change all characters to their lowercase representation
- remove all punctuation and control... |
def wheregreater(self, fieldname, value):
"""
Returns a new DataTable with rows only where the value at
`fieldname` > `value`.
"""
return self.mask([elem > value for elem in self[fieldname]]) | Returns a new DataTable with rows only where the value at
`fieldname` > `value`. |
def send_audio_packet(self, data, *, encode=True):
"""Sends an audio packet composed of the data.
You must be connected to play audio.
Parameters
----------
data: bytes
The :term:`py:bytes-like object` denoting PCM or Opus voice data.
encode: bool
... | Sends an audio packet composed of the data.
You must be connected to play audio.
Parameters
----------
data: bytes
The :term:`py:bytes-like object` denoting PCM or Opus voice data.
encode: bool
Indicates if ``data`` should be encoded into Opus.
... |
def delete_authoring_nodes(self, editor):
"""
Deletes the Model authoring Nodes associated with given editor.
:param editor: Editor.
:type editor: Editor
:return: Method success.
:rtype: bool
"""
editor_node = foundations.common.get_first_item(self.get_e... | Deletes the Model authoring Nodes associated with given editor.
:param editor: Editor.
:type editor: Editor
:return: Method success.
:rtype: bool |
def idempotency_key(self, idempotency_key):
"""
Sets the idempotency_key of this BatchUpsertCatalogObjectsRequest.
A value you specify that uniquely identifies this request among all your requests. A common way to create a valid idempotency key is to use a Universally unique identifier (UUID). ... | Sets the idempotency_key of this BatchUpsertCatalogObjectsRequest.
A value you specify that uniquely identifies this request among all your requests. A common way to create a valid idempotency key is to use a Universally unique identifier (UUID). If you're unsure whether a particular request was successful, yo... |
def bump(self, bump_part):
"""Return a new bumped version instance."""
major, minor, patch, stage, n = tuple(self)
# stage bump
if bump_part not in {"major", "minor", "patch"}:
if bump_part not in self.stages:
raise ValueError(f"Unknown {bump_part} stage")
... | Return a new bumped version instance. |
def merge_like_ops(self):
"""
>>> Cigar("1S20M").merge_like_ops()
Cigar('1S20M')
>>> Cigar("1S1S20M").merge_like_ops()
Cigar('2S20M')
>>> Cigar("1S1S1S20M").merge_like_ops()
Cigar('3S20M')
>>> Cigar("1S1S1S20M1S1S").merge_like_ops()
Cigar('3S20M2S'... | >>> Cigar("1S20M").merge_like_ops()
Cigar('1S20M')
>>> Cigar("1S1S20M").merge_like_ops()
Cigar('2S20M')
>>> Cigar("1S1S1S20M").merge_like_ops()
Cigar('3S20M')
>>> Cigar("1S1S1S20M1S1S").merge_like_ops()
Cigar('3S20M2S') |
def organization_fields_reorder(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_fields#reorder-organization-field"
api_path = "/api/v2/organization_fields/reorder.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/organization_fields#reorder-organization-field |
def get(self, sid):
"""
Constructs a AssetVersionContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext
:rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext
"""
return AssetVer... | Constructs a AssetVersionContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext
:rtype: twilio.rest.serverless.v1.service.asset.asset_version.AssetVersionContext |
def to_eng(num_in):
"""Return number in engineering notation."""
x = decimal.Decimal(str(num_in))
eng_not = x.normalize().to_eng_string()
return(eng_not) | Return number in engineering notation. |
def get_rds_instances_by_region(self, region):
''' Makes an AWS API call to the list of RDS instances in a particular
region '''
try:
conn = self.connect_to_aws(rds, region)
if conn:
instances = conn.get_all_dbinstances()
for instance in i... | Makes an AWS API call to the list of RDS instances in a particular
region |
def flushall(args):
"""Execute flushall in all cluster nodes.
"""
cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster))
for node in cluster.masters:
node.flushall() | Execute flushall in all cluster nodes. |
def get_review_history_statuses(instance, reverse=False):
"""Returns a list with the statuses of the instance from the review_history
"""
review_history = getReviewHistory(instance, reverse=reverse)
return map(lambda event: event["review_state"], review_history) | Returns a list with the statuses of the instance from the review_history |
def ParseMultiple(self, stats, file_objects, knowledge_base):
"""Parse the found release files."""
_ = knowledge_base
# Collate files into path: contents dictionary.
found_files = self._Combine(stats, file_objects)
# Determine collected files and apply weighting.
weights = [w for w in self.WEI... | Parse the found release files. |
def strelka_somatic_variant_stats(variant, variant_metadata):
"""Parse out the variant calling statistics for a given variant from a Strelka VCF
Parameters
----------
variant : varcode.Variant
sample_info : dict
Dictionary of sample to variant calling statistics, corresponds to the sample c... | Parse out the variant calling statistics for a given variant from a Strelka VCF
Parameters
----------
variant : varcode.Variant
sample_info : dict
Dictionary of sample to variant calling statistics, corresponds to the sample columns
in a Strelka VCF
Returns
-------
SomaticV... |
def get_ldap_filter(ldap_filter):
# type: (Any) -> Optional[Union[LDAPFilter, LDAPCriteria]]
"""
Retrieves the LDAP filter object corresponding to the given filter.
Parses it the argument if it is an LDAPFilter instance
:param ldap_filter: An LDAP filter (LDAPFilter or string)
:return: The corr... | Retrieves the LDAP filter object corresponding to the given filter.
Parses it the argument if it is an LDAPFilter instance
:param ldap_filter: An LDAP filter (LDAPFilter or string)
:return: The corresponding filter, can be None
:raise ValueError: Invalid filter string found
:raise TypeError: Unknow... |
async def update_bucket(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
bucket: typing.Dict = None,
**kwargs):
"""
Update bucket for user in chat... | Update bucket for user in chat
You can use bucket parameter or|and kwargs.
Chat or user is always required. If one of them is not provided,
you have to set missing value based on the provided one.
:param bucket:
:param chat:
:param user:
:param kwargs:
... |
def SELFDESTRUCT(self, recipient):
"""Halt execution and register account for later deletion"""
#This may create a user account
recipient = Operators.EXTRACT(recipient, 0, 160)
address = self.address
#FIXME for on the known addresses
if issymbolic(recipient):
... | Halt execution and register account for later deletion |
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
"""Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png')
if os.path.exists(output_filename):
# Don't download image if it's already there
return True
try:
# Downl... | Downloads one image, crops it, resizes it and saves it locally. |
def get_service_agreements(storage_path, status='pending'):
"""
Get service agreements pending to be executed.
:param storage_path: storage path for the internal db, str
:param status:
:return:
"""
conn = sqlite3.connect(storage_path)
try:
cursor = conn.cursor()
return [... | Get service agreements pending to be executed.
:param storage_path: storage path for the internal db, str
:param status:
:return: |
def to_hex_string(data):
''' Convert list of integers to a hex string, separated by ":" '''
if isinstance(data, int):
return '%02X' % data
return ':'.join([('%02X' % o) for o in data]) | Convert list of integers to a hex string, separated by ":" |
def score_n2(matrix, matrix_size):
"""\
Implements the penalty score feature 2.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================== ==================== ===============
Feature Evaluation condition Poi... | \
Implements the penalty score feature 2.
ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54)
============================== ==================== ===============
Feature Evaluation condition Points
============================== =... |
def get_instance(key, expire=None):
"""Return an instance of RedisSet."""
global _instances
try:
instance = _instances[key]
except KeyError:
instance = RedisSet(
key,
_redis,
expire=expire
)
_instances[key] = instance
return instan... | Return an instance of RedisSet. |
def cellpar_to_cell(cellpar, ab_normal=(0,0,1), a_direction=None):
"""Return a 3x3 cell matrix from `cellpar` = [a, b, c, alpha,
beta, gamma]. The returned cell is orientated such that a and b
are normal to `ab_normal` and a is parallel to the projection of
`a_direction` in the a-b plane.
Default ... | Return a 3x3 cell matrix from `cellpar` = [a, b, c, alpha,
beta, gamma]. The returned cell is orientated such that a and b
are normal to `ab_normal` and a is parallel to the projection of
`a_direction` in the a-b plane.
Default `a_direction` is (1,0,0), unless this is parallel to
`ab_normal`, in w... |
def list_secrets(self, path, mount_point=DEFAULT_MOUNT_POINT):
"""Return a list of key names at the specified location.
Folders are suffixed with /. The input must be a folder; list on a file will not return a value. Note that no
policy-based filtering is performed on keys; do not encode sensit... | Return a list of key names at the specified location.
Folders are suffixed with /. The input must be a folder; list on a file will not return a value. Note that no
policy-based filtering is performed on keys; do not encode sensitive information in key names. The values
themselves are not access... |
def _convert_angle_limit(angle, joint, **kwargs):
"""Converts the limit angle of the PyPot JSON file to the internal format"""
angle_pypot = angle
# No need to take care of orientation
if joint["orientation"] == "indirect":
angle_pypot = 1 * angle_pypot
# angle_pypot = angle_pypot + offset... | Converts the limit angle of the PyPot JSON file to the internal format |
def detect():
"""Does this compiler support OpenMP parallelization?"""
compiler = new_compiler()
hasopenmp = hasfunction(compiler, 'omp_get_num_threads()')
needs_gomp = hasopenmp
if not hasopenmp:
compiler.add_library('gomp')
hasopenmp = hasfunction(compiler, 'omp_get_num_threads()')
needs_gomp = hasopenmp
re... | Does this compiler support OpenMP parallelization? |
def recover_from_duplicatekeyerror(self, e):
""" method tries to recover from DuplicateKeyError """
if isinstance(e, DuplicateKeyError):
try:
return self.get_by_params(e.process_name, e.timeperiod, e.start_id, e.end_id)
except LookupError as e:
sel... | method tries to recover from DuplicateKeyError |
def scanAllProcessesForOpenFile(searchPortion, isExactMatch=True, ignoreCase=False):
'''
scanAllProcessessForOpenFile - Scans all processes on the system for a given filename
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If match should be ... | scanAllProcessessForOpenFile - Scans all processes on the system for a given filename
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If match should be exact, otherwise a partial match is performed.
@param ignoreCase <bool> Default False - I... |
def get_all_user_ssh_settings(application_name):
"""Retrieve the known host entries and public keys for application
Retrieve the known host entries and public keys for application for all
units of the given application related to this application for root user
and nova user.
:param application_nam... | Retrieve the known host entries and public keys for application
Retrieve the known host entries and public keys for application for all
units of the given application related to this application for root user
and nova user.
:param application_name: Name of application eg nova-compute-something
:ty... |
def _get_all_indexes(self):
"""Returns all indexes available in the parser"""
if self.parser:
return [v.index for v in self.parser.get_volumes()] + [d.index for d in self.parser.disks]
else:
return None | Returns all indexes available in the parser |
def _get_blkid_type(self):
"""Retrieves the FS type from the blkid command."""
try:
result = _util.check_output_(['blkid', '-p', '-O', str(self.offset), self.get_raw_path()])
if not result:
return None
# noinspection PyTypeChecker
blkid_re... | Retrieves the FS type from the blkid command. |
def find_noncopyable_vars(class_type, already_visited_cls_vars=None):
"""
Returns list of all `noncopyable` variables.
If an already_visited_cls_vars list is provided as argument, the returned
list will not contain these variables. This list will be extended with
whatever variables pointing to clas... | Returns list of all `noncopyable` variables.
If an already_visited_cls_vars list is provided as argument, the returned
list will not contain these variables. This list will be extended with
whatever variables pointing to classes have been found.
Args:
class_type (declarations.class_t): the cla... |
def get_self_attention_bias(x):
"""Creates masked self attention bias.
Args:
x: A tensor of shape [batch, length, depth]
Returns:
self_attention_bias: A tensor of shape [length, length, 1]
"""
x_shape = common_layers.shape_list(x)
self_attention_bias = common_attention.attention_bias_lower_triang... | Creates masked self attention bias.
Args:
x: A tensor of shape [batch, length, depth]
Returns:
self_attention_bias: A tensor of shape [length, length, 1] |
def _issubclass(subclass, superclass, bound_Generic=None, bound_typevars=None,
bound_typevars_readonly=False, follow_fwd_refs=True, _recursion_check=None):
"""Access this via ``pytypes.is_subtype``.
Works like ``issubclass``, but supports PEP 484 style types from ``typing`` module.
subclass : t... | Access this via ``pytypes.is_subtype``.
Works like ``issubclass``, but supports PEP 484 style types from ``typing`` module.
subclass : type
The type to check for being a subtype of ``superclass``.
superclass : type
The type to check for being a supertype of ``subclass``.
bound_Generic : Optio... |
def file_system(self):
"""Gets the filesystem corresponding to the open scheduler."""
if self._file_system is None:
self._file_system = self.scheduler.get_file_system()
return self._file_system | Gets the filesystem corresponding to the open scheduler. |
def has_cell(self, s):
"""Tests whether store `s` is a cell, that is, it uses exactly one
cell, and there can take on only a finite number of states)."""
for t in self.transitions:
if len(t.lhs[s]) != 1:
return False
if len(t.rhs[s]) != 1:
... | Tests whether store `s` is a cell, that is, it uses exactly one
cell, and there can take on only a finite number of states). |
def wait_for_notification(self, handle: int, delegate, notification_timeout: float):
"""Listen for characteristics changes from a BLE address.
@param: mac - MAC address in format XX:XX:XX:XX:XX:XX
@param: handle - BLE characteristics handle in format 0xXX
a value of 0x0... | Listen for characteristics changes from a BLE address.
@param: mac - MAC address in format XX:XX:XX:XX:XX:XX
@param: handle - BLE characteristics handle in format 0xXX
a value of 0x0100 is written to register for listening
@param: delegate - gatttool receives the
... |
def iter_list(self, id, *args, **kwargs):
"""Get a list of attachments. Whereas ``list`` fetches a single page
of attachments according to its ``limit`` and ``page``
arguments, ``iter_list`` returns all attachments by internally
making successive calls to ``list``.
:param id: D... | Get a list of attachments. Whereas ``list`` fetches a single page
of attachments according to its ``limit`` and ``page``
arguments, ``iter_list`` returns all attachments by internally
making successive calls to ``list``.
:param id: Device ID as an int.
:param args: Arguments th... |
def __compare_parameters(self, width, height, zoom, parameters):
"""Compare parameters for equality
Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If
so, True is returned, else False,
:param width: The width of the image
:... | Compare parameters for equality
Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If
so, True is returned, else False,
:param width: The width of the image
:param height: The height of the image
:param zoom: The current scale... |
def tointerval(s):
"""
If string, then convert to an interval; otherwise just return the input
"""
if isinstance(s, basestring):
m = coord_re.search(s)
if m.group('strand'):
return pybedtools.create_interval_from_list([
m.group('chrom'),
m.grou... | If string, then convert to an interval; otherwise just return the input |
def translate(term=None, phrase=None, api_key=GIPHY_PUBLIC_KEY, strict=False,
rating=None):
"""
Shorthand for creating a Giphy api wrapper with the given api key
and then calling the translate method.
"""
return Giphy(api_key=api_key, strict=strict).translate(
term=term, phrase... | Shorthand for creating a Giphy api wrapper with the given api key
and then calling the translate method. |
def absent(self, name, rdtype=None):
"""Require that an owner name (and optionally an rdata type) does
not exist as a prerequisite to the execution of the update."""
if isinstance(name, (str, unicode)):
name = dns.name.from_text(name, None)
if rdtype is None:
rrs... | Require that an owner name (and optionally an rdata type) does
not exist as a prerequisite to the execution of the update. |
def get_task_df(self):
'''
Returns
-------
'''
term_time_df = self._get_term_time_df()
terms_to_include = (
term_time_df
.groupby('term')['top']
.sum()
.sort_values(ascending=False)
.iloc[:self.num_terms_to_include].index
)
task_df = (
term_time_df[term_time_df.term.isin(terms_to_... | Returns
------- |
def adjustText(self):
"""
Updates the text based on the current format options.
"""
pos = self.cursorPosition()
self.blockSignals(True)
super(XLineEdit, self).setText(self.formatText(self.text()))
self.setCursorPosition(pos)
self.blockSignals(False) | Updates the text based on the current format options. |
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_TEXT."""
return Xdr.types.Memo(type=Xdr.const.MEMO_TEXT, text=self.text) | Creates an XDR Memo object for a transaction with MEMO_TEXT. |
def write_file(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = ProbModelXMLWriter(model)
>>> writer.write_file(test_file)
"""
writer = self.__s... | Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = ProbModelXMLWriter(model)
>>> writer.write_file(test_file) |
def waypoint_request_list_send(self):
'''wrapper for waypoint_request_list_send'''
if self.mavlink10():
self.mav.mission_request_list_send(self.target_system, self.target_component)
else:
self.mav.waypoint_request_list_send(self.target_system, self.target_component) | wrapper for waypoint_request_list_send |
def _install_packages(path, packages):
"""Install all packages listed to the target directory.
Ignores any package that includes Python itself and python-lambda as well
since its only needed for deploying and not running the code
:param str path:
Path to copy installed pip packages to.
:pa... | Install all packages listed to the target directory.
Ignores any package that includes Python itself and python-lambda as well
since its only needed for deploying and not running the code
:param str path:
Path to copy installed pip packages to.
:param list packages:
A list of packages ... |
def isMultiContract(self, contract):
""" tells if is this contract has sub-contract with expiries/strikes/sides """
if contract.m_secType == "FUT" and contract.m_expiry == "":
return True
if contract.m_secType in ["OPT", "FOP"] and \
(contract.m_expiry == "" or contr... | tells if is this contract has sub-contract with expiries/strikes/sides |
def kill_all(job_queue, reason='None given', states=None):
"""Terminates/cancels all RUNNING, RUNNABLE, and STARTING jobs."""
if states is None:
states = ['STARTING', 'RUNNABLE', 'RUNNING']
batch = boto3.client('batch')
runnable = batch.list_jobs(jobQueue=job_queue, jobStatus='RUNNABLE')
job... | Terminates/cancels all RUNNING, RUNNABLE, and STARTING jobs. |
def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore):
"""Initialize kvstore"""
for idx, param_on_devs in enumerate(param_arrays):
name = param_names[idx]
kvstore.init(name, arg_params[name])
if update_on_kvstore:
kvstore.pull(name, param... | Initialize kvstore |
def get_languages(self):
"""
Get the list of languages we need to start servers and create
clients for.
"""
languages = ['python']
all_options = CONF.options(self.CONF_SECTION)
for option in all_options:
if option in [l.lower() for l in LSP_LANGUAGES]:... | Get the list of languages we need to start servers and create
clients for. |
def copy_file(self):
share_name = self._create_share()
directory_name = self._create_directory(share_name)
source_file_name = self._get_file_reference()
self.service.create_file(share_name, directory_name, source_file_name, 512)
# Basic
# Copy the file from the directory... | source_file_url = self.service.make_file_url(
remote_share_name,
remote_directory_name,
remote_file_name,
sas_token=remote_sas_token,
)
copy = self.service.copy_file(destination_sharename,
destination_directory_name,
... |
def load_keys(self, issuer, jwks_uri='', jwks=None, replace=False):
"""
Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If ... | Fetch keys from another server
:param jwks_uri: A URL pointing to a site that will return a JWKS
:param jwks: A dictionary representation of a JWKS
:param issuer: The provider URL
:param replace: If all previously gathered keys from this provider
should be replace.
:... |
def run_cmd(cmd, remote, rootdir='', workdir='', ignore_exit_code=False,
ssh='ssh'):
r'''Run the given cmd in the given workdir, either locally or remotely, and
return the combined stdout/stderr
Parameters:
cmd (list of str or str): Command to execute, as list consisting of the
... | r'''Run the given cmd in the given workdir, either locally or remotely, and
return the combined stdout/stderr
Parameters:
cmd (list of str or str): Command to execute, as list consisting of the
command, and options. Alternatively, the command can be given a
single string, which... |
def get_object_references(tb, source, max_string_length=1000):
"""
Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value)
"""
global obj_ref_regex
referenced_attr = set()
for line in ... | Find the values of referenced attributes of objects within the traceback scope.
:param tb: traceback
:return: list of tuples containing (variable name, value) |
def get_context_files(data):
"""Retrieve pre-installed annotation files for annotating genome context.
"""
ref_file = dd.get_ref_file(data)
all_files = []
for ext in [".bed.gz"]:
all_files += sorted(glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
... | Retrieve pre-installed annotation files for annotating genome context. |
def perform_permissions_check(self, user, obj, perms):
""" Performs the permissions check. """
return self.request.forum_permission_handler.can_update_topics_to_announces(obj, user) | Performs the permissions check. |
def add_cell_code(self, cell_str, pos=None):
"""
Add Python cell
:param cell_str: cell content
:return:
"""
cell_str = cell_str.strip()
logging.debug("add_cell_code: {}".format(cell_str))
cell = nbf.v4.new_code_cell(cell_str)
if pos is None:
... | Add Python cell
:param cell_str: cell content
:return: |
def read_content(path: str, limit: Optional[int] = None) -> Iterator[List[str]]:
"""
Returns a list of tokens for each line in path up to a limit.
:param path: Path to files containing sentences.
:param limit: How many lines to read from path.
:return: Iterator over lists of words.
"""
with... | Returns a list of tokens for each line in path up to a limit.
:param path: Path to files containing sentences.
:param limit: How many lines to read from path.
:return: Iterator over lists of words. |
def dump_json(data, indent=None):
"""
:param list | dict data:
:param Optional[int] indent:
:rtype: unicode
"""
return json.dumps(data,
indent=indent,
ensure_ascii=False,
sort_keys=True,
separators=(',', ': '... | :param list | dict data:
:param Optional[int] indent:
:rtype: unicode |
def connect_pores(network, pores1, pores2, labels=[], add_conns=True):
r'''
Returns the possible connections between two group of pores, and optionally
makes the connections.
See ``Notes`` for advanced usage.
Parameters
----------
network : OpenPNM Network Object
pores1 : array_like
... | r'''
Returns the possible connections between two group of pores, and optionally
makes the connections.
See ``Notes`` for advanced usage.
Parameters
----------
network : OpenPNM Network Object
pores1 : array_like
The first group of pores on the network
pores2 : array_like
... |
def get_all_autoscaling_instances(self, instance_ids=None,
max_records=None, next_token=None):
"""
Returns a description of each Auto Scaling instance in the instance_ids
list. If a list is not provided, the service returns the full details
of all in... | Returns a description of each Auto Scaling instance in the instance_ids
list. If a list is not provided, the service returns the full details
of all instances up to a maximum of fifty.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the n... |
def dump_tables_to_tskit(pop):
"""
Converts fwdpy11.TableCollection to an
tskit.TreeSequence
"""
node_view = np.array(pop.tables.nodes, copy=True)
node_view['time'] -= node_view['time'].max()
node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0
edge_view = np.array(pop.tables... | Converts fwdpy11.TableCollection to an
tskit.TreeSequence |
def entrez_batch_webhistory(record, expected, batchsize, *fnargs, **fnkwargs):
"""Recovers the Entrez data from a prior NCBI webhistory search, in
batches of defined size, using Efetch. Returns all results as a list.
- record: Entrez webhistory record
- expected: number of expected search returns
-... | Recovers the Entrez data from a prior NCBI webhistory search, in
batches of defined size, using Efetch. Returns all results as a list.
- record: Entrez webhistory record
- expected: number of expected search returns
- batchsize: how many search returns to retrieve in a batch
- *fnargs: arguments to... |
def vnic_compose_empty(device=None):
"""
Compose empty vNIC for next attaching to a network
:param device: <vim.vm.device.VirtualVmxnet3 or None> Device for this this 'spec' will be composed.
If 'None' a new device will be composed.
'Operation' - edit/add' depends on if d... | Compose empty vNIC for next attaching to a network
:param device: <vim.vm.device.VirtualVmxnet3 or None> Device for this this 'spec' will be composed.
If 'None' a new device will be composed.
'Operation' - edit/add' depends on if device existed
:return: <vim.vm.device.VirtualDevi... |
def _process_key_val(self, instance, key, val):
'''
Logic to let the plugin instance process the redis key/val
Split out for unit testing
@param instance: the plugin instance
@param key: the redis key
@param val: the key value from redis
'''
if instance.c... | Logic to let the plugin instance process the redis key/val
Split out for unit testing
@param instance: the plugin instance
@param key: the redis key
@param val: the key value from redis |
def get_package_version(self):
"""
Get the version of the package
:return:
"""
output = subprocess.check_output([
'{}'.format(self.python),
'setup.py',
'--version',
]).decode()
return output.rstrip() | Get the version of the package
:return: |
def _to_args(x):
"""Convert to args representation"""
if not isinstance(x, (list, tuple, np.ndarray)):
x = [x]
return x | Convert to args representation |
def precision_recall(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n... | Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n_samples, n_classes] for multiclass
Target scores (... |
def bind(
self,
server_name,
script_name=None,
subdomain=None,
url_scheme="http",
default_method="GET",
path_info=None,
query_args=None,
):
"""Return a new :class:`MapAdapter` with the details specified to the
call. Note that `script_n... | Return a new :class:`MapAdapter` with the details specified to the
call. Note that `script_name` will default to ``'/'`` if not further
specified or `None`. The `server_name` at least is a requirement
because the HTTP RFC requires absolute URLs for redirects and so all
redirect excepti... |
def dispatch_request(self):
"""Modified version of Flask.dispatch_request to call process_view."""
req = _request_ctx_stack.top.request
app = current_app
# Return flask's default options response. See issue #40
if req.method == "OPTIONS":
return app.make_default_opt... | Modified version of Flask.dispatch_request to call process_view. |
def autoencoder_range(rhp):
"""Tuning grid of the main autoencoder params."""
rhp.set_float("dropout", 0.01, 0.3)
rhp.set_float("gan_loss_factor", 0.01, 0.1)
rhp.set_float("bottleneck_l2_factor", 0.001, 0.1, scale=rhp.LOG_SCALE)
rhp.set_discrete("bottleneck_warmup_steps", [200, 2000])
rhp.set_float("gumbel_... | Tuning grid of the main autoencoder params. |
def array_from_nested_dictionary(
nested_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Parameters
----------
nested_dict : dict
Dictionary which contains dictionaries
array_fn : function
Takes shape and dtype as arguments, returns empty a... | Parameters
----------
nested_dict : dict
Dictionary which contains dictionaries
array_fn : function
Takes shape and dtype as arguments, returns empty array.
dtype : dtype
NumPy dtype of result array
square_result : bool
Combine keys from outer and inner dictionarie... |
def init():
"""Execute init tasks for all components (virtualenv, pip)."""
if not os.path.isdir('venv'):
print(cyan('\nCreating the virtual env...'))
local('pyvenv-3.4 venv')
print(green('Virtual env created.'))
print(green('Virtual Environment ready.')) | Execute init tasks for all components (virtualenv, pip). |
def post(request):
"""Returns a serialized object"""
data = request.POST or json.loads(request.body)['body']
guid = data.get('guid', None)
res = Result()
if guid:
obj = getObjectsFromGuids([guid,])[0]
comment = Comment()
comment.comment = data.get('comment', 'No comment')
... | Returns a serialized object |
def get_interface_name():
"""
Returns the interface name of the first not link_local and not loopback interface.
"""
interface_name = ''
interfaces = psutil.net_if_addrs()
for name, details in interfaces.items():
for detail in details:
if detail.family == socket.AF_INET:
... | Returns the interface name of the first not link_local and not loopback interface. |
def get_content_of_file(self, project, repository, filename, at=None, markup=None):
"""
Retrieve the raw content for a file path at a specified revision.
The authenticated user must have REPO_READ permission for the specified repository to call this resource.
:param project:
:par... | Retrieve the raw content for a file path at a specified revision.
The authenticated user must have REPO_READ permission for the specified repository to call this resource.
:param project:
:param repository:
:param filename:
:param at: OPTIONAL ref string
:param markup: i... |
def register_identity(self, id_stmt):
"""Register `id_stmt` with its base identity, if any.
"""
bst = id_stmt.search_one("base")
if bst:
bder = self.identity_deps.setdefault(bst.i_identity, [])
bder.append(id_stmt) | Register `id_stmt` with its base identity, if any. |
def auth(self, auth_key):
"""
Performs the initial authentication on connect
"""
if self._socket is None:
self._socket = self._connect()
return self.call('auth', {"AuthKey": auth_key}, expect_body=False) | Performs the initial authentication on connect |
def extract_zipdir(zip_file):
"""
Extract contents of zip file into subfolder in parent directory.
Parameters
----------
zip_file : str
Path to zip file
Returns
-------
str : folder where the zip was extracted
"""
if not os.path.exists(zip_file):
rai... | Extract contents of zip file into subfolder in parent directory.
Parameters
----------
zip_file : str
Path to zip file
Returns
-------
str : folder where the zip was extracted |
def remove(name=None, pkgs=None, purge=False, **kwargs):
'''
Remove a single package with pkg_delete
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.1... | Remove a single package with pkg_delete
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
... |
def streaming_market_data_filter(fields=None, ladder_levels=None):
"""
:param list fields: EX_BEST_OFFERS_DISP, EX_BEST_OFFERS, EX_ALL_OFFERS, EX_TRADED,
EX_TRADED_VOL, EX_LTP, EX_MARKET_DEF, SP_TRADED, SP_PROJECTED
:param int ladder_levels: 1->10
:return: dict
"""
args = locals()
retur... | :param list fields: EX_BEST_OFFERS_DISP, EX_BEST_OFFERS, EX_ALL_OFFERS, EX_TRADED,
EX_TRADED_VOL, EX_LTP, EX_MARKET_DEF, SP_TRADED, SP_PROJECTED
:param int ladder_levels: 1->10
:return: dict |
def _predicted(self):
"""The predicted values of y ('yhat')."""
return np.squeeze(
np.matmul(self.xwins, np.expand_dims(self.solution, axis=-1))
) | The predicted values of y ('yhat'). |
def get_apps_json(self, url, timeout, auth, acs_url, ssl_verify, tags, group):
"""
The dictionary containing the apps is cached during collection and reset
at every `check()` call.
"""
if self.apps_response is not None:
return self.apps_response
# Marathon ap... | The dictionary containing the apps is cached during collection and reset
at every `check()` call. |
def horiz_string(*args, **kwargs):
"""
Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep... | Horizontally concatenates strings reprs preserving indentation
Concats a list of objects ensuring that the next item in the list
is all the way to the right of any previous items.
Args:
*args: list of strings to concat
**kwargs: precision, sep
CommandLine:
python -m utool.util... |
def thread_function(self):
"""Thread function."""
self.__subscribed = True
url = SUBSCRIBE_ENDPOINT + "?token=" + self._session_token
data = self._session.query(url, method='GET', raw=True, stream=True)
if not data or not data.ok:
_LOGGER.debug("Did not receive a va... | Thread function. |
def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr['NUMXVER'] = (__version__, 'Numina package version')
hdr['NUMRNAM'] = (self.__class__.__name__, 'Numina recipe name')
hdr['NUMRVER'] = (self.__version__, 'Numina recipe version')
return hdr | Set metadata in FITS headers. |
def removeThing(self, thingTypeId, thingId):
"""
Delete an existing thing.
It accepts thingTypeId (string) and thingId (string) as parameters
In case of failure it throws APIException
"""
thingUrl = ApiClient.thingUrl % (self.host, thingTypeId, thingId)
r = reque... | Delete an existing thing.
It accepts thingTypeId (string) and thingId (string) as parameters
In case of failure it throws APIException |
def enc_setup(self, enc_alg, msg, auth_data=b'', key=None, iv=""):
""" Encrypt JWE content.
:param enc_alg: The JWE "enc" value specifying the encryption algorithm
:param msg: The plain text message
:param auth_data: Additional authenticated data
:param key: Key (CEK)
:r... | Encrypt JWE content.
:param enc_alg: The JWE "enc" value specifying the encryption algorithm
:param msg: The plain text message
:param auth_data: Additional authenticated data
:param key: Key (CEK)
:return: Tuple (ciphertext, tag), both as bytes |
def create(cls, zmq_context, endpoint):
"""Create new server transport.
Instead of creating the socket yourself, you can call this function and
merely pass the :py:class:`zmq.core.context.Context` instance.
By passing a context imported from :py:mod:`zmq.green`, you can use
gre... | Create new server transport.
Instead of creating the socket yourself, you can call this function and
merely pass the :py:class:`zmq.core.context.Context` instance.
By passing a context imported from :py:mod:`zmq.green`, you can use
green (gevent) 0mq sockets as well.
:param zm... |
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Allow formfield_overrides to contain field names too.
"""
overrides = self.formfield_overrides.get(db_field.name)
if overrides:
kwargs.update(overrides)
field = super(AbstractEntryBaseAdmin, self).formf... | Allow formfield_overrides to contain field names too. |
def email_action_view(self, id, action):
""" Perform action 'action' on UserEmail object 'id'
"""
# Retrieve UserEmail by id
user_email = self.db_manager.get_user_email_by_id(id=id)
# Users may only change their own UserEmails
if not user_email or user_email.user_id != ... | Perform action 'action' on UserEmail object 'id' |
def read_table(self):
"""
Read an AMQP table, and return as a Python dictionary.
"""
self.bitcount = self.bits = 0
tlen = unpack('>I', self.input.read(4))[0]
table_data = AMQPReader(self.input.read(tlen))
result = {}
while table_data.input.tell() < tlen:
... | Read an AMQP table, and return as a Python dictionary. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.