text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_assignable_vault_ids(self, vault_id):
"""Gets a list of vault including and under the given vault node in which any authorization can be assigned.
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
return: (osid.id.IdList) - list of assignable vault ``Ids``
raise: NullA... | 0.003021 |
def id_pools_vsn_ranges(self):
"""
Gets the IdPoolsRanges API Client for VSN Ranges.
Returns:
IdPoolsRanges:
"""
if not self.__id_pools_vsn_ranges:
self.__id_pools_vsn_ranges = IdPoolsRanges('vsn', self.__connection)
return self.__id_pools_vsn_ran... | 0.009288 |
def compareBulk(self, retina_name, body):
"""Bulk compare
Args:
retina_name, str: The retina name (required)
body, ExpressionOperation: Bulk comparison of elements 2 by 2 (required)
Returns: Array[Metric]
"""
resourcePath = '/compare/bulk'
met... | 0.007052 |
def creds(provider):
'''
Return the credentials for AWS signing. This could be just the id and key
specified in the provider configuration, or if the id or key is set to the
literal string 'use-instance-role-credentials' creds will pull the instance
role credentials from the meta data, cache them, ... | 0.002558 |
def _fieldnames_to_colnames(model_cls, fieldnames):
"""Get the names of columns referenced by the given model fields."""
get_field = model_cls._meta.get_field
fields = map(get_field, fieldnames)
return {f.column for f in fields} | 0.007692 |
def format(self):
"""
The |ChartFormat| object providing access to the shape formatting
properties of this data point, such as line and fill.
"""
dPt = self._ser.get_or_add_dPt_for_point(self._idx)
return ChartFormat(dPt) | 0.007435 |
def integral(A=None,dF=None,F=None,axis = 0,trapez = False,cumulative = False):
'''
Turns an array A of length N (the function values in N points)
and an array dF of length N-1 (the masses of the N-1 intervals)
into an array of length N (the integral \int A dF at N points, with first entry 0)
:... | 0.033314 |
def sort_values(self, by, ascending=True):
"""Summary
Returns:
TYPE: Description
"""
if len(self.column_types) == 1:
vec_type = [WeldVec(self.column_types[0])]
else:
vec_type = [WeldVec(WeldStruct(self.column_types))]
if len(self.colu... | 0.003468 |
def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Build html reveal.js slides from markdown in docs/ dir")
p... | 0.002252 |
def load(self, steps_dir=None, step_file=None, step_list=None):
"""Load CWL steps into the WorkflowGenerator's steps library.
Adds steps (command line tools and workflows) to the
``WorkflowGenerator``'s steps library. These steps can be used to
create workflows.
Args:
... | 0.002786 |
def is_philips(dicom_input):
"""
Use this function to detect if a dicom series is a philips dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... | 0.001661 |
def intern_unbound(
ns: sym.Symbol, name: sym.Symbol, dynamic: bool = False, meta=None
) -> "Var":
"""Create a new unbound `Var` instance to the symbol `name` in namespace `ns`."""
var_ns = Namespace.get_or_create(ns)
return var_ns.intern(name, Var(var_ns, name, dynamic=dynamic, meta... | 0.015291 |
def reverseCommit(self):
"""
Remove the inserted character(s).
"""
tc = self.qteWidget.textCursor()
# Select the area from before the insertion to after the insertion,
# and remove it.
tc.setPosition(self.cursorPos1, QtGui.QTextCursor.MoveAnchor)
tc.setP... | 0.002999 |
def change_view(self, request, object_id, form_url='', extra_context=None):
"""
Override change view to add extra context enabling moderate tool.
"""
context = {
'has_moderate_tool': True
}
if extra_context:
context.update(extra_context)
re... | 0.003945 |
def bulk_get(cls, exports, api=None):
"""
Retrieve exports in bulk.
:param exports: Exports to be retrieved.
:param api: Api instance.
:return: list of ExportBulkRecord objects.
"""
api = api or cls._API
export_ids = [Transform.to_export(export) for export... | 0.003891 |
def chunks(seq, size):
""" simple two-line alternative to `ubelt.chunks` """
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) | 0.006711 |
def arc_data(self):
"""Return the map from filenames to lists of line number pairs."""
return dict(
[(f, sorted(amap.keys())) for f, amap in iitems(self.arcs)]
) | 0.00995 |
def __decode_data(self):
"""!
@brief Decodes data from CF-tree features.
"""
self.__clusters = [ [] for _ in range(self.__number_clusters) ];
self.__noise = [];
for index_point in range(0, len(self.__pointer_data)):
(_, clu... | 0.026477 |
def add_version_tracking(self, info_id, version, date, command_line=''):
"""
Add a line with information about which software that was run and when
to the header.
Arguments:
info_id (str): The id of the info line
version (str): The version of the softwar... | 0.010294 |
def _parse_country_file(self, cty_file, country_mapping_filename=None):
"""
Parse the content of a PLIST file from country-files.com return the
parsed values in dictionaries.
Country-files.com provides Prefixes and Exceptions
"""
import plistlib
cty_list = None... | 0.003645 |
def create_objective(dist, abscissas):
"""Create objective function."""
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
"""Local objective function."""
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
return obj | 0.006289 |
def plotres(psr,deleted=False,group=None,**kwargs):
"""Plot residuals, compute unweighted rms residual."""
res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs
if (not deleted) and N.any(psr.deleted != 0):
res, t, errs = res[psr.deleted == 0], t[psr.deleted == 0], errs[psr.deleted == 0]
... | 0.019786 |
def signal(sig, action):
"""
The point of this module and method is to decouple signal handlers from
each other. Standard way to deal with handlers is to always store the old
handler and call it. It creates a chain of handlers, making it impossible
to later remove the handler.
This method behav... | 0.001115 |
def publish(self):
'''
Runs :func:`cleanup` first,
then pushes the changes to the :attr:`remote`.
'''
self.cleanup
remote = self.remote
branch = self.branch
return self.m(
'pushing changes to %s/%s' % (remote, branch),
cmdd=dict(
... | 0.004107 |
def use_plenary_assessment_offered_view(self):
"""Pass through to provider AssessmentOfferedLookupSession.use_plenary_assessment_offered_view"""
self._object_views['assessment_offered'] = PLENARY
# self._get_provider_session('assessment_offered_lookup_session') # To make sure the session is trac... | 0.007813 |
def prune_loop_for_kic(self, loops_segments, search_radius, expected_min_loop_length = None, expected_max_loop_length = None, generate_pymol_session = False):
'''A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method.'''
return s... | 0.034483 |
def get_permission(self, username, virtual_host):
"""Get User permissions for the configured virtual host.
:param str username: Username
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Ra... | 0.00289 |
def extract_subsection(im, shape):
r"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to e... | 0.000778 |
def get_vocab(text, score, max_feats=750, max_feats2=200):
"""
Uses a fisher test to find words that are significant in that they separate
high scoring essays from low scoring essays.
text is a list of input essays.
score is a list of scores, with score[n] corresponding to text[n]
max_feats is t... | 0.003203 |
def filter(self,x):
"""
Filter the signal using second-order sections
"""
y = signal.sosfilt(self.sos,x)
return y | 0.026144 |
def child_removed(self, child):
""" Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method.
"""
super(UiKitView, self).child_removed(child)
if child.widg... | 0.005236 |
def psql(self, args):
r"""Invoke psql, passing the given command-line arguments.
Typical <args> values: ['-c', <sql_string>] or ['-f', <pathname>].
Connection parameters are taken from self. STDIN, STDOUT,
and STDERR are inherited from the parent.
WARNING: This method uses th... | 0.002079 |
def update(self, unique_name=values.unset, callback_method=values.unset,
callback_url=values.unset, friendly_name=values.unset,
rate_plan=values.unset, status=values.unset,
commands_callback_method=values.unset,
commands_callback_url=values.unset, sms_fallback... | 0.004559 |
def breeding_wean(request, breeding_id):
"""This view is used to generate a form by which to wean pups which belong to a particular breeding set.
This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-chang... | 0.017032 |
def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].eigenvectors_left
... | 0.012085 |
def _get_csr_extensions(csr):
'''
Returns a list of dicts containing the name, value and critical value of
any extension contained in a csr object.
'''
ret = OrderedDict()
csrtempfile = tempfile.NamedTemporaryFile()
csrtempfile.write(csr.as_pem())
csrtempfile.flush()
csryaml = _pars... | 0.00361 |
def set_deferred_transfer(self, enable):
"""
Allow transfers to be delayed and buffered
By default deferred transfers are turned off. All reads and
writes will be completed by the time the function returns.
When enabled packets are buffered and sent all at once, which
... | 0.001543 |
def find_completions_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find completions at the cursor.
Return a dict of { name => Completion } objects.
"""
q = gcl.SourceQuery(filename, line, col - 1)
rootpath = ast_tree.find_tokens(q)
if is_identifier_position(rootpath):
return f... | 0.014019 |
def fast_sync_snapshot(working_dir, export_path, private_key, block_number ):
"""
Export all the local state for fast-sync.
If block_number is given, then the name database
at that particular block number will be taken.
The exported tarball will be signed with the given private key,
and the sig... | 0.004472 |
def almost_eq(a, b, bits=32, tol=1, ignore_type=True, pad=0.):
"""
Almost equal, based on the amount of floating point significand bits.
Alternative to "a == b" for float numbers and iterables with float numbers,
and tests for sequence contents (i.e., an elementwise a == b, that also
works with generators, n... | 0.008922 |
def getThings(self):
""" Get the things registered in your account
:return: dict with things registered in the logged in account and API call status
"""
login_return = self._is_logged_in()
# raise NameError("Please login first using the login function, with username... | 0.011966 |
def switch_to_rich_text(self):
"""Switch to rich text mode"""
self.rich_help = True
self.plain_text.hide()
self.rich_text.show()
self.rich_text_action.setChecked(True)
self.show_source_action.setChecked(False) | 0.007605 |
def set_on_level(self, val):
"""Set on level for the button/group."""
on_cmd = self._create_set_property_msg("_on_level", 0x06,
val)
self._send_method(on_cmd, self._property_set)
self._send_method(on_cmd, self._on_message_received) | 0.006452 |
def sequence(self, line_data, child_type=None, reference=None):
"""
Get the sequence of line_data, according to the columns 'seqid', 'start', 'end', 'strand'.
Requires fasta reference.
When used on 'mRNA' type line_data, child_type can be used to specify which kind of sequence to return:... | 0.00602 |
def apis(self):
"""List of API to test"""
value = self.attributes['apis']
if isinstance(value, six.string_types):
value = shlex.split(value)
return value | 0.010152 |
def update(self):
"""Update the processes stats."""
# Reset the stats
self.processlist = []
self.reset_processcount()
# Do not process if disable tag is set
if self.disable_tag:
return
# Time since last update (for disk_io rate computation)
t... | 0.001961 |
def _extract_all_python_namespaces(self, thrift_file_sources_by_target):
"""Extract the python namespace from each thrift source file."""
py_namespaces_by_target = OrderedDict()
failing_py_thrift_by_target = defaultdict(list)
for t, all_content in thrift_file_sources_by_target.items():
py_namespac... | 0.010411 |
def accumulate(iterable, func=operator.add):
"""
Cumulative calculations. (Summation, by default.)
Via: https://docs.python.org/3/library/itertools.html#itertools.accumulate
"""
it = iter(iterable)
total = next(it)
yield total
for element in it:
total = func(total, element)
... | 0.002994 |
def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
"""
self.elapsed_time = -time()
dpi = 100
fig = figure(figsize=(16, 9), dpi=dpi)
with self.writer.s... | 0.00578 |
def reformat_python_docstrings(top_dirs: List[str],
correct_copyright_lines: List[str],
show_only: bool = True,
rewrite: bool = False,
process_only_filenum: int = None) -> None:
"""
Walk a... | 0.000565 |
def refine(video, **kwargs):
"""Refine a video by searching `OMDb API <http://omdbapi.com/>`_.
Several :class:`~subliminal.video.Episode` attributes can be found:
* :attr:`~subliminal.video.Episode.series`
* :attr:`~subliminal.video.Episode.year`
* :attr:`~subliminal.video.Episode.series_imd... | 0.000915 |
def multiply(self, x1, x2, out=None):
"""Return the pointwise product of ``x1`` and ``x2``.
Parameters
----------
x1, x2 : `LinearSpaceElement`
Multiplicands in the product.
out : `LinearSpaceElement`, optional
Element to which the result is written.
... | 0.001787 |
def send(self, data, sample_rate=None):
'''Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what... | 0.001399 |
def _ImageDimensions(images, dynamic_shape=False):
"""Returns the dimensions of an image tensor.
Args:
images: 4-D Tensor of shape [batch, height, width, channels]
dynamic_shape: Whether the input image has undertermined shape. If set to
`True`, shape information will be retrieved at run time. Default... | 0.009629 |
def parse(cls, s, required=False):
"""
Parse string to create an instance
:param str s: String with requirement to parse
:param bool required: Is this requirement required to be fulfilled? If not, then it is a filter.
"""
req = pkg_resources.Requirement.parse(s)
... | 0.008333 |
def getStatus(self):
"""Dumps different debug info about cluster to dict and return it"""
status = {}
status['version'] = VERSION
status['revision'] = REVISION
status['self'] = self.__selfNode
status['state'] = self.__raftState
status['leader'] = self.__raftLeade... | 0.002516 |
def between(min_val, # type: Any
max_val, # type: Any
open_left=False, # type: bool
open_right=False # type: bool
):
"""
'Is between' validation_function generator.
Returns a validation_function to check that min_val <= x <= max_val (defaul... | 0.004506 |
async def respond_rpc(self, msg, _context):
"""Respond to an RPC previously sent to a service."""
rpc_id = msg.get('response_uuid')
result = msg.get('result')
payload = msg.get('response')
self.service_manager.send_rpc_response(rpc_id, result, payload) | 0.006803 |
def thaw_decrypt(vault_client, src_file, tmp_dir, opt):
"""Decrypts the encrypted ice file"""
if not os.path.isdir(opt.secrets):
LOG.info("Creating secret directory %s", opt.secrets)
os.mkdir(opt.secrets)
zip_file = "%s/aomi.zip" % tmp_dir
if opt.gpg_pass_path:
gpg_path_bits =... | 0.000852 |
def get_next_parameters(self, n=None):
"""Gets the next set of ``Parameters`` in this list which must be less than or equal to the return from ``available()``.
arg: n (cardinal): the number of ``Parameter`` elements
requested which must be less than or equal to
``avai... | 0.00382 |
def __create_safari_driver(self):
'''
Creates an instance of Safari webdriver.
'''
# Check for selenium jar env file needed for safari driver.
if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV):
# If not set, check if we have a config setting for it.
try:
... | 0.004032 |
def attach_volume(volume_id, instance_id, device,
region=None, key=None, keyid=None, profile=None):
'''
Attach an EBS volume to an EC2 instance.
..
volume_id
(string) – The ID of the EBS volume to be attached.
instance_id
(string) – The ID of the EC2 instance to at... | 0.00225 |
def rhyming_part(phones):
"""Get the "rhyming part" of a string with CMUdict phones.
"Rhyming part" here means everything from the vowel in the stressed
syllable nearest the end of the word up to the end of the word.
.. doctest::
>>> import pronouncing
>>> phones = pronouncing.phones_... | 0.001353 |
def update_clr(self, aclr, bclr):
"""
Zip the two sequences together, using "left-greedy" rule
============= seqA
||||
====(===============) seqB
"""
print(aclr, bclr, file=sys.stderr)
otype = self.otype
if ot... | 0.002581 |
def split_query(query):
"""
Handle the query as a WWW HTTP 1630 query, as this is how people
usually thinks of URI queries in general. We do not decode anything
in split operations, neither percent nor the terrible plus-to-space
conversion. Return:
>>> split_query("k1=v1&k2=v+2%12&k3=&k4&&&k5... | 0.003058 |
def upload_from_stream(self, filename, source, chunk_size_bytes=None,
metadata=None, session=None):
"""Uploads a user file to a GridFS bucket.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like ... | 0.001688 |
def wrap_list(item):
"""
Returns an object as a list.
If the object is a list, it is returned directly. If it is a tuple or set, it
is returned as a list. If it is another object, it is wrapped in a list and
returned.
"""
if item is None:
return []
elif isinstance(item, list):
... | 0.004577 |
def solution_path(self, min_lambda, max_lambda, lambda_bins, verbose=0):
'''Follows the solution path to find the best lambda value.'''
lambda_grid = np.exp(np.linspace(np.log(max_lambda), np.log(min_lambda), lambda_bins))
aic_trace = np.zeros(lambda_grid.shape) # The AIC score for each lambda v... | 0.005583 |
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_ge... | 0.00134 |
def _term(g):
"""Applies the TERM rule on 'g' (see top comment)."""
all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)}
t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t}
new_rules = []
for rule in g.rules:
if len(rule.rhs) > 1 and any(is... | 0.005831 |
def update_scale(self, overflow):
"""dynamically update loss scale"""
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_r... | 0.006024 |
def has_no_jumps(neuron, max_distance=30.0, axis='z'):
'''Check if there are jumps (large movements in the `axis`)
Arguments:
neuron(Neuron): The neuron object to test
max_distance(float): value above which consecutive z-values are
considered a jump
axis(str): one of x/y/z, whic... | 0.002144 |
def _get_group_no(self, tag_name):
"""
Takes tag name and returns the number of the group to which tag belongs
"""
if tag_name in self.full:
return self.groups.index(self.full[tag_name]["parent"])
else:
return len(self.groups) | 0.006873 |
def _config(self, **kargs):
""" ReConfigure Package """
for key, value in kargs.items():
setattr(self, key, value) | 0.014085 |
def getVersionString():
"""
Function return string with version information.
It is performed by use one of three procedures: git describe,
file in .git dir and file __VERSION__.
"""
version_string = None
try:
version_string = subprocess.check_output(['git', 'describe'])
except:
... | 0.005 |
def _appendTrlFile(trlfile,drizfile):
""" Append drizfile to already existing trlfile from CALXXX.
"""
if not os.path.exists(drizfile):
return
# Open already existing CALWF3 trailer file for appending
ftrl = open(trlfile,'a')
# Open astrodrizzle trailer file
fdriz = open(drizfile)
... | 0.005164 |
def list_associated_storage_groups(
self, full_properties=False, filter_args=None):
"""
Return the :term:`storage groups <storage group>` that are associated
to this CPC.
If the CPC does not support the "dpm-storage-management" feature, or
does not have it enabled, a... | 0.000919 |
def send_exception_to_sentry(self, exc_info):
"""Send an exception to Sentry if enabled.
:param tuple exc_info: exception information as returned from
:func:`sys.exc_info`
"""
if not self.sentry_client:
LOGGER.debug('No sentry_client, aborting')
retu... | 0.002345 |
def agent_service_register(consul_url=None, token=None, **kwargs):
'''
The used to add a new service, with an optional
health check, to the local agent.
:param consul_url: The Consul server URL.
:param name: A name describing the service.
:param address: The address used by the service, default... | 0.001018 |
def row_completed(self, index):
"""Mark the row at index as completed.
.. seealso:: :meth:`completed_row_indices`
This method notifies the obsevrers from :meth:`on_row_completed`.
"""
self._completed_rows.append(index)
for row_completed in self._on_row_completed:
... | 0.00578 |
def cleanup(self):
"""
removes inactive clients (will be run in its own thread, about once
every second)
"""
while self.inactive_timeout > 0:
self.time = time.time()
keys = []
for key, client in self.clients.items.items():
t ... | 0.002946 |
def get_broadcast(self, broadcast_id):
"""
Use this method to get details on a broadcast that is in-progress.
:param String broadcast_id: The ID of the broadcast you want to stop
:rtype A Broadcast object, which contains information of the broadcast: id, sessionId
projectId, cr... | 0.004052 |
def reduce_log_sum(attrs, inputs, proto_obj):
"""Reduce the array along a given axis by log sum value"""
keep_dims = True if 'keepdims' not in attrs else attrs.get('keepdims')
sum_op = symbol.sum(inputs[0], axis=attrs.get('axes'),
keepdims=keep_dims)
log_sym = symbol.log(sum_op)
... | 0.002833 |
def fileserver(opts, backends):
'''
Returns the file server modules
'''
return LazyLoader(_module_dirs(opts, 'fileserver'),
opts,
tag='fileserver',
whitelist=backends,
pack={'__utils__': utils(opts)}) | 0.003289 |
def rank(self, X, algorithm=None):
"""
Returns the feature ranking.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
algorithm : str or None
The ranking mechanism to use, or None for the defaul... | 0.001984 |
def update(self):
"""Update core stats.
Stats is a dict (with both physical and log cpu number) instead of a integer.
"""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
... | 0.003742 |
def get_atom_name(self, atom):
"""Look up the name of atom, returning it as a string. Will raise
BadAtom if atom does not exist."""
r = request.GetAtomName(display = self.display,
atom = atom)
return r.name | 0.022222 |
def subscriptlist(self, subscripts):
"""subscriptlist: subscript (',' subscript)* [',']"""
if len(subscripts) == 1:
return ast.Subscript(slice=subscripts[0], ctx=None, loc=None)
elif all([isinstance(x, ast.Index) for x in subscripts]):
elts = [x.value for x in subscripts... | 0.006961 |
def reply_to(self, message, text, **kwargs):
"""
Convenience function for `send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)`
"""
return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs) | 0.013559 |
def project_process(index, start, end):
"""Compute the metrics for the project process section of the enriched
github issues index.
Returns a dictionary containing "bmi_metrics", "time_to_close_metrics",
"time_to_close_review_metrics" and patchsets_metrics as the keys and
the related Metrics as the... | 0.002956 |
def find_near_matches_levenshtein(subsequence, sequence, max_l_dist):
"""Find near-matches of the subsequence in the sequence.
This chooses a suitable fuzzy search implementation according to the given
parameters.
Returns a list of fuzzysearch.Match objects describing the matching parts
of the seq... | 0.001484 |
def append(self, item):
"""
Append to object, if object is list.
"""
if self.meta_type == 'dict':
raise AssertionError('Cannot append to object of `dict` base type!')
if self.meta_type == 'list':
self._list.append(item)
return | 0.010067 |
def deserialize(self, content_type, strdata):
"""Deserialize string of given content type.
`self` unused in this implementation.
>>> s = teststore()
>>> s.deserialize('application/json', '{"id": "1", "name": "Toto"}')
{u'id': u'1', u'name': u'Toto'}
>>> s.deserialize('t... | 0.00311 |
def _default_step_sizes(reference_vertex):
"""Chooses default step sizes according to [Gao and Han(2010)][3]."""
# Step size to choose when the coordinate is zero.
small_sizes = tf.ones_like(reference_vertex) * 0.00025
# Step size to choose when the coordinate is non-zero.
large_sizes = reference_vertex * 0.0... | 0.015982 |
def calc_contours(data, num_contours):
"""Get sets of contour points for numpy array `data`.
`num_contours` specifies the number (int) of contours to make.
Returns a list of numpy arrays of points--each array makes a polygon
if plotted as such.
"""
mn = np.nanmean(data)
top = np.nanmax(data)... | 0.002463 |
def update_log_type(self, logType, name=None, level=None, stdoutFlag=None, fileFlag=None, color=None, highlight=None, attributes=None):
"""
update a logtype.
:Parameters:
#. logType (string): The logtype.
#. name (None, string): The logtype name. If None, name will be set ... | 0.011159 |
def parse_chains(data):
"""
Parse the chain definitions.
"""
chains = odict()
for line in data.splitlines(True):
m = re_chain.match(line)
if m:
policy = None
if m.group(2) != '-':
policy = m.group(2)
chains[m.group(1)] = {
... | 0.002165 |
def clean(context, days_ago, yes):
"""Clean up files from "old" analyses runs."""
number_of_days_ago = dt.datetime.now() - dt.timedelta(days=days_ago)
analyses = context.obj['store'].analyses(
status='completed',
before=number_of_days_ago,
deleted=False,
)
for analysis_obj in... | 0.006135 |
def _prepare_fetch(self, request: Request, response: Response):
'''Prepare for a fetch.
Coroutine.
'''
self._request = request
self._response = response
yield from self._init_stream()
connection_closed = self._control_connection.closed()
if connection_... | 0.003576 |
def config_oauth(app):
" Configure oauth support. "
for name in PROVIDERS:
config = app.config.get('OAUTH_%s' % name.upper())
if not config:
continue
if not name in oauth.remote_apps:
remote_app = oauth.remote_app(name, **config)
else:
remo... | 0.00463 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.