code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def assign_rates(self, mu=1.0, pi=None, W=None):
"""
Overwrite the GTR model given the provided data
Parameters
----------
mu : float
Substitution rate
W : nxn matrix
Substitution matrix
pi : n vector
Equilibrium frequenc... | Overwrite the GTR model given the provided data
Parameters
----------
mu : float
Substitution rate
W : nxn matrix
Substitution matrix
pi : n vector
Equilibrium frequencies |
def deregister_entity_from_group(self, entity, group):
'''
Removes entity from group
'''
if entity in self._entities:
if entity in self._groups[group]:
self._groups[group].remove(entity)
else:
raise UnmanagedEntityError(entity) | Removes entity from group |
def get_unique_schema_id(schema):
# type: (GraphQLSchema) -> str
"""Get a unique id given a GraphQLSchema"""
assert isinstance(schema, GraphQLSchema), (
"Must receive a GraphQLSchema as schema. Received {}"
).format(repr(schema))
if schema not in _cached_schemas:
_cached_schemas[sch... | Get a unique id given a GraphQLSchema |
def remove_child_objective_banks(self, objective_bank_id):
"""Removes all children from an objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
raise: NotFound - ``objective_bank_id`` not in hierarchy
raise: NullArgument - ``objective... | Removes all children from an objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
raise: NotFound - ``objective_bank_id`` not in hierarchy
raise: NullArgument - ``objective_bank_id`` is ``null``
raise: OperationFailed - unable to com... |
def updateColumnName(self, networkId, tableType, body, verbose=None):
"""
Renames an existing column in the table specified by the `tableType` and `networkId` parameters.
:param networkId: SUID of the network containing the table
:param tableType: Table Type
:param body: Old and... | Renames an existing column in the table specified by the `tableType` and `networkId` parameters.
:param networkId: SUID of the network containing the table
:param tableType: Table Type
:param body: Old and new column name
:param verbose: print more
:returns: default: successful... |
def BE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''8-bit field, Big endian encoded'''
return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) | 8-bit field, Big endian encoded |
def from_dict(cls, d):
"""
Creates a TransformedStructure from a dict.
"""
s = Structure.from_dict(d)
return cls(s, history=d["history"],
other_parameters=d.get("other_parameters", None)) | Creates a TransformedStructure from a dict. |
def str_id(self):
"str: This key's string id."
id_or_name = self.id_or_name
if id_or_name is not None and isinstance(id_or_name, str):
return id_or_name
return None | str: This key's string id. |
def determine_end_point(http_request, url):
"""
returns detail, list or aggregates
"""
if url.endswith('aggregates') or url.endswith('aggregates/'):
return 'aggregates'
else:
return 'detail' if is_detail_url(http_request, url) else 'list' | returns detail, list or aggregates |
def On_close_criteria_box(self, dia):
"""
after criteria dialog window is closed.
Take the acceptance criteria values and update
self.acceptance_criteria
"""
criteria_list = list(self.acceptance_criteria.keys())
criteria_list.sort()
#---------------------... | after criteria dialog window is closed.
Take the acceptance criteria values and update
self.acceptance_criteria |
def open_stream(stream):
"""Opens a stream and reads 8192 bytes from it.
This is useful to check if a stream actually has data
before opening the output.
"""
global stream_fd
# Attempts to open the stream
try:
stream_fd = stream.open()
except StreamError as err:
raise ... | Opens a stream and reads 8192 bytes from it.
This is useful to check if a stream actually has data
before opening the output. |
def result_to_components(self, result, model, island_data, isflags):
"""
Convert fitting results into a set of components
Parameters
----------
result : lmfit.MinimizerResult
The fitting results.
model : lmfit.Parameters
The model that was fit.
... | Convert fitting results into a set of components
Parameters
----------
result : lmfit.MinimizerResult
The fitting results.
model : lmfit.Parameters
The model that was fit.
island_data : :class:`AegeanTools.models.IslandFittingData`
Data abou... |
def is_local(self):
"""Returns True if the package is in the local package repository"""
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid) | Returns True if the package is in the local package repository |
def suspended_updates():
"""
This allows you to postpone updates to all the search indexes inside of a with:
with suspended_updates():
model1.save()
model2.save()
model3.save()
model4.delete()
"""
if getattr(local_storage, "bulk_queue", None) is N... | This allows you to postpone updates to all the search indexes inside of a with:
with suspended_updates():
model1.save()
model2.save()
model3.save()
model4.delete() |
def recv_raw(self, x=MTU):
"""Receives a packet, then returns a tuple containing (cls, pkt_data, time)""" # noqa: E501
pkt, sa_ll = self.ins.recvfrom(x)
if self.outs and sa_ll[2] == socket.PACKET_OUTGOING:
return None, None, None
ts = get_last_packet_timestamp(self.ins)
... | Receives a packet, then returns a tuple containing (cls, pkt_data, time) |
def GET(self, token=None, **kwargs):
'''
Return a websocket connection of Salt's event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. ... | Return a websocket connection of Salt's event stream
.. http:get:: /ws/(token)
:query format_events: The event stream will undergo server-side
formatting if the ``format_events`` URL parameter is included
in the request. This can be useful to avoid formatting on the
... |
def uniq2orderipix(uniq):
"""
convert a HEALPix pixel coded as a NUNIQ number
to a (norder, ipix) tuple
"""
order = ((np.log2(uniq//4)) // 2)
order = order.astype(int)
ipix = uniq - 4 * (4**order)
return order, ipix | convert a HEALPix pixel coded as a NUNIQ number
to a (norder, ipix) tuple |
def reindex(clear: bool, progressive: bool, batch_size: int):
"""Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to pr... | Reindex all content; optionally clear index before.
All is done in asingle transaction by default.
:param clear: clear index content.
:param progressive: don't run in a single transaction.
:param batch_size: number of documents to process before writing to the
index. Unused in sin... |
def create(name, url, backend, frequency=None, owner=None, org=None):
'''Create a new harvest source'''
log.info('Creating a new Harvest source "%s"', name)
source = actions.create_source(name, url, backend,
frequency=frequency,
owner=own... | Create a new harvest source |
def create_instance(self, body, project_id=None):
"""
Creates a new Cloud SQL instance.
:param body: Body required by the Cloud SQL insert API, as described in
https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/insert#request-body.
:type body: dict
:... | Creates a new Cloud SQL instance.
:param body: Body required by the Cloud SQL insert API, as described in
https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/insert#request-body.
:type body: dict
:param project_id: Project ID of the project that contains the instance... |
def deltran(tree, feature):
"""
DELTRAN (delayed transformation) (Swofford & Maddison, 1987) aims at reducing the number of ambiguities
in the parsimonious result. DELTRAN makes the changes as close as possible to the leaves,
hence prioritizing parallel mutations. DELTRAN is performed after DOWNPASS.
... | DELTRAN (delayed transformation) (Swofford & Maddison, 1987) aims at reducing the number of ambiguities
in the parsimonious result. DELTRAN makes the changes as close as possible to the leaves,
hence prioritizing parallel mutations. DELTRAN is performed after DOWNPASS.
if N is not a root:
P <- pare... |
def linkify_h_by_hg(self, hostgroups):
"""Link hosts with hostgroups
:param hostgroups: hostgroups object to link with
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: None
"""
# Register host in the hostgroups
for host in self:
new_hos... | Link hosts with hostgroups
:param hostgroups: hostgroups object to link with
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: None |
def transform_file_output(result):
""" Transform to convert SDK file/dir list output to something that
more clearly distinguishes between files and directories. """
from collections import OrderedDict
new_result = []
iterable = result if isinstance(result, list) else result.get('items', result)
... | Transform to convert SDK file/dir list output to something that
more clearly distinguishes between files and directories. |
def get_display(display):
"""dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protocol to use (None if automatic)
H... | dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protocol to use (None if automatic)
HOST -- the host name (string,... |
def get_pstats(pstatfile, n):
"""
Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve
"""
with tempfile.TemporaryFile(mode='w+') as stream:
ps = pstats.Stats(pstatfile, stream=stream)
ps.sort_sta... | Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve |
def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):
"""
See ``authenticate_with_certificate_chain``.
:param pem.Certificate client_cert: The client certificate to use.
"""
return authenticate_with_certificate_chain(
reactor, base_url, [client_cert], clien... | See ``authenticate_with_certificate_chain``.
:param pem.Certificate client_cert: The client certificate to use. |
def sio(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
samp_infile="", institution="", syn=False, syntype="", instrument="",
labfield=0, phi=0, theta=0, peakfiel... | converts Scripps Institution of Oceanography measurement files to MagIC data base model 3.0
Parameters
_________
magfile : input measurement file
dir_path : output directory path, default "."
input_dir_path : input file directory IF different from dir_path, default ""
meas_file : output file me... |
def get_timerange_formatted(self, now):
"""
Return two ISO8601 formatted date strings, one for timeMin, the other for timeMax (to be consumed by get_events)
"""
later = now + datetime.timedelta(days=self.days)
return now.isoformat(), later.isoformat() | Return two ISO8601 formatted date strings, one for timeMin, the other for timeMax (to be consumed by get_events) |
def list_traces(
self,
project_id,
view=None,
page_size=None,
start_time=None,
end_time=None,
filter_=None,
order_by=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None... | Returns of a list of traces that match the specified filter conditions.
Example:
>>> from google.cloud import trace_v1
>>>
>>> client = trace_v1.TraceServiceClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
... |
def get_values(self, obj):
"""get label and shape for classes.
The label contains all attributes and methods
"""
if is_exception(obj.node):
label = r"\fb\f09%s\fn" % obj.title
else:
label = r"\fb%s\fn" % obj.title
if obj.shape == "interface":
... | get label and shape for classes.
The label contains all attributes and methods |
def flag_forgotten_entries(session, today=None):
"""Flag any entries from previous days where users forgot to sign
out.
:param session: SQLAlchemy session through which to access the database.
:param today: (optional) The current date as a `datetime.date` object. Used for testing.
""" # noqa
to... | Flag any entries from previous days where users forgot to sign
out.
:param session: SQLAlchemy session through which to access the database.
:param today: (optional) The current date as a `datetime.date` object. Used for testing. |
def step_forward_with_function(self, uv0fun, uv1fun, dt):
"""Advance particles using a function to determine u and v.
Parameters
----------
uv0fun : function
Called like ``uv0fun(x,y)``. Should return the velocity field
u, v at time t.
uv1fun(x,y)... | Advance particles using a function to determine u and v.
Parameters
----------
uv0fun : function
Called like ``uv0fun(x,y)``. Should return the velocity field
u, v at time t.
uv1fun(x,y) : function
Called like ``uv1fun(x,y)``. Should return th... |
def scale_rows(A, v, copy=True):
"""Scale the sparse rows of a matrix.
Parameters
----------
A : sparse matrix
Sparse matrix with M rows
v : array_like
Array of M scales
copy : {True,False}
- If copy=True, then the matrix is copied to a new and different return
... | Scale the sparse rows of a matrix.
Parameters
----------
A : sparse matrix
Sparse matrix with M rows
v : array_like
Array of M scales
copy : {True,False}
- If copy=True, then the matrix is copied to a new and different return
matrix (e.g. B=scale_rows(A,v))
... |
def stack_memory(data, n_steps=2, delay=1, **kwargs):
"""Short-term history embedding: vertically concatenate a data
vector or matrix with delayed copies of itself.
Each column `data[:, i]` is mapped to::
data[:, i] -> [data[:, i],
data[:, i - delay],
... | Short-term history embedding: vertically concatenate a data
vector or matrix with delayed copies of itself.
Each column `data[:, i]` is mapped to::
data[:, i] -> [data[:, i],
data[:, i - delay],
...
data[:, i - (n_steps-1)*delay]... |
def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7):
"""Function to fetch and process MODSCAG fractional snow cover products for input datetime
Products are tiled in MODIS sinusoidal projection
example url: https://snow-data.jpl.nasa.gov/modscag-histor... | Function to fetch and process MODSCAG fractional snow cover products for input datetime
Products are tiled in MODIS sinusoidal projection
example url: https://snow-data.jpl.nasa.gov/modscag-historic/2015/001/MOD09GA.A2015001.h07v03.005.2015006001833.snow_fraction.tif |
def get_user_profile_photos(self, user_id, offset=None, limit=None):
"""
Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Uniqu... | Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
https://core.telegram.org/bots/api#getuserprofilephotos
Parameters:
:param user_id: Unique identifier of the target user
:type user_id: int
Opt... |
def synced(func):
'''
Decorator for functions that should be called synchronously from another thread
:param func: function to call
'''
def wrapper(self, *args, **kwargs):
'''
Actual wrapper for the synchronous function
'''
task = DataManagerTask(func, *args, **kwar... | Decorator for functions that should be called synchronously from another thread
:param func: function to call |
def validate_bool(b):
"""Convert b to a boolean or raise"""
if isinstance(b, six.string_types):
b = b.lower()
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
raise ValueEr... | Convert b to a boolean or raise |
def trees_by_subpath(self, sub_path):
"""
Search trees by `sub_path` using ``Tree.path.startswith(sub_path)``
comparison.
Args:
sub_path (str): Part of the :attr:`.Tree.path` property of
:class:`.Tree`.
Returns:
set: Set of matching :clas... | Search trees by `sub_path` using ``Tree.path.startswith(sub_path)``
comparison.
Args:
sub_path (str): Part of the :attr:`.Tree.path` property of
:class:`.Tree`.
Returns:
set: Set of matching :class:`Tree` instances. |
def preprocess_source(base_dir=os.curdir):
"""
A special method for convert all source files to compatible with current
python version during installation time.
The source directory layout must like this :
base_dir --+
|
+-- src (All sources are placed into t... | A special method for convert all source files to compatible with current
python version during installation time.
The source directory layout must like this :
base_dir --+
|
+-- src (All sources are placed into this directory)
|
+-- prep... |
def sync_imports( self, quiet = False ):
"""Return a context manager to control imports onto all the engines
in the underlying cluster. This method is used within a ``with`` statement.
Any imports should be done with no experiments running, otherwise the
method will block until the clus... | Return a context manager to control imports onto all the engines
in the underlying cluster. This method is used within a ``with`` statement.
Any imports should be done with no experiments running, otherwise the
method will block until the cluster is quiet. Generally imports will be one
... |
def gradient(self):
"""
Derivative of the covariance matrix over the lower triangular, flat part of L.
It is equal to
∂K/∂Lᵢⱼ = ALᵀ + LAᵀ,
where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1.
Returns
-------
Lu : ndarray
Derivative ... | Derivative of the covariance matrix over the lower triangular, flat part of L.
It is equal to
∂K/∂Lᵢⱼ = ALᵀ + LAᵀ,
where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1.
Returns
-------
Lu : ndarray
Derivative of K over the lower-triangular, flat par... |
def clamp(inclusive_lower_bound: int,
inclusive_upper_bound: int,
value: int) -> int:
"""
Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``.
"""
if value <= inclusive_lower_bound:
return inclusive_lower_bound
elif value >= inclu... | Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``. |
def init(filename=ConfigPath):
"""Loads INI configuration into this module's attributes."""
section, parts = "DEFAULT", filename.rsplit(":", 1)
if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
if not os.path.isfile(filename): return
vardict, parser = globals(), config... | Loads INI configuration into this module's attributes. |
def createFromSource(cls, vs, name=None):
''' returns a github component for any github url (including
git+ssh:// git+http:// etc. or None if this is not a Github URL.
For all of these we use the github api to grab a tarball, because
that's faster.
Normally versi... | returns a github component for any github url (including
git+ssh:// git+http:// etc. or None if this is not a Github URL.
For all of these we use the github api to grab a tarball, because
that's faster.
Normally version will be empty, unless the original url was of the
... |
def _concat_reps(self, kpop, max_var_multiple, quiet, **kwargs):
"""
Combine structure replicates into a single indfile,
returns nreps, ninds. Excludes reps with too high of
variance (set with max_variance_multiplier) to exclude
runs that did not converge.
"""
## make an output handle... | Combine structure replicates into a single indfile,
returns nreps, ninds. Excludes reps with too high of
variance (set with max_variance_multiplier) to exclude
runs that did not converge. |
def correct_structure(self, atol=1e-8):
"""Determine if the structure matches the standard primitive structure.
The standard primitive will be different between seekpath and pymatgen
high-symmetry paths, but this is handled by the specific subclasses.
Args:
atol (:obj:`floa... | Determine if the structure matches the standard primitive structure.
The standard primitive will be different between seekpath and pymatgen
high-symmetry paths, but this is handled by the specific subclasses.
Args:
atol (:obj:`float`, optional): Absolute tolerance used to compare
... |
def _y_axis(self, draw_axes=True):
"""Override y axis to make it polar"""
if not self._y_labels or not self.show_y_labels:
return
axis = self.svg.node(self.nodes['plot'], class_="axis y web")
for label, r in reversed(self._y_labels):
major = r in self._y_labels_... | Override y axis to make it polar |
def retrieve(cls, *args, **kwargs):
"""Return parent method."""
return super(BankAccount, cls).retrieve(*args, **kwargs) | Return parent method. |
def transition_loop(n_states, prob):
'''Construct a self-loop transition matrix over `n_states`.
The transition matrix will have the following properties:
- `transition[i, i] = p` for all i
- `transition[i, j] = (1 - p) / (n_states - 1)` for all `j != i`
This type of transition matrix is ... | Construct a self-loop transition matrix over `n_states`.
The transition matrix will have the following properties:
- `transition[i, i] = p` for all i
- `transition[i, j] = (1 - p) / (n_states - 1)` for all `j != i`
This type of transition matrix is appropriate when states tend to be
local... |
def split_string(self, string):
""" Yields substrings for which the same escape code applies.
"""
self.actions = []
start = 0
# strings ending with \r are assumed to be ending in \r\n since
# \n is appended to output strings automatically. Accounting
# for that,... | Yields substrings for which the same escape code applies. |
def generate_api_key(self):
"""
Creates and returns a new API Key/pass pair.
:returns: API key/pass pair in JSON format
"""
endpoint = '/'.join((self.server_url, '_api', 'v2', 'api_keys'))
resp = self.r_session.post(endpoint)
resp.raise_for_status()
retur... | Creates and returns a new API Key/pass pair.
:returns: API key/pass pair in JSON format |
def resolveFilenameConflicts(self):
"""Goes through list of DPs to make sure that their destination names
do not clash. Adjust names as needed. Returns True if some conflicts were resolved.
"""
taken_names = set()
resolved = False
# iterate through items
for item,... | Goes through list of DPs to make sure that their destination names
do not clash. Adjust names as needed. Returns True if some conflicts were resolved. |
def list_active_vms(cwd=None):
'''
Return a list of machine names for active virtual machine on the host,
which are defined in the Vagrantfile at the indicated path.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_active_vms cwd=/projects/project_1
'''
vms = []
cmd = ... | Return a list of machine names for active virtual machine on the host,
which are defined in the Vagrantfile at the indicated path.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_active_vms cwd=/projects/project_1 |
def rolling_restart(self, slave_batch_size=None,
slave_fail_count_threshold=None,
sleep_seconds=None,
stale_configs_only=None,
unupgraded_only=None,
restart_role_types=None,
restart_role_n... | Rolling restart the roles of a service. The sequence is:
1. Restart all the non-slave roles
2. If slaves are present restart them in batches of size specified
3. Perform any post-command needed after rolling restart
@param slave_batch_size: Number of slave roles to restart at a time
Mu... |
def _calculate_gas(owners: List[str], safe_setup_data: bytes, payment_token: str) -> int:
"""
Calculate gas manually, based on tests of previosly deployed safes
:param owners: Safe owners
:param safe_setup_data: Data for proxy setup
:param payment_token: If payment token, we will... | Calculate gas manually, based on tests of previosly deployed safes
:param owners: Safe owners
:param safe_setup_data: Data for proxy setup
:param payment_token: If payment token, we will need more gas to transfer and maybe storage if first time
:return: total gas needed for deployment |
def configure_logger(logger, filename, folder, log_level):
'''Configure logging behvior for the simulations.
'''
fmt = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
if folder is not None:
log_file = os.path.join(folder, filename)
hdl = logging.FileHandler(log_file)
... | Configure logging behvior for the simulations. |
def sh3(cmd):
"""Execute command in a subshell, return stdout, stderr
If anything appears in stderr, print it out to sys.stderr"""
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True,
env=sub_environment())
out, err = p.communicate()
retcode = p.returncode
if retcode:
rais... | Execute command in a subshell, return stdout, stderr
If anything appears in stderr, print it out to sys.stderr |
def write_hash_file_for_path(path, recompute=False):
r""" Creates a hash file for each file in a path
CommandLine:
python -m utool.util_hash --test-write_hash_file_for_path
Example:
>>> # DISABLE_DOCTEST
>>> import os
>>> import utool as ut
>>> from utool.util_hash ... | r""" Creates a hash file for each file in a path
CommandLine:
python -m utool.util_hash --test-write_hash_file_for_path
Example:
>>> # DISABLE_DOCTEST
>>> import os
>>> import utool as ut
>>> from utool.util_hash import * # NOQA
>>> fpath = ut.grab_test_imgpath... |
def _emit_message(cls, message):
"""Print a message to STDOUT."""
sys.stdout.write(message)
sys.stdout.flush() | Print a message to STDOUT. |
def get_path(filename):
"""
Get absolute path for filename.
:param filename: file
:return: path
"""
path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename))
return path | Get absolute path for filename.
:param filename: file
:return: path |
def getISAAssay(assayNum, studyNum, pathToISATABFile):
"""
This function returns an Assay object given the assay and study numbers in an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the assay and study numbers you are interested in!
:p... | This function returns an Assay object given the assay and study numbers in an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the assay and study numbers you are interested in!
:param assayNum: The Assay number (notice it's not zero-based index).... |
def oidcCredentials(self, *args, **kwargs):
"""
Get Taskcluster credentials given a suitable `access_token`
Given an OIDC `access_token` from a trusted OpenID provider, return a
set of Taskcluster credentials for use on behalf of the identified
user.
This method is typi... | Get Taskcluster credentials given a suitable `access_token`
Given an OIDC `access_token` from a trusted OpenID provider, return a
set of Taskcluster credentials for use on behalf of the identified
user.
This method is typically not called with a Taskcluster client library
and d... |
def get_id(self):
'''
:returns: Object ID of associated app
:rtype: string
Returns the object ID of the app that the handler is currently
associated with.
'''
if self._dxid is not None:
return self._dxid
else:
return 'app-' + self.... | :returns: Object ID of associated app
:rtype: string
Returns the object ID of the app that the handler is currently
associated with. |
def _render_having(having_conditions):
"""Render the having part of a query.
Parameters
----------
having_conditions : list
A ``list`` of ``dict``s to filter the rows
Returns
-------
str
A string that represents the "having" part of a query.
See Also
--------
r... | Render the having part of a query.
Parameters
----------
having_conditions : list
A ``list`` of ``dict``s to filter the rows
Returns
-------
str
A string that represents the "having" part of a query.
See Also
--------
render_query : Further clarification of `condit... |
def problem(self):
"""
| Comment: For tickets of type "incident", the ID of the problem the incident is linked to
"""
if self.api and self.problem_id:
return self.api._get_problem(self.problem_id) | | Comment: For tickets of type "incident", the ID of the problem the incident is linked to |
def token_scan(cls, result_key, token):
"""
Define a property that is set to true if the given token is found in
the log file. Uses the __contains__ method of the log file.
"""
def _scan(self):
return token in self
cls.scan(result_key, _scan) | Define a property that is set to true if the given token is found in
the log file. Uses the __contains__ method of the log file. |
def n_executions(self):
"""
Queries and returns the number of past task executions.
"""
pipeline = self.tiger.connection.pipeline()
pipeline.exists(self.tiger._key('task', self.id))
pipeline.llen(self.tiger._key('task', self.id, 'executions'))
exists, n_executions... | Queries and returns the number of past task executions. |
def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, verbosity=0, keep_logs=False, **kwargs):
"""Re-submit jobs automatically"""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
... | Re-submit jobs automatically |
def make_display_lines(self):
"""
生成输出行
注意: 多线程终端同时输出会有bug, 导致起始位置偏移, 需要在每行加\r
"""
self.screen_height, self.screen_width = self.linesnum() # 屏幕显示行数
display_lines = ['\r']
display_lines.append(self._title + '\r')
top = self.topline
bottom = self... | 生成输出行
注意: 多线程终端同时输出会有bug, 导致起始位置偏移, 需要在每行加\r |
def _decrypt(private_key, ciphertext, padding):
"""
Decrypts RSA ciphertext using a private key
:param private_key:
A PrivateKey object
:param ciphertext:
The ciphertext - a byte string
:param padding:
The padding mode to use, specified as a kSecPadding*Key value
:rai... | Decrypts RSA ciphertext using a private key
:param private_key:
A PrivateKey object
:param ciphertext:
The ciphertext - a byte string
:param padding:
The padding mode to use, specified as a kSecPadding*Key value
:raises:
ValueError - when any of the parameters contain... |
def get_all_player_ids(ids="shots"):
"""
Returns a pandas DataFrame containing the player IDs used in the
stats.nba.com API.
Parameters
----------
ids : { "shots" | "all_players" | "all_data" }, optional
Passing in "shots" returns a DataFrame that contains the player IDs of
all ... | Returns a pandas DataFrame containing the player IDs used in the
stats.nba.com API.
Parameters
----------
ids : { "shots" | "all_players" | "all_data" }, optional
Passing in "shots" returns a DataFrame that contains the player IDs of
all players have shot chart data. It is the default ... |
def get_gtf_db(gtf, in_memory=False):
"""
create a gffutils DB, in memory if we don't have write permissions
"""
db_file = gtf + ".db"
if file_exists(db_file):
return gffutils.FeatureDB(db_file)
if not os.access(os.path.dirname(db_file), os.W_OK | os.X_OK):
in_memory = True
d... | create a gffutils DB, in memory if we don't have write permissions |
def X_less(self):
"""Zoom out on the x-axis."""
self.parent.value('window_length',
self.parent.value('window_length') / 2)
self.parent.overview.update_position() | Zoom out on the x-axis. |
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256):
"""
Truncates a colormap, such that the new colormap consists of
``cmap[minval:maxval]``.
If maxval is larger than minval, the truncated colormap will be reversed.
Args:
cmap (colormap): Colormap to be truncated
minval (float)... | Truncates a colormap, such that the new colormap consists of
``cmap[minval:maxval]``.
If maxval is larger than minval, the truncated colormap will be reversed.
Args:
cmap (colormap): Colormap to be truncated
minval (float): Lower bound. Should be a float betwee 0 and 1.
maxval (float): U... |
def GetPlaylists(self, start, max_count, order, reversed):
"""Gets a set of playlists.
:param int start: The index of the first playlist to be fetched
(according to the ordering).
:param int max_count: The maximum number of playlists to fetch.
:param str order... | Gets a set of playlists.
:param int start: The index of the first playlist to be fetched
(according to the ordering).
:param int max_count: The maximum number of playlists to fetch.
:param str order: The ordering that should be used.
:param bool reversed: Whet... |
def add(self, subj: Node, pred: URIRef, obj: Node) -> "FHIRResource":
"""
Shortcut to rdflib add function
:param subj:
:param pred:
:param obj:
:return: self for chaining
"""
self._g.add((subj, pred, obj))
return self | Shortcut to rdflib add function
:param subj:
:param pred:
:param obj:
:return: self for chaining |
def _generate_ndarray_function_code(handle, name, func_name, signature_only=False):
"""Generate function for ndarray op by handle and function name."""
real_name = ctypes.c_char_p()
desc = ctypes.c_char_p()
num_args = mx_uint()
arg_names = ctypes.POINTER(ctypes.c_char_p)()
arg_types = ctypes.POI... | Generate function for ndarray op by handle and function name. |
def sh2(cmd):
"""Execute command in a subshell, return stdout.
Stderr is unbuffered from the subshell.x"""
p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment())
out = p.communicate()[0]
retcode = p.returncode
if retcode:
raise CalledProcessError(retcode, cmd)
else:
... | Execute command in a subshell, return stdout.
Stderr is unbuffered from the subshell.x |
def deflections_from_grid(self, grid, tabulate_bins=1000):
"""
Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed... | Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
tabulate_bins : int
The number of bins to tabulate the... |
def flag(val):
"""Does the value look like an on/off flag?"""
if val == 1:
return True
elif val == 0:
return False
val = str(val)
if len(val) > 5:
return False
return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF') | Does the value look like an on/off flag? |
def on_bindok(self, unused_frame):
"""
This method is invoked by pika when it receives the Queue.BindOk
response from RabbitMQ.
"""
self._logger.info('Queue bound')
while not self._stopping:
# perform the action that publishes on this client
self.p... | This method is invoked by pika when it receives the Queue.BindOk
response from RabbitMQ. |
def get_traindata(self) -> np.ndarray:
"""
Pulls all available data and concatenates for model training
:return: 2d array of points
"""
traindata = None
for key, value in self.data.items():
if key not in ['__header__', '__version__', '__globals__']:
... | Pulls all available data and concatenates for model training
:return: 2d array of points |
def get_class_name(self):
"""
Return the class name of the field
:rtype: string
"""
if self.class_idx_value is None:
self.class_idx_value = self.CM.get_type(self.class_idx)
return self.class_idx_value | Return the class name of the field
:rtype: string |
def make_full_url(request, url):
"""Get a relative URL and returns the absolute version.
Eg: “/foo/bar?q=is-open” ==> “http://example.com/foo/bar?q=is-open”
"""
urlparts = request.urlparts
return '{scheme}://{site}/{url}'.format(
scheme=urlparts.scheme,
site=get_site_name(request),
... | Get a relative URL and returns the absolute version.
Eg: “/foo/bar?q=is-open” ==> “http://example.com/foo/bar?q=is-open” |
def _get_descriptors(self):
"""Returns three elements tuple with socket descriptors ready
for gevent.select.select
"""
rlist = []
wlist = []
xlist = []
for socket, flags in self.sockets.items():
if isinstance(socket, zmq.Socket):
rlist... | Returns three elements tuple with socket descriptors ready
for gevent.select.select |
def zip(self, *others):
"""
Zip the items of this collection with one or more
other sequences, and wrap the result.
Unlike Python's zip, all sequences must be the same length.
Parameters:
others: One or more iterables or Collections
Returns:
A... | Zip the items of this collection with one or more
other sequences, and wrap the result.
Unlike Python's zip, all sequences must be the same length.
Parameters:
others: One or more iterables or Collections
Returns:
A new collection.
Examples:
... |
def has_permission(self, request, view):
"""Check list and create permissions based on sign and filters."""
if view.suffix == 'Instance':
return True
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
... | Check list and create permissions based on sign and filters. |
def loop(self, timeout=1.0, max_packets=1):
"""Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
p... | Process network events.
This function must be called regularly to ensure communication with the
broker is carried out. It calls select() on the network socket to wait
for network events. If incoming data is present it will then be
processed. Outgoing commands, from e.g. publish(), are n... |
def main():
'''main entry'''
cli = docker.from_env()
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "pcv", ["pretty", "compose"])
except getopt.GetoptError as _:
print("Usage: docker-parse [--pretty|-p|--compose|-c] [containers]")
sys.exit(2)
if len(args) == 0:
... | main entry |
def _get_args_contents(self):
"""
Mimic the argument formatting behaviour of
ActionBase._execute_module().
"""
return ' '.join(
'%s=%s' % (key, shlex_quote(str(self.args[key])))
for key in self.args
) + ' ' | Mimic the argument formatting behaviour of
ActionBase._execute_module(). |
def area(self, chord_length=1e-4):
"""Find area enclosed by path.
Approximates any Arc segments in the Path with lines
approximately `chord_length` long, and returns the area enclosed
by the approximated Path. Default chord length is 0.01. If Arc
segments are included ... | Find area enclosed by path.
Approximates any Arc segments in the Path with lines
approximately `chord_length` long, and returns the area enclosed
by the approximated Path. Default chord length is 0.01. If Arc
segments are included in path, to ensure accurate results, make
... |
def modify(self, service_name, json, **kwargs):
"""Modify an AppNexus object"""
return self._send(requests.put, service_name, json, **kwargs) | Modify an AppNexus object |
def deserialize_profile(profile, key_prefix='', pop=False):
"""De-serialize user profile fields into concrete model fields."""
result = {}
if pop:
getter = profile.pop
else:
getter = profile.get
def prefixed(name):
"""Return name prefixed by `... | De-serialize user profile fields into concrete model fields. |
async def presentProof(self, proofRequest: ProofRequest) -> FullProof:
"""
Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revoca... | Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values) |
def process_stats(self, stats, prefix, metric_categories, nested_tags, tags, recursion_level=0):
"""
The XML will have Stat Nodes and Nodes that contain the metrics themselves
This code recursively goes through each Stat Node to properly setup tags
where each Stat will have a different t... | The XML will have Stat Nodes and Nodes that contain the metrics themselves
This code recursively goes through each Stat Node to properly setup tags
where each Stat will have a different tag key depending on the context. |
def depth(self, value):
""" Update ourself and any of our subcommands. """
for command in self.subcommands.values():
command.depth = value + 1
del command.argparser._defaults[self.arg_label_fmt % self._depth]
command.argparser._defaults[self.arg_label_fmt % value] = c... | Update ourself and any of our subcommands. |
def _make_pheno_assoc(
self, graph, gene_id, disorder_num, disorder_label, phene_key
):
"""
From the docs:
Brackets, "[ ]", indicate "nondiseases," mainly genetic variations
that lead to apparently abnormal laboratory test values
(e.g., dysalbuminemic euthyroidal... | From the docs:
Brackets, "[ ]", indicate "nondiseases," mainly genetic variations
that lead to apparently abnormal laboratory test values
(e.g., dysalbuminemic euthyroidal hyperthyroxinemia).
Braces, "{ }", indicate mutations that contribute to susceptibility
to multifactorial d... |
def _recon_lcs(x, y):
"""
Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns:
sequence: LCS of x and y
"""
i, j = len(x), len(y)
table = _lcs... | Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns:
sequence: LCS of x and y |
def get_instance(cls, dependencies=None):
"""
Return an instance for a contract name.
:param dependencies:
:return: Contract base instance
"""
assert cls is not ContractBase, 'ContractBase is not meant to be used directly.'
assert cls.CONTRACT_NAME, 'CONTRACT_NAM... | Return an instance for a contract name.
:param dependencies:
:return: Contract base instance |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.