text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def assignRenderer(self, action):
"""
Assigns the renderer for this chart to the current selected
renderer.
"""
name = nativestring(action.text()).split(' ')[0]
self._renderer = XChartRenderer.plugin(name)
self.uiTypeBTN.setDefaultAction(action)
se... | 0.005952 |
def __partial_trace_mat(mat, trace_systems, dimensions, reverse=True):
"""
Partial trace over subsystems of multi-partite matrix.
Note that subsystems are ordered as rho012 = rho0(x)rho1(x)rho2.
Args:
mat (matrix_like): a matrix NxN.
trace_systems (list(int)): a list of subsystems (sta... | 0.000484 |
def clearness_index(ghi, solar_zenith, extra_radiation, min_cos_zenith=0.065,
max_clearness_index=2.0):
"""
Calculate the clearness index.
The clearness index is the ratio of global to extraterrestrial
irradiance on a horizontal plane.
Parameters
----------
ghi : numeri... | 0.000566 |
def update(self):
"""
Preparse the packaging system for installations.
"""
packager = self.packager
if packager == APT:
self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update')
elif packager == YUM:
self.sudo('yum update')
else:
... | 0.005263 |
def _get_zone(self, domain, domain_id):
"""
Pulls the zone for the current domain from authenticated Hetzner account and
returns it as an zone object.
"""
api = self.api[self.account]
for request in api['zone']['GET']:
url = (request.copy()).get('url', '/').re... | 0.005587 |
def create_emailconfirmation(self, email_address):
"Create an email confirmation obj from the given email address obj"
confirmation_key = self.generate_key(email_address.email)
confirmation = self.create(
email_address=email_address,
created_at=now(),
key=conf... | 0.005391 |
def get_query(self, query_params=None):
"""Return a query string"""
if query_params is None:
query_params = {}
query = ''
query_params['idSite'] = self.site_id
if self.api_token is not None:
query_params['token_auth'] = self.api_token
for key, valu... | 0.003883 |
def user_organisations(cls, user_id, state=None, include_deactivated=False):
"""
Get organisations that the user has joined
:param user_id: the user ID
:param state: the user's "join" state
:param include_deactivated: Include deactivated resources in response
:returns: l... | 0.00221 |
def find_item(self, fq_name):
"""Find an item in the specification by fully qualified name.
Args:
fq_name (str): Fully-qualified name of the item.
Returns:
The item if it is in the specification. None otherwise
"""
names = fq_name.split(self._separator)... | 0.003205 |
def env_is_exposed(self, tgt_env):
'''
Check if an environment is exposed by comparing it against a whitelist
and blacklist.
'''
return salt.utils.stringutils.check_whitelist_blacklist(
tgt_env,
whitelist=self.saltenv_whitelist,
blacklist=self.... | 0.005747 |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
NAME_FACTORY.update_base_dict(args['data'])
NAME_FACTORY_CLEAN.update_base_dict(args['data'])
NAME_FACTORY_DIRTY.u... | 0.003774 |
def get_user_submissions(self, task):
""" Get all the user's submissions for a given task """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to get his submissions")
cursor = self._database.submissions.find({"username": self._user_manager.se... | 0.007707 |
def refresh_meta(self):
"""Calculations that only depend on aggregate counts in Confusion Matrix go here"""
# these calcs are duplicated in __init__()
setattr(self, '_num_classes', len(self.index))
setattr(self, '_colnums', np.arange(0, self._num_classes))
try:
setat... | 0.005533 |
def split(self, availWidth, availHeight):
"""
Split ourselves in two paragraphs.
"""
logger.debug("*** split (%f, %f)", availWidth, availHeight)
splitted = []
if self.splitIndex:
text1 = self.text[:self.splitIndex]
text2 = self.text[self.splitInd... | 0.004505 |
def _search_flags(self):
"""
Returns the user search flag: (regex, case_sensitive, whole_words).
"""
return (self.checkBoxRegex.isChecked(),
self.checkBoxCase.isChecked(),
self.checkBoxWholeWords.isChecked(),
self.checkBoxInSelection.isChec... | 0.006135 |
async def _fair_recv(self):
"""
Receive from all the existing peers, rotating the list of peers every
time.
:returns: The frames.
"""
with await self._read_lock:
peer = await self._fair_get_in_peer()
result = peer.inbox.read_nowait()
retu... | 0.006079 |
def check_empty_app_dir(self):
"""Check to see if the directory in which the app is going to be created is empty."""
if not os.listdir(self.app_path):
self.handle_error(
'No app exists in this directory. Try using "tcinit --template '
'{} --action create" to c... | 0.013333 |
def marginalize(self, variables, inplace=True):
"""
Modifies the factor with marginalized values.
Parameters
----------
variables: list, array-like
List of variables over which to marginalize.
inplace: boolean
If inplace=True it will modify the f... | 0.003085 |
def run(cls, version=None):
"""
Test runner method; is called by parent class defined in suite.py.
:param version: B2G version string to test against
:return: bool PASS/FAIL status
"""
try:
dumper = certdump()
versions = dumper.nssversion_via_mari... | 0.006711 |
def auto_reuse_variable_scope(func):
"""
A decorator which automatically reuses the current variable scope if the
function has been called with the same variable scope before.
Example:
.. code-block:: python
@auto_reuse_variable_scope
def myfunc(x):
return tf.layers.co... | 0.001431 |
def cut_distant_injections(workflow, inj_file, out_dir, tags=None):
"Set up a job for removing injections that are too distant to be seen"
if tags is None:
tags = []
node = Executable(workflow.cp, 'inj_cut', ifos=workflow.ifos,
out_dir=out_dir, tags=tags).create_node()
nod... | 0.002053 |
def registry(region_name, algorithm=None):
"""Return docker registry for the given AWS region
Note: Not all the algorithms listed below have an Amazon Estimator implemented. For full list of
pre-implemented Estimators, look at:
https://github.com/aws/sagemaker-python-sdk/tree/master/src/sagemaker/amaz... | 0.001257 |
def make_message(self, data):
"""
Create a Message instance from data, data will be loaded
via munge according to the codec specified in the
transport_content_type attribute
Returns:
Message: message object
"""
data = self.codec.loads(data)
... | 0.00722 |
def del_uid(self, search):
"""
Find and remove a user id that matches the search string given. This method does not modify the corresponding
:py:obj:`~pgpy.PGPUID` object; it only removes it from the list of user ids on the key.
:param search: A text string to match name, comment, or em... | 0.008757 |
def set_scene_velocity(self, scene_id, velocity):
"""reconfigure a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to set velocity on scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg... | 0.011403 |
def calculate_statistics(self, start, stop):
"""Starts the statistics calculation.
:param start: The left limit of the time window in percent.
:param stop: The right limit of the time window in percent.
.. note::
The calculation takes some time. Check the status byte to se... | 0.00295 |
def add_hotspot(self, hotspot, xy):
"""
Add the hotspot at ``(x, y)``. The hotspot must fit inside the bounds
of the virtual device. If it does not then an ``AssertError`` is
raised.
"""
(x, y) = xy
assert(0 <= x <= self.width - hotspot.width)
assert(0 <= ... | 0.003802 |
def http(container = None):
"wrap a WSGI-style class method to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(self, event):
return _handler(self if container is None else container, event, lambda env: func(self, env))
return handler
r... | 0.01194 |
def initialize(self, runtime):
"""OSID Manager initialize"""
from .primitives import Id
if self._runtime is not None:
raise IllegalState('Manager has already been initialized')
self._runtime = runtime
config = runtime.get_configuration()
parameter_id = Id('par... | 0.006614 |
def _handle_result_by_idx_slice(self, idx_slice):
"""
Handle processing when the result argument provided is an index slice.
"""
opts = dict(self.options)
skip = opts.pop('skip', 0)
limit = opts.pop('limit', None)
py_to_couch_validate('skip', skip)
py_to_c... | 0.002241 |
def accept(self):
'''Extracts raw value from form's raw data and passes it to converter'''
value = self.raw_value
if not self._check_value_type(value):
# XXX should this be silent or TypeError?
value = [] if self.multiple else self._null_value
self.clean_value = s... | 0.007752 |
def pile(args):
"""
%prog pile abedfile bbedfile > piles
Call intersectBed on two bedfiles.
"""
from jcvi.utils.grouper import Grouper
p = OptionParser(pile.__doc__)
p.add_option("--minOverlap", default=0, type="int",
help="Minimum overlap required [default: %default]")
... | 0.001248 |
def reset_all_to_flows(self, force=False):
""" Resets the IOSystem and all extensions to absolute flows
This method calls reset_to_flows for the IOSystem and for
all Extensions in the system.
Parameters
----------
force: boolean, optional
If True, reset to ... | 0.00317 |
def matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, q=None,
numeric=True, convention=1):
r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in ... | 0.000687 |
def select_files(self, what="o"):
"""
Helper function used to select the files of a task.
Args:
what: string with the list of characters selecting the file type
Possible choices:
i ==> input_file,
o ==> output_file,
... | 0.001699 |
def inspecting_client_factory(self, host, port, ioloop_set_to):
"""Return an instance of :class:`ReplyWrappedInspectingClientAsync` or similar
Provided to ease testing. Dynamically overriding this method after instantiation
but before start() is called allows for deep brain surgery. See
... | 0.009542 |
def detect_gaps(dataframe, timestep, print_all=False, print_max=5, verbose=True):
"""checks if a given dataframe contains gaps and returns the number of gaps
This funtion checks if a dataframe contains any gaps for a given temporal
resolution that needs to be specified in seconds. The number of gaps
de... | 0.003107 |
def update_row(self, key, value):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
index of the row,... | 0.00146 |
def writeMibObjects(self, *varBinds, **context):
"""Create, destroy or modify Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, create,
destroy or modify all or none of the referenced Managed Objects Instances.
If a non-existing Managed Ob... | 0.005221 |
def finalize( self, already_done=None ):
"""Finalize our values (recursively) taken from our children"""
if already_done is None:
already_done = {}
if already_done.has_key( self ):
return True
already_done[self] = True
self.filter_children()
childr... | 0.024605 |
def dump_json(i):
"""
Input: {
dict - dictionary
(skip_indent) - if 'yes', skip indent
(sort_keys) - if 'yes', sort keys
}
Output: {
return - return code = 0, if successful
> 0, ... | 0.032864 |
def get_cond_latents_at_level(cond_latents, level, hparams):
"""Returns a single or list of conditional latents at level 'level'."""
if cond_latents:
if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]:
return [cond_latent[level] for cond_latent in cond_latents]
elif hparams.latent_dist_encod... | 0.012953 |
def _contains(self, hit):
'''Returns True iff (the query contig is contained in the reference contig and
the query contig is not flagged to be kept)'''
return (
hit.qry_name not in self.contigs_to_keep
and hit.qry_name != hit.ref_name
and (100 * hit.hit_len... | 0.008949 |
def get_categories(self, entry):
"""
Return the categories linked in HTML.
"""
try:
return format_html_join(
', ', '<a href="{}" target="blank">{}</a>',
[(category.get_absolute_url(), category.title)
for category in entry.categ... | 0.004 |
def send_note(self, to, subject="", body="", noetid=""):
"""Send a note
:param to: The username(s) that this note is to
:param subject: The subject of the note
:param body: The body of the note
:param noetid: The UUID of the note that is being responded to
"""
... | 0.007231 |
def _save_pys(self, filepath):
"""Saves file as pys file and returns True if save success
Parameters
----------
filepath: String
\tTarget file path for xls file
"""
try:
with Bz2AOpen(filepath, "wb",
main_window=self.main_... | 0.002525 |
def tree_prune_rank(self, tree, rank="species"):
"""Takes a TreeNode tree and prunes off any tips not at the specified rank and backwards up
until all of the tips are at the specified rank.
Parameters
----------
tree : `skbio.tree.TreeNode`
The root node of the tree ... | 0.005789 |
def init_db(drop_all=False, bind=engine):
"""Initialize the database, optionally dropping existing tables."""
try:
if drop_all:
Base.metadata.drop_all(bind=bind)
Base.metadata.create_all(bind=bind)
except OperationalError as err:
msg = 'password authentication failed for ... | 0.002232 |
def make_id(name):
"""
Create a random id combined with the creditor name.
@return string consisting of name (truncated at 22 chars), -,
12 char rand hex string.
"""
name = re.sub(r'[^a-zA-Z0-9]', '', name)
r = get_rand_string(12)
if len(name) > 22:
name = name[:22]
return na... | 0.003012 |
def calculate_slope_aspect(elevation, xres, yres, z=1.0, scale=1.0):
"""
Calculate slope and aspect map.
Return a pair of arrays 2 pixels smaller than the input elevation array.
Slope is returned in radians, from 0 for sheer face to pi/2 for
flat ground. Aspect is returned in radians, counterclock... | 0.000607 |
def _get_dbid2goids(associations):
"""Return gene2go data for user-specified taxids."""
id2gos = cx.defaultdict(set)
for ntd in associations:
id2gos[ntd.DB_ID].add(ntd.GO_ID)
return dict(id2gos) | 0.008403 |
def add_bboxes_to_image(image, bboxes, color='red', width=1):
"""
Draw rectangles on the image for the bounding boxes
Returns a PIL.Image
Arguments:
image -- input image
bboxes -- bounding boxes in the [((l, t), (r, b)), ...] format
Keyword arguments:
color -- color to draw the rectangle... | 0.001951 |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Write the Attributes structure encoding to the data stream.
Args:
output_stream (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
k... | 0.001166 |
def set(self, style={}):
"""overrides style values at the current stack level"""
_style = {}
for attr in style:
if attr in self.cmds and not style[attr] in self.cmds[attr]:
print 'WARNING: ESC/POS PRINTING: ignoring invalid value: '+utfstr(style[attr])+' for style: '+... | 0.007042 |
def is_closed(self):
"""
_check if the observation table is closed.
Args:
None
Returns:
tuple (bool, str): True if the observation table is
closed and false otherwise. If the table is not closed
the escaping string is returned.
"""
... | 0.002941 |
def prefix_to_addrmask(value, sep=" "):
"""
Converts a CIDR formatted prefix into an address netmask representation.
Argument sep specifies the separator between the address and netmask parts.
By default it's a single space.
Examples:
>>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.1... | 0.005587 |
def update(self, attrs):
"""Return a copy of the current Heartbeat with updated attributes."""
data = self.dict()
data.update(attrs)
heartbeat = Heartbeat(data, self.args, self.configs, _clone=True)
return heartbeat | 0.007813 |
def set_cookie(self, kaka, request):
"""Returns a http_cookiejar.Cookie based on a set-cookie header line"""
if not kaka:
return
part = urlparse(request.url)
_domain = part.hostname
logger.debug("%s: '%s'", _domain, kaka)
for cookie_name, morsel in kaka.ite... | 0.001142 |
def get_accuracy(self, scalar=None):
"""Num_True_Positive / Num_Samples"""
# to get a Series instead of a dict:
# (np.diag(c).astype(float) / c.T.sum())
# == pd.Series(self.sensitivity)
if ((not self._scalar_stats and not scalar and self._num_classes > 2) or
(... | 0.009208 |
def call(corofunc, *args, **kwargs):
"""
:return:
a delegator function that returns a coroutine object by calling
``corofunc(seed_tuple, *args, **kwargs)``.
"""
corofunc = _ensure_coroutine_function(corofunc)
def f(seed_tuple):
return corofunc(seed_tuple, *args, **kwargs)
... | 0.006079 |
def select_build_worker(self, pos: Union[Unit, Point2, Point3], force: bool=False) -> Optional[Unit]:
"""Select a worker to build a bulding with."""
workers = self.workers.closer_than(20, pos) or self.workers
for worker in workers.prefer_close_to(pos).prefer_idle:
if not worker.orde... | 0.011019 |
def get_context_data(self, **kwargs):
"""Includes the metrics slugs in the context."""
data = super(MetricsListView, self).get_context_data(**kwargs)
# Metrics organized by category, like so:
# { <category_name>: [ <slug1>, <slug2>, ... ]}
data.update({'metrics': get_r().metric_... | 0.00554 |
def list_commands(self, page_size=None):
"""
Lists the commands visible to this client.
Commands are returned in lexicographical order.
:rtype: :class:`.Command` iterator
"""
params = {}
if page_size is not None:
params['limit'] = page_size
... | 0.003328 |
def _validate_labels(labels):
"""Check for empty labels in the middle of a label sequence,
labels that are too long, and for too many labels.
@raises NameTooLong: the name as a whole is too long
@raises LabelTooLong: an individual label is too long
@raises EmptyLabel: a label is empty (i.e. the root... | 0.00267 |
def assert_tz_offset(tz):
"""Assert that system's timezone offset equals to the timezone offset found.
If they don't match, we probably have a misconfiguration, for example, an
incorrect timezone set in /etc/timezone file in systemd distributions."""
tz_offset = get_tz_offset(tz)
system_offset = ge... | 0.003344 |
def validate_filters(self, branchset_node, uncertainty_type, filters):
"""
See superclass' method for description and signature specification.
Checks that the following conditions are met:
* "sourceModel" uncertainties can not have filters.
* Absolute uncertainties must have on... | 0.000578 |
def delete(self, image_file, delete_thumbnails=True):
"""
Deletes the reference to the ``image_file`` and deletes the references
to thumbnails as well as thumbnail files if ``delete_thumbnails`` is
`True``. Does not delete the ``image_file`` is self.
"""
if delete_thumbna... | 0.004902 |
def filled_out_template(filename, **substitutions):
'''Return content of file filename with applied substitutions.'''
res = None
with open(filename, 'r') as fp:
template = fp.read()
res = filled_out_template_str(template, **substitutions)
return res | 0.003559 |
def switch_opt(default, shortname, help_msg):
"""Define a switchable ConfOpt.
This creates a boolean option. If you use it in your CLI, it can be
switched on and off by prepending + or - to its name: +opt / -opt.
Args:
default (bool): the default value of the swith option.
shortname (s... | 0.00141 |
def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content | 0.005952 |
def marshal( compoundSignature, variableList, startByte = 0, lendian=True ):
"""
Encodes the Python objects in variableList into the DBus wire-format
matching the supplied compoundSignature. This function retuns a list of
binary strings is rather than a single string to simplify the recursive
marsha... | 0.015005 |
def unpack_xml(text) -> ET.ElementTree:
"""Unpack an XML string from AniDB API."""
etree: ET.ElementTree = ET.parse(io.StringIO(text))
_check_for_errors(etree)
return etree | 0.005319 |
def _get_key_data(d, key):
"""
Generic function to grab dictionary data by key with error handling
:return:
"""
d2 = ""
try:
d2 = d[key]
except KeyError:
logger_dataframes.info("get_key_data: KeyError: {}".format(key))
return d2 | 0.003623 |
def _release(level):
"""TODO: we should make sure that we are on master release"""
version, comment = _new_version(level)
if version is not None:
run(['git',
'commit',
str(VER_PATH.relative_to(BASE_PATH)),
str(CHANGES_PATH.relative_to(BASE_PATH)),
... | 0.001325 |
def plugins(self):
"""Lazily load iotile plugins only on demand.
This is a slow operation on computers with a slow FS and is rarely
accessed information, so only compute it when it is actually asked
for.
"""
if self._plugins is None:
self._plugins = {}
... | 0.003731 |
def move_detections(label, dy, dx):
"""
Move detections in direction dx, dy.
:param label: The label dict containing all detection lists.
:param dy: The delta in y direction as a number.
:param dx: The delta in x direction as a number.
:return:
"""
for k in label.keys():
if k.st... | 0.002155 |
def rest_api_exists(self, rest_api_id):
# type: (str) -> bool
"""Check if an an API Gateway REST API exists."""
client = self._client('apigateway')
try:
client.get_rest_api(restApiId=rest_api_id)
return True
except client.exceptions.NotFoundException:
... | 0.008824 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance
:rtype: twilio.rest.previ... | 0.008463 |
def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new button that will request
the user's phone number upon being clicked.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
"""
return c... | 0.006818 |
def kl_divergence(res1, res2):
"""
Computes the `Kullback-Leibler (KL) divergence
<https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`_ *from* the
discrete probability distribution defined by `res2` *to* the discrete
probability distribution defined by `res1`.
Parameters
----------
... | 0.000326 |
def preview(self, n=10, k='items', kheader='displayLink', klink='link', kdescription='snippet'):
"""Print a preview of the search results.
Args:
n (int):
Maximum number of search results to preview
k (str):
Key in :class:`api.results`.metadata to preview
kheader (str):
... | 0.015015 |
def components_for_entity(self, entity: int) -> Tuple[C, ...]:
"""Retrieve all Components for a specific Entity, as a Tuple.
Retrieve all Components for a specific Entity. The method is probably
not appropriate to use in your Processors, but might be useful for
saving state, or passing ... | 0.002387 |
def writeFromDict(dataDict, headers, csvFile):
"""
Write dictionary to a CSV, where keys are row numbers and values are a list.
"""
with open(csvFile, "wb") as f:
writer = csv.writer(f, delimiter=",")
writer.writerow(headers)
for row in sorted(dataDict.keys()):
writer.writerow(dataDict[row]) | 0.012579 |
def import_(module_name, backport=False):
"""
Pass a (potentially dotted) module name of a Python 3 standard library
module. This function imports the module compatibly on Py2 and Py3 and
returns the top-level module.
Example use:
>>> http = import_('http.client')
>>> http = import_... | 0.000924 |
def asset(path):
"""
Join the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_wit... | 0.002212 |
async def get_module_data(request):
"""
Query a module (by its serial number) for its live data
"""
hw = hw_from_req(request)
requested_serial = request.match_info['serial']
res = None
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
else:
hw_mods = hw.... | 0.001431 |
def _shutdown_transport(self):
"""
Unwrap a Python 2.6 SSL socket, so we can call shutdown()
"""
if HAVE_PY26_SSL and (self.sslobj is not None):
self.sock = self.sslobj.unwrap()
self.sslobj = None | 0.007905 |
def _build_pentameter_templates(self) -> List[str]:
"""Create pentameter templates."""
return [ # '-UU|-UU|-|-UU|-UU|X'
self.constants.DACTYL + self.constants.DACTYL +
self.constants.STRESSED + self.constants.DACTYL + self.constants.DACTYL
+ self.constants.OPTIONAL_E... | 0.005952 |
def get_conventional_to_primitive_transformation_matrix(self, international_monoclinic=True):
"""
Gives the transformation matrix to transform a conventional
unit cell to a primitive cell according to certain standards
the standards are defined in Setyawan, W., & Curtarolo, S. (2010).
... | 0.001884 |
def loglike_from_image(filename, offset):
"""
Get a log-like stream of RGB values from an image.
Args:
filename (str): The filename of a PNG image.
offset (Number): If < 1, interpreted as proportion of way across
the image. If > 1, interpreted as pixels from left.
Returns:
... | 0.001271 |
def delete(handler, item_id, id_name):
"""Delete an item"""
data = {'operation': 'delete',
'id': item_id,
'id_name': id_name}
handler.invoke(data) | 0.005495 |
def _query(self, url, xpath):
"""Base query for an url and xpath
Args:
url (str): URL to search
xpath (str): xpath to search (may be ``None``)
"""
return self.session.query(CachedRequest).filter(CachedRequest.url == url).filter(CachedRequest.xpath == xpath) | 0.009554 |
def numchannels(samples:np.ndarray) -> int:
"""
return the number of channels present in samples
samples: a numpy array as returned by sndread
for multichannel audio, samples is always interleaved,
meaning that samples[n] returns always a frame, which
is either a single scalar for mono audio, ... | 0.004367 |
def determine_tool(filepath, tool_to_get):
"""
Determine the tool to use for reading/writing.
The function uses an internally defined set of mappings between filepaths,
regular expresions and readers/writers to work out which tool to use
for a given task, given the filepath.
It is intended for... | 0.001528 |
def regex_find(pattern, content):
"""Find the given 'pattern' in 'content'"""
find = re.findall(pattern, content)
if not find:
cij.err("pattern <%r> is invalid, no matches!" % pattern)
cij.err("content: %r" % content)
return ''
if len(find) >= 2:
cij.err("pattern <%r> i... | 0.002247 |
def find_objects(modules):
"""Find subclasses of `Object` and `ObjectSet` in the given modules.
:param modules: The full *names* of modules to include. These modules MUST
have been imported in advance.
"""
return {
subclass.__name__: subclass
for subclass in chain(
g... | 0.002237 |
def get_hash(path, form='sha256', chunk_size=65536):
'''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really ... | 0.001133 |
def __run_pre_all(self):
"""Execute the pre-all.py and pre-all.sql files if they exist"""
# if the list of delta dirs is [delta1, delta2] the pre scripts of delta2 are
# executed before the pre scripts of delta1
for d in reversed(self.dirs):
pre_all_py_path = os.path.join(d... | 0.003783 |
def update_server(self, datacenter_id, server_id, **kwargs):
"""
Updates a server with the parameters provided.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type ... | 0.001932 |
def _modify_raw_data(sample_data, is_basepairs):
""" Modify counts or base pairs according to `read_count_multiplier`
or `base_count_multiplier`.
"""
return OrderedDict(
(_modify_raw_val(x, is_basepairs), _modify_raw_val(y, is_basepairs))
for x, y in sample_data.items()
) | 0.003205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.