code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def filter_zone(self, data):
"""Check if a zone is private"""
if self.private_zone is not None:
if data['Config']['PrivateZone'] != self.str2bool(self.private_zone):
return False
if data['Name'] != '{0}.'.format(self.domain):
return False
return ... | Check if a zone is private |
def get_userstable_data(self):
"""Get users with roles on the project.
Roles can be applied directly on the project or through a group.
"""
project_users = {}
project = self.tab_group.kwargs['project']
try:
# Get all global roles once to avoid multiple reque... | Get users with roles on the project.
Roles can be applied directly on the project or through a group. |
def _warn_silly_options(cls, args):
'''Print warnings about any options that may be silly.'''
if 'page-requisites' in args.span_hosts_allow \
and not args.page_requisites:
_logger.warning(
_('Spanning hosts is allowed for page requisites, '
'... | Print warnings about any options that may be silly. |
def compare_variants_label_plot(data):
""" Return HTML for the Compare variants plot"""
keys = OrderedDict()
keys['total_called_variants_known'] = {'name': 'Known Variants'}
keys['total_called_variants_novel'] = {'name': 'Novel Variants'}
pconfig = {
'id': 'picard_variantCallingMetrics_var... | Return HTML for the Compare variants plot |
def _compile_pfgen(self):
"""Post power flow computation for PV and SW"""
string = '"""\n'
string += 'system.dae.init_g()\n'
for gcall, pflow, shunt, series, stagen, call in zip(
self.gcall, self.pflow, self.shunt, self.series, self.stagen,
self.gcalls):
... | Post power flow computation for PV and SW |
def DBObject(table_name, versioning=VersioningTypes.NONE):
"""Classes annotated with DBObject gain persistence methods."""
def wrapped(cls):
field_names = set()
all_fields = []
for name in dir(cls):
fld = getattr(cls, name)
if fld and isinstance(fld, Field):
... | Classes annotated with DBObject gain persistence methods. |
def get_distbins(start=100, bins=2500, ratio=1.01):
""" Get exponentially sized
"""
b = np.ones(bins, dtype="float64")
b[0] = 100
for i in range(1, bins):
b[i] = b[i - 1] * ratio
bins = np.around(b).astype(dtype="int")
binsizes = np.diff(bins)
return bins, binsizes | Get exponentially sized |
def _rename_hstore_unique(self, old_table_name, new_table_name,
old_field, new_field, keys):
"""Renames an existing UNIQUE constraint for the specified
hstore keys."""
old_name = self._unique_constraint_name(
old_table_name, old_field, keys)
new... | Renames an existing UNIQUE constraint for the specified
hstore keys. |
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type en... | Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :cl... |
def generate_nodes(self, topology):
"""
Generate a list of nodes for the new topology
:param dict topology: processed topology from
:py:meth:`process_topology`
:return: a list of dicts on nodes
:rtype: list
"""
nodes = []
de... | Generate a list of nodes for the new topology
:param dict topology: processed topology from
:py:meth:`process_topology`
:return: a list of dicts on nodes
:rtype: list |
def list_symbols(self, partial_match=None):
"""
Returns all symbols in the library
Parameters
----------
partial: None or str
if not none, use this string to do a partial match on symbol names
Returns
-------
list of str
"""
s... | Returns all symbols in the library
Parameters
----------
partial: None or str
if not none, use this string to do a partial match on symbol names
Returns
-------
list of str |
def apply_layout(self, child, layout):
""" Apply the flexbox specific layout.
"""
params = self.create_layout_params(child, layout)
w = child.widget
if w:
# padding
if layout.get('padding'):
dp = self.dp
l, t, r, b ... | Apply the flexbox specific layout. |
def update( # noqa: C901
self, alert_condition_nrql_id, policy_id, name=None, threshold_type=None, query=None,
since_value=None, terms=None, expected_groups=None, value_function=None,
runbook_url=None, ignore_overlap=None, enabled=True):
"""
Updates any of the option... | Updates any of the optional parameters of the alert condition nrql
:type alert_condition_nrql_id: int
:param alert_condition_nrql_id: Alerts condition NRQL id to update
:type policy_id: int
:param policy_id: Alert policy id where target alert condition belongs to
:type conditi... |
def tradingStatusDF(symbol=None, token='', version=''):
'''The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news disseminatio... | The Trading status message is used to indicate the current trading status of a security.
For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons.
For non-IEX-listed securities, IE... |
def _s3_intermediate_upload(file_obj, file_name, fields, session, callback_url):
"""Uploads a single file-like object to an intermediate S3 bucket which One Codex can pull from
after receiving a callback.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
... | Uploads a single file-like object to an intermediate S3 bucket which One Codex can pull from
after receiving a callback.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
A wrapper around a pair of fastx files (`FASTXInterleave`) or a single fastx file. I... |
def predict(self, x_test):
"""Returns the prediction of the model on the given test data.
Args:
x_test : array-like, shape = (n_samples, sent_length)
Test samples.
Returns:
y_pred : array-like, shape = (n_smaples, sent_length)
Prediction labels f... | Returns the prediction of the model on the given test data.
Args:
x_test : array-like, shape = (n_samples, sent_length)
Test samples.
Returns:
y_pred : array-like, shape = (n_smaples, sent_length)
Prediction labels for x. |
def isSameStatementList(stmListA: List[HdlStatement],
stmListB: List[HdlStatement]) -> bool:
"""
:return: True if two lists of HdlStatement instances are same
"""
if stmListA is stmListB:
return True
if stmListA is None or stmListB is None:
return False
f... | :return: True if two lists of HdlStatement instances are same |
def _copy_across(self, rel_path, cb=None):
"""If the upstream doesn't have the file, get it from the alternate and store it in the upstream"""
from . import copy_file_or_flo
if not self.upstream.has(rel_path):
if not self.alternate.has(rel_path):
return None
... | If the upstream doesn't have the file, get it from the alternate and store it in the upstream |
def distance_to(self, other_catchment):
"""
Returns the distance between the centroids of two catchments in kilometers.
:param other_catchment: Catchment to calculate distance to
:type other_catchment: :class:`.Catchment`
:return: Distance between the catchments in km.
:... | Returns the distance between the centroids of two catchments in kilometers.
:param other_catchment: Catchment to calculate distance to
:type other_catchment: :class:`.Catchment`
:return: Distance between the catchments in km.
:rtype: float |
def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
"""
input_dict = su... | Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object |
def _metahash(self):
"""Checksum hash of all the inputs to this rule.
Output is invalid until collect_srcs and collect_deps have been run.
In theory, if this hash doesn't change, the outputs won't change
either, which makes it useful for caching.
"""
# BE CAREFUL when ... | Checksum hash of all the inputs to this rule.
Output is invalid until collect_srcs and collect_deps have been run.
In theory, if this hash doesn't change, the outputs won't change
either, which makes it useful for caching. |
def unescape(msg, extra_format_dict={}):
"""Takes a girc-escaped message and returns a raw IRC message"""
new_msg = ''
extra_format_dict.update(format_dict)
while len(msg):
char = msg[0]
msg = msg[1:]
if char == escape_character:
escape_key = msg[0]
msg ... | Takes a girc-escaped message and returns a raw IRC message |
async def on_step(self, iteration):
self.combinedActions = []
"""
- depots when low on remaining supply
- townhalls contains commandcenter and orbitalcommand
- self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount... | - depots when low on remaining supply
- townhalls contains commandcenter and orbitalcommand
- self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount
- self.already_pending(TYPE) counts how many units are queued - but in this bot be... |
def realpred(cls, lemma, pos, sense=None):
"""Instantiate a Pred from its components."""
string_tokens = [lemma]
if pos is not None:
string_tokens.append(pos)
if sense is not None:
sense = str(sense)
string_tokens.append(sense)
predstr = '_'.jo... | Instantiate a Pred from its components. |
def step(self):
# type: () -> bool
"""
Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0
"""
with self.__lock:
s... | Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0 |
def frames(self):
"""Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj... | Retrieve the next frame from the image directory and convert it to a ColorImage,
a DepthImage, and an IrImage.
Parameters
----------
skip_registration : bool
If True, the registration step is skipped.
Returns
-------
:obj:`tuple` of :obj:`ColorImage`... |
def html(data, options, center=False, save=False,
save_name=None, save_path='saved', dated=True, notebook=True):
"""
save=True will create a standalone HTML doc under localdir/saved (creating folfer save if necessary)
center=True will center the plot in the output cell, otherwise left-aligned by de... | save=True will create a standalone HTML doc under localdir/saved (creating folfer save if necessary)
center=True will center the plot in the output cell, otherwise left-aligned by default. |
def close(self):
"""Closes the tunnel."""
try:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
except socket.error:
pass | Closes the tunnel. |
def code_data_whitening(self, decoding, inpt):
"""
XOR Data Whitening
:param decoding:
:param inpt:
:return:
"""
inpt_copy = array.array("B", inpt)
return self.apply_data_whitening(decoding, inpt_copy) | XOR Data Whitening
:param decoding:
:param inpt:
:return: |
def grant_admin_role(self):
"""
Grant admin access to a user. If the user already has admin access, this
does nothing. If the user currently has a non-admin role, it will be replaced
with the admin role.
@return: An ApiUser object
"""
apiuser = ApiUser(self._get_resource_root(), self.name, ... | Grant admin access to a user. If the user already has admin access, this
does nothing. If the user currently has a non-admin role, it will be replaced
with the admin role.
@return: An ApiUser object |
def listdict_to_listlist_and_matrix(sparse):
"""Transforms the adjacency list representation of a graph
of type listdict into the listlist + weight matrix representation
:param sparse: graph in listdict representation
:returns: couple with listlist representation, and weight matrix
:complexity: lin... | Transforms the adjacency list representation of a graph
of type listdict into the listlist + weight matrix representation
:param sparse: graph in listdict representation
:returns: couple with listlist representation, and weight matrix
:complexity: linear |
def build_markdown_body(self, text):
"""Generate the body for the Markdown file.
- processes each json block one by one
- for each block, process:
- the creator of the notebook (user)
- the date the notebook was created
- the date the notebook was last update... | Generate the body for the Markdown file.
- processes each json block one by one
- for each block, process:
- the creator of the notebook (user)
- the date the notebook was created
- the date the notebook was last updated
- the input by detecting the edito... |
def adafactor_optimizer_from_hparams(hparams, lr):
"""Create an Adafactor optimizer based on model hparams.
Args:
hparams: model hyperparameters
lr: learning rate scalar.
Returns:
an AdafactorOptimizer
Raises:
ValueError: on illegal values
"""
if hparams.optimizer_adafactor_decay_type == "a... | Create an Adafactor optimizer based on model hparams.
Args:
hparams: model hyperparameters
lr: learning rate scalar.
Returns:
an AdafactorOptimizer
Raises:
ValueError: on illegal values |
def validate(input_schema=None, output_schema=None,
input_example=None, output_example=None,
validator_cls=None,
format_checker=None, on_empty_404=False,
use_defaults=False):
"""Parameterized decorator for schema validation
:type validator_cls: IValidator cla... | Parameterized decorator for schema validation
:type validator_cls: IValidator class
:type format_checker: jsonschema.FormatChecker or None
:type on_empty_404: bool
:param on_empty_404: If this is set, and the result from the
decorated method is a falsy value, a 404 will be raised.
:type use... |
def list_formats ():
"""Print information about available archive formats to stdout."""
print("Archive programs of", App)
print("Archive programs are searched in the following directories:")
print(util.system_search_path())
print()
for format in ArchiveFormats:
print(format, "files:")
... | Print information about available archive formats to stdout. |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(MySQLCollector, self).get_default_config()
config.update({
'path': 'mysql',
# Connection settings
'hosts': [],
# Which rows of 'SHOW... | Returns the default collector settings |
def pid(self):
"""The server's PID (None if not running).
"""
# We can't possibly be running if our base_pathname isn't defined.
if not self.base_pathname:
return None
try:
pidfile = os.path.join(self.base_pathname, 'postmaster.pid')
return int... | The server's PID (None if not running). |
def push(self, repository, stream=False, raise_on_error=True, **kwargs):
"""
Pushes an image repository to the registry.
:param repository: Name of the repository (can include a tag).
:type repository: unicode | str
:param stream: Use the stream output format with additional sta... | Pushes an image repository to the registry.
:param repository: Name of the repository (can include a tag).
:type repository: unicode | str
:param stream: Use the stream output format with additional status information.
:type stream: bool
:param raise_on_error: Raises errors in t... |
def Subgroups(self):
"""Returns a Groups object containing all child groups.
>>> clc.v2.Group("wa1-4416").Subgroups()
<clc.APIv2.group.Groups object at 0x105fa27d0>
"""
return(Groups(alias=self.alias,groups_lst=self.data['groups'],session=self.session)) | Returns a Groups object containing all child groups.
>>> clc.v2.Group("wa1-4416").Subgroups()
<clc.APIv2.group.Groups object at 0x105fa27d0> |
def VerifySignature(self, message, signature, public_key, unhex=True):
"""
Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint): the public key to ... | Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint): the public key to use for verifying the signature.
unhex (bool): whether the message should be un... |
def evolution_strength_of_connection(A, B=None, epsilon=4.0, k=2,
proj_type="l2", block_flag=False,
symmetrize_measure=True):
"""Evolution Strength Measure.
Construct strength of connection matrix using an Evolution-based measure
Pa... | Evolution Strength Measure.
Construct strength of connection matrix using an Evolution-based measure
Parameters
----------
A : csr_matrix, bsr_matrix
Sparse NxN matrix
B : string, array
If B=None, then the near nullspace vector used is all ones. If B is
an (NxK) array, the... |
def panes(self):
" List with all panes from this Window. "
result = []
for s in self.splits:
for item in s:
if isinstance(item, Pane):
result.append(item)
return result | List with all panes from this Window. |
def update_vip(self, vip, body=None):
"""Updates a load balancer vip."""
return self.put(self.vip_path % (vip), body=body) | Updates a load balancer vip. |
def parse(self):
"""
Parses a requirements.txt-like file
"""
index_server = None
for num, line in enumerate(self.iter_lines()):
line = line.rstrip()
if not line:
continue
if line.startswith('#'):
# comments are l... | Parses a requirements.txt-like file |
def _textio_iterlines(stream):
"""
Iterates over lines in a TextIO stream until an EOF is encountered.
This is the iterator version of stream.readlines()
"""
line = stream.readline()
while line != '':
yield line
line = stream.readline() | Iterates over lines in a TextIO stream until an EOF is encountered.
This is the iterator version of stream.readlines() |
def nearby_faces(mesh, points):
"""
For each point find nearby faces relatively quickly.
The closest point on the mesh to the queried point is guaranteed to be
on one of the faces listed.
Does this by finding the nearest vertex on the mesh to each point, and
then returns all the faces that int... | For each point find nearby faces relatively quickly.
The closest point on the mesh to the queried point is guaranteed to be
on one of the faces listed.
Does this by finding the nearest vertex on the mesh to each point, and
then returns all the faces that intersect the axis aligned bounding box
cen... |
def _create_RSA_private_key(self,
bytes):
"""
Instantiates an RSA key from bytes.
Args:
bytes (byte string): Bytes of RSA private key.
Returns:
private_key
(cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKe... | Instantiates an RSA key from bytes.
Args:
bytes (byte string): Bytes of RSA private key.
Returns:
private_key
(cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey):
RSA private key created from key bytes. |
def __get_tax(self, account_id, **kwargs):
"""Call documentation: `/account/get_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#get_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``... | Call documentation: `/account/get_tax
<https://www.wepay.com/developer/reference/account-2011-01-15#get_tax>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... |
def element_data_from_Z(Z):
'''Obtain elemental data given a Z number
An exception is thrown if the Z number is not found
'''
# Z may be a str
if isinstance(Z, str) and Z.isdecimal():
Z = int(Z)
if Z not in _element_Z_map:
raise KeyError('No element data for Z = {}'.format(Z))... | Obtain elemental data given a Z number
An exception is thrown if the Z number is not found |
def _rsa_recover_prime_factors(n, e, d):
"""
Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto.
"""
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a ... | Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto. |
def find_runner(program):
"""Return a command that will run program.
Args:
program: The string name of the program to try to run.
Returns:
commandline list of strings to run the program (eg. with subprocess.call()) or None
"""
if os.path.isfile(program) and not os.access(program, os... | Return a command that will run program.
Args:
program: The string name of the program to try to run.
Returns:
commandline list of strings to run the program (eg. with subprocess.call()) or None |
def setup_versioned_routes(routes, version=None):
"""Set up routes with a version prefix."""
prefix = '/' + version if version else ""
for r in routes:
path, method = r
route(prefix + path, method, routes[r]) | Set up routes with a version prefix. |
def delete_operation(self, name):
"""
Deletes the long-running operation.
.. seealso::
https://cloud.google.com/datastore/docs/reference/data/rest/v1/projects.operations/delete
:param name: the name of the operation resource.
:type name: str
:return: none if... | Deletes the long-running operation.
.. seealso::
https://cloud.google.com/datastore/docs/reference/data/rest/v1/projects.operations/delete
:param name: the name of the operation resource.
:type name: str
:return: none if successful.
:rtype: dict |
def debug_ratelimit(g):
"""Log debug of github ratelimit information from last API call
Parameters
----------
org: github.MainClass.Github
github object
"""
assert isinstance(g, github.MainClass.Github), type(g)
debug("github ratelimit: {rl}".format(rl=g.rate_limiting)) | Log debug of github ratelimit information from last API call
Parameters
----------
org: github.MainClass.Github
github object |
def sort_by_number_values(x00, y00): # pragma: no cover, looks like not used!
"""Compare x00, y00 base on number of values
:param x00: first elem to compare
:type x00: list
:param y00: second elem to compare
:type y00: list
:return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id e... | Compare x00, y00 base on number of values
:param x00: first elem to compare
:type x00: list
:param y00: second elem to compare
:type y00: list
:return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else
:rtype: int |
def config_get(self, param, default=None):
'''Return the value of a git configuration option. This will
return the value of the default parameter (which defaults to
None) if the given option does not exist.'''
try:
return self("config", "--get", param,
... | Return the value of a git configuration option. This will
return the value of the default parameter (which defaults to
None) if the given option does not exist. |
def save(self, filename, binary=True):
"""
Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
... | Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vtr" will select the VTK XML writer.
binary... |
def remove():
"""Function executed when running the script with the -remove switch"""
current = True # only affects current user
root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE
for key in (KEY_C1 % ("", EWS), KEY_C1 % ("NoCon", EWS),
KEY_C0 % ("", EWS), KE... | Function executed when running the script with the -remove switch |
def writelines(lines, filename, encoding='utf-8', mode='wb'):
"""
Write 'lines' to file ('filename') assuming 'encoding'
Return (eventually new) encoding
"""
return write(os.linesep.join(lines), filename, encoding, mode) | Write 'lines' to file ('filename') assuming 'encoding'
Return (eventually new) encoding |
def weed(self):
"""
Get rid of key value pairs that are not standard
"""
_ext = [k for k in self._dict.keys() if k not in self.c_param]
for k in _ext:
del self._dict[k] | Get rid of key value pairs that are not standard |
def get_data(self, path, **params):
""" Giving a service path and optional specific arguments, returns
the XML data from the API parsed as a dict structure.
"""
xml = self.get_response(path, **params)
try:
return parse(xml)
except Exception as err:
... | Giving a service path and optional specific arguments, returns
the XML data from the API parsed as a dict structure. |
def mock_bable(monkeypatch):
""" Mock the BaBLEInterface class with some controllers inside. """
mocked_bable = MockBaBLE()
mocked_bable.set_controllers([
Controller(0, '11:22:33:44:55:66', '#0'),
Controller(1, '22:33:44:55:66:11', '#1', settings={'powered': True, 'low_energy': True}),
... | Mock the BaBLEInterface class with some controllers inside. |
def arraydifference(X,Y):
"""
Elements of a numpy array that do not appear in another.
Fast routine for determining which elements in numpy array `X`
do not appear in numpy array `Y`.
**Parameters**
**X** : numpy array
Numpy array to comapare to numpy array `Y`.
... | Elements of a numpy array that do not appear in another.
Fast routine for determining which elements in numpy array `X`
do not appear in numpy array `Y`.
**Parameters**
**X** : numpy array
Numpy array to comapare to numpy array `Y`.
Return subset of `... |
def _resolve_group_location(self, group: str) -> str:
"""
Resolves the location of a setting file based on the given identifier.
:param group: the identifier for the group's settings file (~its location)
:return: the absolute path of the settings location
"""
if os.path.i... | Resolves the location of a setting file based on the given identifier.
:param group: the identifier for the group's settings file (~its location)
:return: the absolute path of the settings location |
def put(self, local_path, remote_path=None):
"""
Copy a file (or directory recursively) to a location on the remote server
:param local_path: Local path to copy to; can be file or directory
:param remote_path: Remote path to copy to (default: None - Copies file or directory to
... | Copy a file (or directory recursively) to a location on the remote server
:param local_path: Local path to copy to; can be file or directory
:param remote_path: Remote path to copy to (default: None - Copies file or directory to
home directory directory on the remote server) |
def validateSamOptions(options, group=False):
''' Check the validity of the option combinations for sam/bam input '''
if options.per_gene:
if options.gene_tag and options.per_contig:
raise ValueError("need to use either --per-contig "
"OR --gene-tag, please do n... | Check the validity of the option combinations for sam/bam input |
def launch(exec_, args):
"""
Launches application.
"""
if not exec_:
raise RuntimeError(
'Mayalauncher could not find a maya executable, please specify'
'a path in the config file (-e) or add the {} directory location'
'to your PATH system environment.... | Launches application. |
def search(self):
""" This is the most important method """
try:
filters = json.loads(self.query)
except ValueError:
return False
result = self.model_query
if 'filter'in filters.keys():
result = self.parse_filter(filters['filter'])
if ... | This is the most important method |
def get_nan_locs(self, **kwargs):
"""Gets the locations of nans in feature data and returns
the coordinates in the matrix
"""
if np.issubdtype(self.X.dtype, np.string_) or np.issubdtype(self.X.dtype, np.unicode_):
mask = np.where( self.X == '' )
nan_matrix = np.ze... | Gets the locations of nans in feature data and returns
the coordinates in the matrix |
def add_point_region(self, y: float, x: float) -> Graphic:
"""Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.... | Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.
.. versionadded:: 1.0
Scriptable: Yes |
def _unpack(struct, bc, offset=0):
"""
returns the unpacked data tuple, and the next offset past the
unpacked data
"""
return struct.unpack_from(bc, offset), offset + struct.size | returns the unpacked data tuple, and the next offset past the
unpacked data |
def query(self, model_cls):
"""
SQLAlchemy query like method
"""
self._filters_cmd = list()
self.query_filters = list()
self._order_by_cmd = None
self._offset = 0
self._limit = 0
self.query_class = model_cls._name
return self | SQLAlchemy query like method |
def _mark_void(self):
''' Marks the invoice as refunded, and updates the attached cart if
necessary. '''
self.invoice.status = commerce.Invoice.STATUS_VOID
self.invoice.save() | Marks the invoice as refunded, and updates the attached cart if
necessary. |
def open(self, file_path):
"""
Open a SQLite database file.
:param str file_path: SQLite database file path to open.
"""
from simplesqlite import SimpleSQLite
if self.is_opened():
if self.stream.database_path == abspath(file_path):
self._log... | Open a SQLite database file.
:param str file_path: SQLite database file path to open. |
def is_matching_mime_type(self, mime_type):
'''This implements the MIME-type matching logic for deciding whether
to run `make_clean_html`
'''
if len(self.include_mime_types) == 0:
return True
if mime_type is None:
return False
mime_type = mime_typ... | This implements the MIME-type matching logic for deciding whether
to run `make_clean_html` |
def bits(self, count):
"""Reads `count` bits and returns an uint, MSB read first.
May raise BitReaderError if not enough data could be read or
IOError by the underlying file object.
"""
if count < 0:
raise ValueError
if count > self._bits:
n_byt... | Reads `count` bits and returns an uint, MSB read first.
May raise BitReaderError if not enough data could be read or
IOError by the underlying file object. |
def get_gid_list(user, include_default=True):
'''
Returns a list of all of the system group IDs of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
return []
gid_list = list(
six.itervalues(
get_group_dict(user, include_default=include_default)... | Returns a list of all of the system group IDs of which the user
is a member. |
def __get_eval_info(self):
"""Get inner evaluation count and names."""
if self.__need_reload_eval_info:
self.__need_reload_eval_info = False
out_num_eval = ctypes.c_int(0)
# Get num of inner evals
_safe_call(_LIB.LGBM_BoosterGetEvalCounts(
... | Get inner evaluation count and names. |
def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool... | Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. |
def __get_neighbors(self, node_index):
"""!
@brief Returns indexes of neighbors of the specified node.
@param[in] node_index (uint):
@return (list) Neighbors of the specified node.
"""
return [ index for index in range(len(self.__data_p... | !
@brief Returns indexes of neighbors of the specified node.
@param[in] node_index (uint):
@return (list) Neighbors of the specified node. |
def gen_hyper_keys(minion_id,
country='US',
state='Utah',
locality='Salt Lake City',
organization='Salted',
expiration_days='365'):
'''
Generate the keys to be used by libvirt hypervisors, this routine gens
the ke... | Generate the keys to be used by libvirt hypervisors, this routine gens
the keys and applies them to the pillar for the hypervisor minions |
def list_(properties='size,alloc,free,cap,frag,health', zpool=None, parsable=True):
'''
.. versionadded:: 2015.5.0
Return information about (all) storage pools
zpool : string
optional name of storage pool
properties : string
comma-separated list of properties to list
parsable... | .. versionadded:: 2015.5.0
Return information about (all) storage pools
zpool : string
optional name of storage pool
properties : string
comma-separated list of properties to list
parsable : boolean
display numbers in parsable (exact) values
.. versionadded:: 2018.3.... |
def remove(self, dic):
'''remove the pair by passing a identical dict
Args:
dic (dict): key and value
'''
for kw in dic:
removePair = Pair(kw, dic[kw])
self._remove([removePair]) | remove the pair by passing a identical dict
Args:
dic (dict): key and value |
def get_datastores(service_instance, reference, datastore_names=None,
backing_disk_ids=None, get_all_datastores=False):
'''
Returns a list of vim.Datastore objects representing the datastores visible
from a VMware object, filtered by their names, or the backing disk
cannonical name or... | Returns a list of vim.Datastore objects representing the datastores visible
from a VMware object, filtered by their names, or the backing disk
cannonical name or scsi_addresses
service_instance
The Service Instance Object from which to obtain datastores.
reference
The VMware object fro... |
def index_all(self):
"""
Index all records under :attr:`record_path`.
"""
self.logger.debug('Start indexing all records under: %s',
self.record_path)
with self.db.connection():
for json_path in sorted(self.find_record_files()):
... | Index all records under :attr:`record_path`. |
def _identify_heterogeneity_blocks_seg(in_file, seg_file, params, work_dir, somatic_info):
"""Identify heterogeneity blocks corresponding to segmentation from CNV input file.
"""
def _segment_by_cns(target_chrom, freqs, coords):
with open(seg_file) as in_handle:
reader = csv.reader(in_ha... | Identify heterogeneity blocks corresponding to segmentation from CNV input file. |
def _library_check(self):
"""
Checks for missing shared library dependencies in the IOU image.
"""
try:
output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path)
except (FileNotFoundError, subprocess.SubprocessError) as e:
lo... | Checks for missing shared library dependencies in the IOU image. |
def get_content_version(cls, abspath: str) -> str:
"""Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1
"""
data = cls.get_c... | Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The
default implementation is a hash of the file's contents.
.. versionadded:: 3.1 |
def manifest(txt, dname):
"""Extracts file manifest for a body of text with the given directory."""
_, files = _expand_source(txt, dname, HTML)
return files | Extracts file manifest for a body of text with the given directory. |
def plot_one_month(x, y, xlabel=None, ylabel=None, title=None, ylim=None):
"""时间跨度为一月。
major tick = every days
"""
plt.close("all")
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111)
ax.plot(x, y)
days = DayLocator(range(365))
daysFmt = DateFormatter("%Y-%m-... | 时间跨度为一月。
major tick = every days |
def user_save(self):
"""Save the current user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
username = self.user_username_le.text()
first = self.user_first_le.text()
last = self.user_last_le.text()
... | Save the current user
:returns: None
:rtype: None
:raises: None |
def comments(context, obj):
""" Render comments for obj. """
content_type = ContentType.objects.get_for_model(obj.__class__)
comment_list = LogEntry.objects.filter(
content_type=content_type,
object_id=obj.pk,
action_flag=COMMENT
)
return {
'obj': obj,
'commen... | Render comments for obj. |
def rev_after(self, rev: int) -> int:
"""Return the earliest future rev on which the value will change."""
self.seek(rev)
if self._future:
return self._future[-1][0] | Return the earliest future rev on which the value will change. |
def _distarray_no_missing(self, xc, xd):
"""Distance array calculation for data with no missing values. The 'pdist() function outputs a condense distance array, and squareform() converts this vector-form
distance vector to a square-form, redundant distance matrix.
*This could be a target for sav... | Distance array calculation for data with no missing values. The 'pdist() function outputs a condense distance array, and squareform() converts this vector-form
distance vector to a square-form, redundant distance matrix.
*This could be a target for saving memory in the future, by not needing to expand t... |
def render_pyquery(self, **kwargs):
"""Render the graph, and return a pyquery wrapped tree"""
from pyquery import PyQuery as pq
return pq(self.render(**kwargs), parser='html') | Render the graph, and return a pyquery wrapped tree |
def _trim_tree(state):
"""Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed ... | Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed here.
- Removing a leaf n... |
def init(opts):
'''
Open the connection to the network device
managed through netmiko.
'''
proxy_dict = opts.get('proxy', {})
opts['multiprocessing'] = proxy_dict.get('multiprocessing', False)
netmiko_connection_args = proxy_dict.copy()
netmiko_connection_args.pop('proxytype', None)
... | Open the connection to the network device
managed through netmiko. |
def _make_reversed_wildcards(self, old_length=-1):
"""Creates a full mapping from all wildcard translations to the corresponding wildcards"""
if len(self._reversed_wildcards) > 0:
# We already created reversed wildcards, so we don't need to do all of them
# again
star... | Creates a full mapping from all wildcard translations to the corresponding wildcards |
def _handle_exception(self, row, exception):
"""
Logs an exception occurred during transformation of a row.
:param list|dict|() row: The source row.
:param Exception exception: The exception.
"""
self._log('Error during processing of line {0:d}.'.format(self._source_read... | Logs an exception occurred during transformation of a row.
:param list|dict|() row: The source row.
:param Exception exception: The exception. |
def make_cutter(self):
"""
Create solid to subtract from material to make way for the fastener's
head (just the head)
"""
return cadquery.Workplane('XY') \
.circle(self.access_diameter / 2) \
.extrude(self.access_height) | Create solid to subtract from material to make way for the fastener's
head (just the head) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.