code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def threshold_img(data, threshold, mask=None, mask_out='below'):
""" Threshold data, setting all values in the array above/below threshold
to zero.
Args:
data (ndarray): The image data to threshold.
threshold (float): Numeric threshold to apply to image.
mask (ndarray): Optional 1D-a... | Threshold data, setting all values in the array above/below threshold
to zero.
Args:
data (ndarray): The image data to threshold.
threshold (float): Numeric threshold to apply to image.
mask (ndarray): Optional 1D-array with the same length as the data. If
passed, the thresho... |
def devices(self):
"""
Return a list of connected devices in the form (*serial*, *status*) where status can
be any of the following:
1. device
2. offline
3. unauthorized
:returns: A list of tuples representing connected devices
"""
devices = None... | Return a list of connected devices in the form (*serial*, *status*) where status can
be any of the following:
1. device
2. offline
3. unauthorized
:returns: A list of tuples representing connected devices |
def _get_griddistrict(ding0_filepath):
"""
Just get the grid district number from ding0 data file path
Parameters
----------
ding0_filepath : str
Path to ding0 data ending typically
`/path/to/ding0_data/"ding0_grids__" + str(``grid_district``) + ".xxx"`
Returns
-------
i... | Just get the grid district number from ding0 data file path
Parameters
----------
ding0_filepath : str
Path to ding0 data ending typically
`/path/to/ding0_data/"ding0_grids__" + str(``grid_district``) + ".xxx"`
Returns
-------
int
grid_district number |
def validate_scopes(self, client_id, scopes, client, request,
*args, **kwargs):
"""Ensure the client is authorized access to requested scopes."""
if hasattr(client, 'validate_scopes'):
return client.validate_scopes(scopes)
return set(client.default_scopes).iss... | Ensure the client is authorized access to requested scopes. |
def create_spot_instances(ec2, price, image_id, spec, num_instances=1, timeout=None, tentative=False, tags=None):
"""
:rtype: Iterator[list[Instance]]
"""
def spotRequestNotFound(e):
return e.error_code == "InvalidSpotInstanceRequestID.NotFound"
for attempt in retry_ec2(retry_for=a_long_tim... | :rtype: Iterator[list[Instance]] |
def as_dict(self):
"""
ping statistics.
Returns:
|dict|:
Examples:
>>> import pingparsing
>>> parser = pingparsing.PingParsing()
>>> parser.parse(ping_result)
>>> parser.as_dict()
{
"destination": "... | ping statistics.
Returns:
|dict|:
Examples:
>>> import pingparsing
>>> parser = pingparsing.PingParsing()
>>> parser.parse(ping_result)
>>> parser.as_dict()
{
"destination": "google.com",
"packet_tr... |
def disable(self):
""" Relieve all state machines that have no active execution and hide the widget """
self.ticker_text_label.hide()
if self.current_observed_sm_m:
self.stop_sm_m_observation(self.current_observed_sm_m) | Relieve all state machines that have no active execution and hide the widget |
def add_api_compression(self, api_id, min_compression_size):
"""
Add Rest API compression
"""
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
'op': 'replace',
'path': '/minimumCo... | Add Rest API compression |
def _profile(self, frame, event, arg):
"""The callback function to register by :func:`sys.setprofile`."""
# c = event.startswith('c_')
if event.startswith('c_'):
return
time1 = self.timer()
frames = self.frame_stack(frame)
if frames:
frames.pop()
... | The callback function to register by :func:`sys.setprofile`. |
def unmount(self, client):
"""Unmounts a backend within Vault"""
getattr(client, self.unmount_fun)(mount_point=self.path) | Unmounts a backend within Vault |
def check_version(server, version, filename, timeout=SHORT_TIMEOUT):
"""Check for the latest version of OK and update accordingly."""
address = VERSION_ENDPOINT.format(server=server)
print('Checking for software updates...')
log.info('Existing OK version: %s', version)
log.info('Checking latest ve... | Check for the latest version of OK and update accordingly. |
def _stinespring_to_choi(data, input_dim, output_dim):
"""Transform Stinespring representation to Choi representation."""
trace_dim = data[0].shape[0] // output_dim
stine_l = np.reshape(data[0], (output_dim, trace_dim, input_dim))
if data[1] is None:
stine_r = stine_l
else:
stine_r =... | Transform Stinespring representation to Choi representation. |
def _cdf(self, xloc, left, right, cache):
"""
Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Add(chaospy.Uniform(), 1).fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0. 0.5... | Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Add(chaospy.Uniform(), 1).fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0. 0.5 1. ]
>>> print(chaospy.Add(1, chaospy.Uniform()).... |
def dup_idx(arr):
"""Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from ... | Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from root_numpy import dup_idx... |
def get_feature_sequence(self, feature_id, organism=None, sequence=None):
"""
[CURRENTLY BROKEN] Get the sequence of a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
... | [CURRENTLY BROKEN] Get the sequence of a feature
:type feature_id: str
:param feature_id: Feature UUID
:type organism: str
:param organism: Organism Common Name
:type sequence: str
:param sequence: Sequence Name
:rtype: dict
:return: A standard apollo ... |
def SelfReferenceProperty(label=None, collection_name=None, **attrs):
"""Create a self reference.
"""
if 'reference_class' in attrs:
raise ConfigurationError(
'Do not provide reference_class to self-reference.')
return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **... | Create a self reference. |
def update(self):
'''Update definitions.'''
# Download http://rebase.neb.com/rebase/link_withref to tmp
self._tmpdir = tempfile.mkdtemp()
try:
self._rebase_file = self._tmpdir + '/rebase_file'
print 'Downloading latest enzyme definitions'
url = 'http:/... | Update definitions. |
def mktmp(self):
"""
Make the I{location} directory if it doesn't already exits.
"""
try:
if not os.path.isdir(self.location):
os.makedirs(self.location)
except:
log.debug(self.location, exc_info=1)
return self | Make the I{location} directory if it doesn't already exits. |
def _call_variants_samtools(align_bams, ref_file, items, target_regions, tx_out_file):
"""Call variants with samtools in target_regions.
Works around a GATK VCF 4.2 compatibility issue in samtools 1.0
by removing addition 4.2-only isms from VCF header lines.
"""
config = items[0]["config"]
mpil... | Call variants with samtools in target_regions.
Works around a GATK VCF 4.2 compatibility issue in samtools 1.0
by removing addition 4.2-only isms from VCF header lines. |
def action_create(self, courseid, taskid, path):
""" Delete a file or a directory """
# the path is given by the user. Let's normalize it
path = path.strip()
if not path.startswith("/"):
path = "/" + path
want_directory = path.endswith("/")
wanted_path = sel... | Delete a file or a directory |
def set_device_name(self, newname):
""" Sets internal device name. (not announced bluetooth name).
requires utf-8 encoded string. """
return self.write(request.SetDeviceName(self.seq, *self.prep_str(newname))) | Sets internal device name. (not announced bluetooth name).
requires utf-8 encoded string. |
def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True):
"""Construct many rest-of-world geometries and optionally write to filepath ``fp``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``."""
geoms = {}
... | Construct many rest-of-world geometries and optionally write to filepath ``fp``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``. |
def parse_qtype(self, param_type, param_value):
'''parse type of quniform or qloguniform'''
if param_type == 'quniform':
return self._parse_quniform(param_value)
if param_type == 'qloguniform':
param_value[:2] = np.log(param_value[:2])
return list(np.exp(self.... | parse type of quniform or qloguniform |
def _integrate_scipy(self, intern_xout, intern_y0, intern_p,
atol=1e-8, rtol=1e-8, first_step=None, with_jacobian=None,
force_predefined=False, name=None, **kwargs):
""" Do not use directly (use ``integrate('scipy', ...)``).
Uses `scipy.integrate.ode <h... | Do not use directly (use ``integrate('scipy', ...)``).
Uses `scipy.integrate.ode <http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html>`_
Parameters
----------
\*args :
See :meth:`integrate`.
name : str (default: 'lsoda'/'dopri5' when jacobia... |
def from_dict(config):
'''
Instantiate a new ProxyConfig from a dictionary that represents a
client configuration, as described in `the documentation`_.
.. _the documentation:
https://docs.docker.com/network/proxy/#configure-the-docker-client
'''
return Proxy... | Instantiate a new ProxyConfig from a dictionary that represents a
client configuration, as described in `the documentation`_.
.. _the documentation:
https://docs.docker.com/network/proxy/#configure-the-docker-client |
def set_value(self, value: datetime):
""" Sets the current value """
assert isinstance(value, datetime)
self.value = value | Sets the current value |
def absent(name, orgname=None, profile='grafana'):
'''
Ensure that a data source is present.
name
Name of the data source to remove.
orgname
Name of the organization from which the data source should be absent.
profile
Configuration profile used to connect to the Grafana i... | Ensure that a data source is present.
name
Name of the data source to remove.
orgname
Name of the organization from which the data source should be absent.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'. |
def plot(self,
resolution_constant_regions=20,
resolution_smooth_regions=200):
"""
Return arrays x, y for plotting the piecewise constant function.
Just the minimum number of straight lines are returned if
``eps=0``, otherwise `resolution_constant_regions` plott... | Return arrays x, y for plotting the piecewise constant function.
Just the minimum number of straight lines are returned if
``eps=0``, otherwise `resolution_constant_regions` plotting intervals
are insed in the constant regions with `resolution_smooth_regions`
plotting intervals in the sm... |
def trim_sparse(M, n_std=3, s_min=None, s_max=None):
"""Apply the trimming procedure to a sparse matrix.
"""
try:
from scipy.sparse import coo_matrix
except ImportError as e:
print(str(e))
print("I am peforming dense normalization by default.")
return trim_dense(M.todens... | Apply the trimming procedure to a sparse matrix. |
def main():
"""Provide the entry point to the subreddit_stats command."""
parser = arg_parser(usage='usage: %prog [options] SUBREDDIT VIEW')
parser.add_option('-c', '--commenters', type='int', default=10,
help='Number of top commenters to display '
'[default %defa... | Provide the entry point to the subreddit_stats command. |
def create_encoder_config(args: argparse.Namespace,
max_seq_len_source: int,
max_seq_len_target: int,
config_conv: Optional[encoder.ConvolutionalEmbeddingConfig],
num_embed_source: int) -> Tuple[encoder.EncoderConfig... | Create the encoder config.
:param args: Arguments as returned by argparse.
:param max_seq_len_source: Maximum source sequence length.
:param max_seq_len_target: Maximum target sequence length.
:param config_conv: The config for the convolutional encoder (optional).
:param num_embed_source: The size... |
def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
"""
Add or remove replicas depending on `f`
"""
# TODO: refactor this
replica_num = old_required_number_of_instances
while... | Add or remove replicas depending on `f` |
def InitFromHuntObject(self,
hunt_obj,
hunt_counters=None,
with_full_summary=False):
"""Initialize API hunt object from a database hunt object.
Args:
hunt_obj: rdf_hunt_objects.Hunt to read the data from.
hunt_counters: Opti... | Initialize API hunt object from a database hunt object.
Args:
hunt_obj: rdf_hunt_objects.Hunt to read the data from.
hunt_counters: Optional db.HuntCounters object with counters information.
with_full_summary: if True, hunt_runner_args, completion counts and a few
other fields will be fil... |
def run_single(workflow, *, registry, db_file, always_cache=True):
""""Run workflow in a single thread, storing results in a Sqlite3
database.
:param workflow: Workflow or PromisedObject to be evaluated.
:param registry: serialization Registry function.
:param db_file: filename of Sqlite3 database,... | Run workflow in a single thread, storing results in a Sqlite3
database.
:param workflow: Workflow or PromisedObject to be evaluated.
:param registry: serialization Registry function.
:param db_file: filename of Sqlite3 database, give `':memory:'` to
keep the database in memory only.
:param ... |
def shape(self):
"""Total spaces per axis, computed recursively.
The recursion ends at the fist level that does not have a shape.
Examples
--------
>>> r2, r3 = odl.rn(2), odl.rn(3)
>>> pspace = odl.ProductSpace(r2, r3)
>>> pspace.shape
(2,)
>>> ... | Total spaces per axis, computed recursively.
The recursion ends at the fist level that does not have a shape.
Examples
--------
>>> r2, r3 = odl.rn(2), odl.rn(3)
>>> pspace = odl.ProductSpace(r2, r3)
>>> pspace.shape
(2,)
>>> pspace2 = odl.ProductSpace(p... |
def close(self):
""" Close the object nicely and release all the data
arrays from memory YOU CANT GET IT BACK, the pointers
and data are gone so use the getData method to get
the data array returned for future use. You can use
putData to reattach a new data array ... | Close the object nicely and release all the data
arrays from memory YOU CANT GET IT BACK, the pointers
and data are gone so use the getData method to get
the data array returned for future use. You can use
putData to reattach a new data array to the imageObject. |
def list_of_mined(cls):
"""
Provide the list of mined so they can be added to the list
queue.
:return: The list of mined domains or URL.
:rtype: list
"""
# We initiate a variable which will return the result.
result = []
if PyFunceble.CONFIGURAT... | Provide the list of mined so they can be added to the list
queue.
:return: The list of mined domains or URL.
:rtype: list |
def render(self, container, descender, state, space_below=0,
first_line_only=False):
"""Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the renderi... | Typeset the paragraph
The paragraph is typeset in the given container starting below the
current cursor position of the container. When the end of the container
is reached, the rendering state is preserved to continue setting the
rest of the paragraph when this method is called with a n... |
def get_example(cls) -> list:
"""Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`.
"""
if cls.ex... | Returns an example value for the Array type.
If an example isn't a defined attribute on the class we return
a list of 1 item containing the example value of the `items` attribute.
If `items` is None we simply return a `[1]`. |
def _flush(self, close=False):
"""Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool): A flag denoting whether t... | Flushes remaining output records in the output queues to plasma.
None is used as special type of record that is propagated from sources
to sink to notify that the end of data in a stream.
Attributes:
close (bool): A flag denoting whether the channel should be
also mar... |
def put(self, message):
"""
Simply test Put a string
:param message: str of the message
:return: str of the message
"""
return self.connection.put('echo/string', data=dict(message=message)) | Simply test Put a string
:param message: str of the message
:return: str of the message |
def expand(data):
'''Generates configuration sets based on the YAML input contents
For an introduction to the YAML mark-up, just search the net. Here is one of
its references: https://en.wikipedia.org/wiki/YAML
A configuration set corresponds to settings for **all** variables in the
input template that need... | Generates configuration sets based on the YAML input contents
For an introduction to the YAML mark-up, just search the net. Here is one of
its references: https://en.wikipedia.org/wiki/YAML
A configuration set corresponds to settings for **all** variables in the
input template that needs replacing. For exampl... |
def diffusion_coeff_counts(self):
"""List of tuples of (diffusion coefficient, counts) pairs.
The order of the diffusion coefficients is as in self.diffusion_coeff.
"""
return [(key, len(list(group)))
for key, group in itertools.groupby(self.diffusion_coeff)] | List of tuples of (diffusion coefficient, counts) pairs.
The order of the diffusion coefficients is as in self.diffusion_coeff. |
def getLayout(self, algorithmName, verbose=None):
"""
Returns all the details, including names, parameters, and compatible column types for the Layout algorithm specified by the `algorithmName` parameter.
:param algorithmName: Name of the Layout algorithm
:param verbose: print more
... | Returns all the details, including names, parameters, and compatible column types for the Layout algorithm specified by the `algorithmName` parameter.
:param algorithmName: Name of the Layout algorithm
:param verbose: print more
:returns: 200: successful operation |
def FromJsonString(self, value):
"""Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
... | Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ParseError: On parsing ... |
def cli(ctx, resource):
"""
Displays all locally cached <resource> versions available for installation.
\b
Available resources:
ips (default)
dev_tools
"""
log = logging.getLogger('ipsv.setup')
assert isinstance(ctx, Context)
resource = str(resource).lower()
if res... | Displays all locally cached <resource> versions available for installation.
\b
Available resources:
ips (default)
dev_tools |
def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.rb_tutor.isChecked():
self.user_type = 'tutor'
elif self.rb_student.isChecked():
self.user_type = 'student'
self.accept() | Return either 'tutor' or 'student' based on which radio
button is selected. |
def preferred_height(self, cli, width, max_available_height, wrap_lines):
"""
Preferred height: as much as needed in order to display all the completions.
"""
complete_state = cli.current_buffer.complete_state
column_width = self._get_column_width(complete_state)
column_c... | Preferred height: as much as needed in order to display all the completions. |
def _get_default(self, obj):
''' Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc.
'''
if self.name in obj._property_values:
# this shouldn't happen because we should have checked befor... | Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc. |
def doDirectPayment(self, params):
"""Call PayPal DoDirectPayment method."""
defaults = {"method": "DoDirectPayment", "paymentaction": "Sale"}
required = ["creditcardtype",
"acct",
"expdate",
"cvv2",
"ipaddress",
... | Call PayPal DoDirectPayment method. |
def process(self):
"""Construct and start a new File hunt.
Returns:
The newly created GRR hunt object.
Raises:
RuntimeError: if no items specified for collection.
"""
print('Hunt to collect {0:d} items'.format(len(self.file_path_list)))
print('Files to be collected: {0!s}'.format(s... | Construct and start a new File hunt.
Returns:
The newly created GRR hunt object.
Raises:
RuntimeError: if no items specified for collection. |
def get_poll(self, arg, *, request_policy=None):
"""Retrieves a poll from strawpoll.
:param arg: Either the ID of the poll or its strawpoll url.
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy... | Retrieves a poll from strawpoll.
:param arg: Either the ID of the poll or its strawpoll url.
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy`]
:raises HTTPException: Requesting the poll faile... |
def get_last_config_update_time_output_last_config_update_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_last_config_update_time = ET.Element("get_last_config_update_time")
config = get_last_config_update_time
output = ET.SubElement(get... | Auto Generated Code |
def h_kinetic(T, P, MW, Hvap, f=1):
r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
h = \left(\frac{2f}{2-f}\right)\left(\frac{MW}{1000\cdot 2\pi R T}
\right)^{0.5}\left... | r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
h = \left(\frac{2f}{2-f}\right)\left(\frac{MW}{1000\cdot 2\pi R T}
\right)^{0.5}\left(\frac{H_{vap}^2 P \cdot MW}{1000\cdot R... |
def graph_from_voxels(fg_markers,
bg_markers,
regional_term = False,
boundary_term = False,
regional_term_args = False,
boundary_term_args = False):
"""
Create a graph-cut ready graph to segme... | Create a graph-cut ready graph to segment a nD image using the voxel neighbourhood.
Create a `~medpy.graphcut.maxflow.GraphDouble` object for all voxels of an image with a
:math:`ndim * 2` neighbourhood.
Every voxel of the image is regarded as a node. They are connected to their immediate
neig... |
def source_filename(self, docname: str, srcdir: str):
""" Get the full filename to referenced image """
docpath = Path(srcdir, docname)
parent = docpath.parent
imgpath = parent.joinpath(self.filename)
# Does this exist?
if not imgpath.exists():
msg = f'Image... | Get the full filename to referenced image |
def settings_system_update(self, data):
"""
Set system settings. Uses PUT to /settings/system interface
:Args:
* *data*: (dict) Settings dictionary as specified `here <https://cloud.knuverse.com/docs/api/#api-System_Settings-Set_System_Settings>`_.
:Returns: None
"... | Set system settings. Uses PUT to /settings/system interface
:Args:
* *data*: (dict) Settings dictionary as specified `here <https://cloud.knuverse.com/docs/api/#api-System_Settings-Set_System_Settings>`_.
:Returns: None |
def state_by_node2state_by_state(tpm):
"""Convert a state-by-node TPM to a state-by-state TPM.
.. important::
A nondeterministic state-by-node TPM can have more than one
representation as a state-by-state TPM. However, the mapping can be
made to be one-to-one if we assume the TPMs to be... | Convert a state-by-node TPM to a state-by-state TPM.
.. important::
A nondeterministic state-by-node TPM can have more than one
representation as a state-by-state TPM. However, the mapping can be
made to be one-to-one if we assume the TPMs to be conditionally
independent. Therefore,... |
def exception(self, e):
"""Log an error messsage.
:param e: Exception to log.
"""
self.logged_exception(e)
self.logger.exception(e) | Log an error messsage.
:param e: Exception to log. |
def sync_header_chain(cls, path, bitcoind_server, last_block_id ):
"""
Synchronize our local block headers up to the last block ID given.
@last_block_id is *inclusive*
@bitcoind_server is host:port or just host
"""
current_block_id = SPVClient.height( path )
if cu... | Synchronize our local block headers up to the last block ID given.
@last_block_id is *inclusive*
@bitcoind_server is host:port or just host |
def _set_time_property(self, v, load=False):
"""
Setter method for time_property, mapped from YANG variable /ptp_state/time_property (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_time_property is considered as a private
method. Backends looking to popul... | Setter method for time_property, mapped from YANG variable /ptp_state/time_property (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_time_property is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._s... |
def _onMouseWheel(self, evt):
"""Translate mouse wheel events into matplotlib events"""
# Determine mouse location
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
# Convert delta/rotation/rate into a floating point step size
delta = evt.GetWheelDelta()
r... | Translate mouse wheel events into matplotlib events |
def get_all_chains(self):
"""Assemble and return a list of all chains for all leaf nodes to the merkle root.
"""
return [self.get_chain(i) for i in range(len(self.leaves))] | Assemble and return a list of all chains for all leaf nodes to the merkle root. |
def from_string(cls, string, *, default_func=None):
'''Construct a Service from a string.
If default_func is provided and any ServicePart is missing, it is called with
default_func(protocol, part) to obtain the missing part.
'''
if not isinstance(string, str):
raise ... | Construct a Service from a string.
If default_func is provided and any ServicePart is missing, it is called with
default_func(protocol, part) to obtain the missing part. |
def asset_view_atype(self, ):
"""View the project of the current atype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
atype = self.cur_asset.atype
self.view_atype(atype) | View the project of the current atype
:returns: None
:rtype: None
:raises: None |
def delete_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Delete the DCNM OUT network and update the result. """
tenant_name = fw_dict.get('tenant_name')
ret = self._delete_service_nwk(tenant_id, tenant_name, 'out')
if ret:
res = fw_const.DCNM_OUT_NETWORK_DEL_SU... | Delete the DCNM OUT network and update the result. |
def __add_item(self, item, keys=None):
""" Internal method to add an item to the multi-key dictionary"""
if(not keys or not len(keys)):
raise Exception('Error in %s.__add_item(%s, keys=tuple/list of items): need to specify a tuple/list containing at least one key!'
... | Internal method to add an item to the multi-key dictionary |
def get_plugin(cls, name=None, **kwargs):
"""Returns the first format plugin whose attributes match kwargs.
For example::
get_plugin(extension="scratch14")
Will return the :class:`KurtPlugin` whose :attr:`extension
<KurtPlugin.extension>` attribute is ``"scratch14"``.
... | Returns the first format plugin whose attributes match kwargs.
For example::
get_plugin(extension="scratch14")
Will return the :class:`KurtPlugin` whose :attr:`extension
<KurtPlugin.extension>` attribute is ``"scratch14"``.
The :attr:`name <KurtPlugin.name>` is used as th... |
def getid(self, idtype):
'''
idtype in Uniq constants
'''
memorable_id = None
while memorable_id in self._ids:
l=[]
for _ in range(4):
l.append(str(randint(0, 19)))
memorable_id = ''.join(l)
self._ids.append(memorable_id... | idtype in Uniq constants |
def gather_layer_info(self):
"""Extracts the tagged coiled-coil parameters for each layer."""
for i in range(len(self.cc[0])):
layer_radii = [x[i].tags['distance_to_ref_axis'] for x in self.cc]
self.radii_layers.append(layer_radii)
layer_alpha = [x[i].tags['alpha_angl... | Extracts the tagged coiled-coil parameters for each layer. |
def authentication_required(meth):
"""Simple class method decorator.
Checks if the client is currently connected.
:param meth: the original called method
"""
def check(cls, *args, **kwargs):
if cls.authenticated:
return meth(cls, *args, **kwargs)
raise Error("Authentic... | Simple class method decorator.
Checks if the client is currently connected.
:param meth: the original called method |
def make_data():
"""creates example data set"""
a = { (1,1):.25, (1,2):.15, (1,3):.2,
(2,1):.3, (2,2):.3, (2,3):.1,
(3,1):.15, (3,2):.65, (3,3):.05,
(4,1):.1, (4,2):.05, (4,3):.8
}
epsilon = 0.01
I,p = multidict({1:5, 2:6, 3:8, 4:20})
K,LB = multidict({1:.... | creates example data set |
def apply(self, data_source):
"""
Called with the predict data (new information).
@param data_source: Either a pandas.DataFrame or a file-like object.
"""
dataframe = self.__get_dataframe(data_source, use_target=False)
dataframe = self.__cleaner.apply(dataframe)
d... | Called with the predict data (new information).
@param data_source: Either a pandas.DataFrame or a file-like object. |
def implemented(cls, for_type):
"""Assert that protocol 'cls' is implemented for type 'for_type'.
This will cause 'for_type' to be registered with the protocol 'cls'.
Subsequently, protocol.isa(for_type, cls) will return True, as will
isinstance, issubclass and others.
Raises:
... | Assert that protocol 'cls' is implemented for type 'for_type'.
This will cause 'for_type' to be registered with the protocol 'cls'.
Subsequently, protocol.isa(for_type, cls) will return True, as will
isinstance, issubclass and others.
Raises:
TypeError if 'for_type' doesn't... |
def get_api_link(self):
"""
Adds a query string to the api url. At minimum adds the type=choices
argument so that the return format is json. Any other filtering
arguments calculated by the `get_qs` method are then added to the
url. It is up to the destination url to respect them ... | Adds a query string to the api url. At minimum adds the type=choices
argument so that the return format is json. Any other filtering
arguments calculated by the `get_qs` method are then added to the
url. It is up to the destination url to respect them as filters. |
def get_tac_permissions(calendar_id):
"""
Return a list of sorted Permission objects representing
the user permissions of a given Tacoma calendar.
:return: a list of trumba.Permission objects
corresponding to the given campus calendar.
None if error, [] if not exists
raise ... | Return a list of sorted Permission objects representing
the user permissions of a given Tacoma calendar.
:return: a list of trumba.Permission objects
corresponding to the given campus calendar.
None if error, [] if not exists
raise DataFailureException or a corresponding TrumbaExce... |
def _adjacent_tri(self, edge, i):
"""
Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle.
"""
if not np.isscalar(i):
i = [x for x in i if x not in edge][0]
try:
pt1 = self.... | Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle. |
def injector_gear_2_json(self):
"""
transform this local object to JSON.
:return: the JSON from this local object
"""
LOGGER.debug("InjectorCachedGear.injector_gear_2_json")
json_obj = {
'gearId': self.id,
'gearName': self.name,
'gearAd... | transform this local object to JSON.
:return: the JSON from this local object |
def get_property(obj, name):
"""
Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed.
"""
... | Gets value of object property specified by its name.
:param obj: an object to read property from.
:param name: a name of the property to get.
:return: the property value or null if property doesn't exist or introspection failed. |
def apply_filters(self, filters):
"""
It applies a specified filters. The filters are used to reduce the control groups
which are accessed by get_confgs, get_stats, and get_defaults methods.
"""
_configs = self.configs
_stats = self.stats
self.configs = {}
... | It applies a specified filters. The filters are used to reduce the control groups
which are accessed by get_confgs, get_stats, and get_defaults methods. |
def sun_declination(day):
"""Compute the declination angle of the sun for the given date.
Uses the Spencer Formula
(found at http://www.illustratingshadows.com/www-formulae-collection.pdf)
:param day: The datetime.date to compute the declination angle for
:returns: The angle, in degrees, of the an... | Compute the declination angle of the sun for the given date.
Uses the Spencer Formula
(found at http://www.illustratingshadows.com/www-formulae-collection.pdf)
:param day: The datetime.date to compute the declination angle for
:returns: The angle, in degrees, of the angle of declination |
def send_video_note(chat_id, video_note,
duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=False,
**kwargs):
"""
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
... | Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
:param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
:param video_note: Video to send. Pass a file_id as String to send a video t... |
def read_hotkey(suppress=True):
"""
Similar to `read_key()`, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p"
"""
queue = _queue.Queue()
fn = lambda e:... | Similar to `read_key()`, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p" |
def get_mimetype(self):
"""
Mimetype is calculated based on the file's content. If ``_mimetype``
attribute is available, it will be returned (backends which store
mimetypes or can easily recognize them, should set this private
attribute to indicate that type should *NOT* be calcu... | Mimetype is calculated based on the file's content. If ``_mimetype``
attribute is available, it will be returned (backends which store
mimetypes or can easily recognize them, should set this private
attribute to indicate that type should *NOT* be calculated). |
def timeit(output):
"""
If output is string, then print the string and also time used
"""
b = time.time()
yield
print output, 'time used: %.3fs' % (time.time()-b) | If output is string, then print the string and also time used |
def gps_rtk_send(self, time_last_baseline_ms, rtk_receiver_id, wn, tow, rtk_health, rtk_rate, nsats, baseline_coords_type, baseline_a_mm, baseline_b_mm, baseline_c_mm, accuracy, iar_num_hypotheses, force_mavlink1=False):
'''
RTK GPS data. Gives information on the relative baseline calcul... | RTK GPS data. Gives information on the relative baseline calculation
the GPS is reporting
time_last_baseline_ms : Time since boot of last baseline message received in ms. (uint32_t)
rtk_receiver_id : Identification of connected RTK receiver. (uint8_t)
... |
def init_db_conn(connection_name, HOSTS=None):
"""
Initialize a redis connection by each connection string
defined in the configuration file
"""
el = elasticsearch.Elasticsearch(hosts=HOSTS)
el_pool.connections[connection_name] = ElasticSearchClient(el) | Initialize a redis connection by each connection string
defined in the configuration file |
def executor(self) -> "ThreadPoolExecutor":
"""Executor instance.
:rtype: ThreadPoolExecutor
"""
if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown:
self.configure()
return self.__executor | Executor instance.
:rtype: ThreadPoolExecutor |
def has_stack(self, stack_name):
"""
Checks if a CloudFormation stack with given name exists
:param stack_name: Name or ID of the stack
:return: True if stack exists. False otherwise
"""
cf = self.cf_client
try:
resp = cf.describe_stacks(StackName=stac... | Checks if a CloudFormation stack with given name exists
:param stack_name: Name or ID of the stack
:return: True if stack exists. False otherwise |
def update_hosts(self, host_names):
"""Primarily for puppet-unity use.
Update the hosts for the lun if needed.
:param host_names: specify the new hosts which access the LUN.
"""
if self.host_access:
curr_hosts = [access.host.name for access in self.host_access]
... | Primarily for puppet-unity use.
Update the hosts for the lun if needed.
:param host_names: specify the new hosts which access the LUN. |
def getMachine(self, machineName):
"""returns a machine object for a given machine
Input:
machineName - name of the box ex: SERVER.DOMAIN.COM
"""
url = self._url + "/%s" % machineName
return Machine(url=url,
securityHandler=self._securityHa... | returns a machine object for a given machine
Input:
machineName - name of the box ex: SERVER.DOMAIN.COM |
def pairs(args):
"""
See __doc__ for OptionParser.set_pairs().
"""
import jcvi.formats.bed
p = OptionParser(pairs.__doc__)
p.set_pairs()
opts, targs = p.parse_args(args)
if len(targs) != 1:
sys.exit(not p.print_help())
samfile, = targs
bedfile = samfile.rsplit(".", 1)[... | See __doc__ for OptionParser.set_pairs(). |
def svg(self, value):
"""
Set SVG field value.
If the svg has embed base64 element we will extract them
to disk in order to avoid duplication of content
"""
if len(value) < 500:
self._svg = value
return
try:
root = ET.fromstr... | Set SVG field value.
If the svg has embed base64 element we will extract them
to disk in order to avoid duplication of content |
def job_file(self):
"""The path to the submit description file representing this job.
"""
job_file_name = '%s.job' % (self.name)
job_file_path = os.path.join(self.initial_dir, job_file_name)
self._job_file = job_file_path
return self._job_file | The path to the submit description file representing this job. |
def add_permission(self, perm):
"""
Soyut Role Permission nesnesi tanımlamayı sağlar.
Args:
perm (object):
"""
self.Permissions(permission=perm)
PermissionCache.flush()
self.save() | Soyut Role Permission nesnesi tanımlamayı sağlar.
Args:
perm (object): |
def start_record():
"""
Install an httplib wrapper that records but does not modify calls.
"""
global record, playback, current
if record:
raise StateError("Already recording.")
if playback:
raise StateError("Currently playing back.")
record = True
current = ReplayData()
... | Install an httplib wrapper that records but does not modify calls. |
def zoomedHealpixMap(title, map, lon, lat, radius,
xsize=1000, **kwargs):
"""
Inputs: lon (deg), lat (deg), radius (deg)
"""
reso = 60. * 2. * radius / xsize # Deg to arcmin
hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs) | Inputs: lon (deg), lat (deg), radius (deg) |
def _make_sql_params(self,kw):
"""Make a list of strings to pass to an SQL statement
from the dictionary kw with Python types"""
return ['%s=?' %k for k in kw.keys() ]
for k,v in kw.iteritems():
vals.append('%s=?' %k)
return vals | Make a list of strings to pass to an SQL statement
from the dictionary kw with Python types |
def dasopr(fname):
"""
Open a DAS file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
:rtype: int
"""
fname = stypes.stringToCharP(fn... | Open a DAS file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
:rtype: int |
def _execute_cell(args, cell_body):
"""Implements the BigQuery cell magic used to execute BQ queries.
The supported syntax is:
%%bq execute <args>
[<inline SQL>]
Args:
args: the optional arguments following '%%bq execute'.
cell_body: optional contents of the cell
Returns:
QueryResultsTa... | Implements the BigQuery cell magic used to execute BQ queries.
The supported syntax is:
%%bq execute <args>
[<inline SQL>]
Args:
args: the optional arguments following '%%bq execute'.
cell_body: optional contents of the cell
Returns:
QueryResultsTable containing query result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.