text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def search(query, model):
""" Performs a search query and returns the object ids """
query = query.strip()
LOGGER.debug(query)
sqs = SearchQuerySet()
results = sqs.raw_search('{}*'.format(query)).models(model)
if not results:
results = sqs.raw_search('*{}'.format(query)).models(model)
... | 0.002262 |
def _on_message(self, bus, message): # pylint: disable=unused-argument
"""When a message is received from Gstreamer."""
if message.type == Gst.MessageType.EOS:
self.stop()
elif message.type == Gst.MessageType.ERROR:
self.stop()
err, _ = message.parse_error()
... | 0.005618 |
def remap_link_target(path, absolute=False):
""" remap a link target to a static URL if it's prefixed with @ """
if path.startswith('@'):
# static resource
return static_url(path[1:], absolute=absolute)
if absolute:
# absolute-ify whatever the URL is
return urllib.parse.urlj... | 0.00274 |
def spl(self):
"""
Sound Pressure Level - defined as 20 * log10(p/p0),
where p is the RMS of the sound wave in Pascals and p0 is
20 micro Pascals.
Since we would need to know calibration information about the
microphone used to record the sound in order to transform
... | 0.002933 |
def build_intent(self, intent_name):
"""Builds an Intent object of the given name"""
# TODO: contexts
is_fallback = self.assist._intent_fallbacks[intent_name]
contexts = self.assist._required_contexts[intent_name]
events = self.assist._intent_events[intent_name]
new_inten... | 0.00578 |
def parse_args_and_kwargs(self, cmdline):
'''
cmdline: list
returns tuple of: args (list), kwargs (dict)
'''
# Parse args and kwargs
args = []
kwargs = {}
if len(cmdline) > 1:
for item in cmdline[1:]:
if '=' in item:
... | 0.004049 |
def render_profile_data(self, as_parsed):
"""Render the chosen profile entry, as it was parsed."""
try:
return deep_map(self._render_profile_data, as_parsed)
except RecursionException:
raise DbtProfileError(
'Cycle detected: Profile input has a reference t... | 0.005291 |
def dirs(self, before=time.time(), exited=True):
"""
Provider a generator of container state directories.
If exited is None, all are returned. If it is False, unexited
containers are returned. If it is True, only exited containers are
returned.
"""
timestamp = is... | 0.002491 |
def make_cookie_content(name, load, sign_key, domain=None, path=None,
timestamp="", enc_key=None, max_age=0,
sign_alg='SHA256'):
"""
Create and return a cookies content
If you only provide a `seed`, a HMAC gets added to the cookies value
and this is check... | 0.000534 |
def ms_bot_framework(self) -> dict:
"""Returns MS Bot Framework compatible state of the Button instance.
Creates MS Bot Framework CardAction (button) with postBack value return.
Returns:
control_json: MS Bot Framework representation of Button state.
"""
card_action ... | 0.006073 |
def __parse(self, stream):
"""Parse Sorting Hat stream"""
if not stream:
raise InvalidFormatError(cause="stream cannot be empty or None")
json = self.__load_json(stream)
self.__parse_organizations(json)
self.__parse_identities(json)
self.__parse_blacklist(j... | 0.006173 |
def Ribbon(line1, line2, c="m", alpha=1, res=(200, 5)):
"""Connect two lines to generate the surface inbetween.
.. hint:: |ribbon| |ribbon.py|_
"""
if isinstance(line1, Actor):
line1 = line1.coordinates()
if isinstance(line2, Actor):
line2 = line2.coordinates()
ppoints1 = vtk.v... | 0.000502 |
def as_url(cls, api=None, name_prefix='', url_prefix=''):
""" Generate url for resource.
:return RegexURLPattern: Django URL
"""
url_prefix = url_prefix and "%s/" % url_prefix
name_prefix = name_prefix and "%s-" % name_prefix
url_regex = '^%s%s/?$' % (
url_... | 0.003623 |
def __to_file(self, message_no):
""" Write a single message to file """
filename = self.__create_file_name(message_no)
try:
with codecs.open(filename, mode='w',
encoding=self.messages[message_no].encoding)\
as file__:
f... | 0.003125 |
def create_session(self):
"""Create a session on the frontier silicon device."""
req_url = '%s/%s' % (self.__webfsapi, 'CREATE_SESSION')
sid = yield from self.__session.get(req_url, params=dict(pin=self.pin),
timeout = self.timeout)
text = yiel... | 0.009346 |
def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True):
"""
Function creates a text view with wrap_mode
and justification
"""
text_view = Gtk.TextView()
text_view.set_wrap_mode(wrap_mode)
text_view.... | 0.005464 |
def mydot(A, B):
r"""Dot-product that can handle dense and sparse arrays
Parameters
----------
A : numpy ndarray or scipy sparse matrix
The first factor
B : numpy ndarray or scipy sparse matrix
The second factor
Returns
C : numpy ndarray or scipy sparse matrix
The d... | 0.004107 |
def sort_direction(self):
"""
Return the direction in which the linked table is is sorted by
this column ("asc" or "desc"), or None this column is unsorted.
"""
if self.table._meta.order_by == self.name:
return "asc"
elif self.table._meta.order_by == ("-" + ... | 0.005051 |
def is_mastercard(n):
"""Checks if credit card number fits the mastercard format."""
n, length = str(n), len(str(n))
if length >= 16 and length <= 19:
if ''.join(n[:2]) in strings_between(51, 56):
return True
return False | 0.003876 |
def _license_from_classifiers(data):
"""try to get a license from the classifiers"""
classifiers = data.get('classifiers', [])
found_license = None
for c in classifiers:
if c.startswith("License :: OSI Approved :: "):
found_license = c.replace("License :: OSI Approved :: ", "")
r... | 0.00295 |
def is_locked(self, key):
"""
Checks the lock for the specified key. If the lock is acquired, it returns ``true``. Otherwise, it returns ``false``.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ de... | 0.007474 |
def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):
""" Helper function for element-wise operation.
The function will perform numpy-like broadcasting if needed and call different functions.
Parameters
--------
lhs : NDArray or numeric value
Left-hand side operand.... | 0.001976 |
def waveguide(path,
points,
finish,
bend_radius,
number_of_points=0.01,
direction=None,
layer=0,
datatype=0):
'''
Easy waveguide creation tool with absolute positioning.
path : starting `gdspy.Path... | 0.000548 |
def commit(self, commit):
'''
.. seealso:: :attr:`commit`
'''
c = self.commit
if c:
if not commit:
commit = c[0]
if commit in c:
self._checkout(treeish=commit) | 0.007813 |
def cluster(args):
"""
%prog cluster prefix fastqfiles
Use `vsearch` to remove duplicate reads. This routine is heavily influenced
by PyRAD: <https://github.com/dereneaton/pyrad>.
"""
p = OptionParser(cluster.__doc__)
add_consensus_options(p)
p.set_align(pctid=95)
p.set_outdir()
... | 0.001197 |
def prepare_communication (self):
"""
Find the subdomain rank (tuple) for each processor and
determine the neighbor info.
"""
nsd_ = self.nsd
if nsd_<1:
print('Number of space dimensions is %d, nothing to do' %nsd_)
return
... | 0.016367 |
def disable(self):
"""
Disable the plugin.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
self.client.api.disable_plugin(self.name)
self.reload() | 0.00738 |
def load_data(self, data_np):
"""
Load raw numpy data into the viewer.
"""
image = AstroImage.AstroImage(logger=self.logger)
image.set_data(data_np)
self.set_image(image) | 0.009132 |
def tilt_axes(self):
"""The current tilt along the (X, Y) axes of the tablet's
current logical orientation, in degrees off the tablet's Z axis
and whether they have changed in this event.
That is, if the tool is perfectly orthogonal to the tablet,
the tilt angle is 0. When the top tilts towards the logical t... | 0.022686 |
def intersect_ranges(self, starts, stops):
"""Intersect with a set of ranges.
Parameters
----------
starts : array_like, int
Range start values.
stops : array_like, int
Range stop values.
Returns
-------
idx : SortedIndex
... | 0.002301 |
def stop(self):
"""
::
POST /:login/machines/:id?action=stop
Initiate shutdown of the remote machine.
"""
action = {'action': 'stop'}
j, r = self.datacenter.request('POST', self.path, params=action)
r.raise_for_status() | 0.013115 |
def export(self, class_name, method_name, **kwargs):
"""
Port a trained estimator to the syntax of a chosen programming language.
Parameters
----------
:param class_name : string
The name of the class in the returned result.
:param method_name : string
... | 0.002119 |
def move_item(self, item, origin, destination):
"""
Moves an item from one cluster to anoter cluster.
:param item: the item to be moved.
:param origin: the originating cluster.
:param destination: the target cluster.
"""
if self.equality:
item_index =... | 0.003384 |
def serialize_upload(name, storage, url):
"""
Serialize uploaded file by name and storage. Namespaced by the upload url.
"""
if isinstance(storage, LazyObject):
# Unwrap lazy storage class
storage._setup()
cls = storage._wrapped.__class__
else:
cls = storage.__class__... | 0.002242 |
def equal(self, line1, line2):
'''
return true if exactly equal or if equal but modified,
otherwise return false
return type: BooleanPlus
'''
eqLine = line1 == line2
if eqLine:
return BooleanPlus(True, False)
else:
unchanged_count ... | 0.003106 |
def _create_graph(self, return_target_sources=None):
"""
Create a DiGraph out of the existing edge map.
:param return_target_sources: Used for making up those missing returns
:returns: A networkx.DiGraph() object
"""
if return_target_sources is None:
# We set ... | 0.00205 |
def log_uniform(low, high, size:Optional[List[int]]=None)->FloatOrTensor:
"Draw 1 or shape=`size` random floats from uniform dist: min=log(`low`), max=log(`high`)."
res = uniform(log(low), log(high), size)
return exp(res) if size is None else res.exp_() | 0.022642 |
def get_image_registry_url(self, image_name):
"""
Helper function for obtain registry url of image from it's name
:param image_name: str, short name of an image, example:
- conu:0.5.0
:return: str, image registry url, example:
- 172.30.1.1:5000/myproject/conu:0.5.... | 0.003676 |
def update_input(filelist, ivmlist=None, removed_files=None):
"""
Removes files flagged to be removed from the input filelist.
Removes the corresponding ivm files if present.
"""
newfilelist = []
if removed_files == []:
return filelist, ivmlist
else:
sci_ivm = list(zip(filel... | 0.005319 |
def list_cands(candsfile, threshold=0.):
""" Prints candidate info in time order above some threshold """
loc, prop, d0 = pc.read_candidates(candsfile, snrmin=threshold, returnstate=True)
if 'snr2' in d0['features']:
snrcol = d0['features'].index('snr2')
elif 'snr1' in d0['features']:
... | 0.004944 |
def session_from_client_secrets_file(client_secrets_file, scopes, **kwargs):
"""Creates a :class:`requests_oauthlib.OAuth2Session` instance from a
Google-format client secrets file.
Args:
client_secrets_file (str): The path to the `client secrets`_ .json
file.
scopes (Sequence[s... | 0.001054 |
def run(self):
""" Spawns the metric reporting thread """
self.thr = threading.Thread(target=self.collect_and_report)
self.thr.daemon = True
self.thr.name = "Instana Metric Collection"
self.thr.start() | 0.008299 |
def tf2zpk(b, a):
"""Return zero, pole, gain (z,p,k) representation from a numerator,
denominator representation of a linear filter.
Convert zero-pole-gain filter parameters to transfer function form
:param ndarray b: numerator polynomial.
:param ndarray a: numerator and denominator polynomials.
... | 0.005192 |
def include_file(filename, lineno, local_first):
""" Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
If local_first is True, then it will first search the file in the
local path before looking for it in the in... | 0.001264 |
def _build_path(self):
'''
Constructs the actual request URL with accompanying query if any.
Returns:
None: But does modify self.path, which contains the final
request path sent to the server.
'''
if not self.path:
self.path = '/'
... | 0.001938 |
def add_robot(self, controller):
"""Add a robot controller"""
# connect to the controller
# -> this is to support module robots
controller.on_mode_change(self._on_robot_mode_change)
self.robots.append(controller) | 0.007905 |
def format_meta_lines(cls, meta, labels, offset, **kwargs):
'''Return all information from a given meta dictionary in a list of lines'''
lines = []
# Name and underline
name = meta['package_name']
if 'version' in meta:
name += '-' + meta['version']
if 'custom... | 0.004617 |
def remove_node(cls, cluster_id_label, private_dns, parameters=None):
"""
Add a node to an existing cluster
"""
conn = Qubole.agent(version=Cluster.api_version)
parameters = {} if not parameters else parameters
data = {"private_dns" : private_dns, "parameters" : parameter... | 0.00995 |
def generate_log_between_tags(self, older_tag, newer_tag):
"""
Generate log between 2 specified tags.
:param dict older_tag: All issues before this tag's date will be
excluded. May be special value, if new tag is
the first tag. (Mean... | 0.001733 |
def _print_value(self):
"""Generates the table values."""
for line in range(self.Lines_num):
for col, length in zip(self.Table, self.AttributesLength):
vals = list(col.values())[0]
val = vals[line] if len(vals) != 0 and line < len(vals) else ''
... | 0.004149 |
def update(self, callback=None, errback=None, **kwargs):
"""
Update scope group configuration. Pass a list of keywords and their values to
update. For the list of keywords available for address configuration, see :attr:`ns1.rest.ipam.Scopegroups.INT_FIELDS` and :attr:`ns1.rest.ipam.Scopegroups.P... | 0.005429 |
def init_search(self):
"""Call the generators to generate the initial architectures for the search."""
if self.verbose:
logger.info("Initializing search.")
for generator in self.generators:
graph = generator(self.n_classes, self.input_shape).generate(
self... | 0.004573 |
def read_lsm_scaninfo(fh):
"""Read LSM ScanInfo structure from file and return as dict."""
block = {}
blocks = [block]
unpack = struct.unpack
if struct.unpack('<I', fh.read(4))[0] != 0x10000000:
# not a Recording sub block
log.warning('read_lsm_scaninfo: invalid LSM ScanInfo structur... | 0.000645 |
def update(self, resource, timeout=-1):
"""
Updates a Logical Switch.
Args:
resource (dict): Object to update.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView, just stop... | 0.005 |
def filter_skiplines(code, errors):
"""Filter lines by `noqa`.
:return list: A filtered errors
"""
if not errors:
return errors
enums = set(er.lnum for er in errors)
removed = set([
num for num, l in enumerate(code.split('\n'), 1)
if num in enums and SKIP_PATTERN(l)
... | 0.002353 |
def to_text(self):
"""Render a Text MessageElement as plain text.
:returns: The plain text representation of the Text MessageElement.
:rtype: basestring
"""
if self.items is None:
return
else:
text = ''
for item in self.items:
... | 0.005168 |
def is_applicable(cls, conf):
"""Return whether this promoter is applicable for given conf"""
return all((
URLPromoter.is_applicable(conf),
not cls.needs_firefox(conf),
)) | 0.009132 |
def _get_baremetal_connections(self, port,
only_active_switch=False,
from_segment=False):
"""Get switch ips and interfaces from baremetal transaction.
This method is used to extract switch/interface
information from transacti... | 0.00206 |
def component_type(self):
"""
Returns the classname of the elements.
:return: the class of the elements
:rtype: str
"""
cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;")
comptype = javabridge.call(cls, "getComponentType", "()Ljava/lang/Class;... | 0.007538 |
def lstrip(self, chars=None):
""" Like str.lstrip, except it returns the Colr instance. """
return self.__class__(
self._str_strip('lstrip', chars),
no_closing=chars and (closing_code in chars),
) | 0.008197 |
def acceptCompletion( self ):
"""
Accepts the current completion and inserts the code into the edit.
:return <bool> accepted
"""
tree = self._completerTree
if not tree:
return False
tree.hide()
ite... | 0.014493 |
def _analyze_state(state: GlobalState):
"""
:param state: the current state
:return: returns the issues for that corresponding state
"""
instruction = state.get_current_instruction()
annotations = cast(
List[MultipleSendsAnnotation],
list(state.get_annotations(MultipleSendsAnnot... | 0.002406 |
def form_valid(self, form):
"""After the form is valid lets let people know"""
ret = super(ProjectCopy, self).form_valid(form)
self.copy_relations()
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Project %s copied' % self.object.name)
... | 0.009063 |
def candidates(self):
"""A list of candidate addresses (as dictionaries) from a geocode
operation"""
# convert x['location'] to a point from a json point struct
def cditer():
for candidate in self._json_struct['candidates']:
newcandidate = candidate.copy()
... | 0.004057 |
def parse(self, contents):
"""Parse the document.
:param contents: The text contents of the document.
:rtype: a *generator* of tokenized text.
"""
i = 0
for text in contents.split(self.delim):
if not len(text.strip()):
continue
wor... | 0.002116 |
def _on_process_error(self, error):
"""
Display child process error in the text edit.
"""
if self is None:
return
err = PROCESS_ERROR_STRING[error]
self._formatter.append_message(err + '\r\n', output_format=OutputFormat.ErrorMessageFormat) | 0.010033 |
def resolve_pid(fetched_pid):
"""Retrieve the real PID given a fetched PID.
:param pid: fetched PID to resolve.
"""
return PersistentIdentifier.get(
pid_type=fetched_pid.pid_type,
pid_value=fetched_pid.pid_value,
pid_provider=fetched_pid.provider.pid_provider
) | 0.003268 |
def sbot_executable():
"""
Find shoebot executable
"""
gsettings=load_gsettings()
venv = gsettings.get_string('current-virtualenv')
if venv == 'Default':
sbot = which('sbot')
elif venv == 'System':
# find system python
env_venv = os.environ.get('VIRTUAL_ENV')
... | 0.003563 |
def _countOverlapIndices(self, i, j):
"""
Return the overlap between bucket indices i and j
"""
if self.bucketMap.has_key(i) and self.bucketMap.has_key(j):
iRep = self.bucketMap[i]
jRep = self.bucketMap[j]
return self._countOverlap(iRep, jRep)
else:
raise ValueError("Either i... | 0.017699 |
def _status_code_check(self, response: Dict[str, Any]):
"""检查响应码并进行对不同的响应进行处理.
主要包括:
+ 编码在500~599段为服务异常,直接抛出对应异常
+ 编码在400~499段为调用异常,为对应ID的future设置异常
+ 编码在300~399段为警告,会抛出对应警告
+ 编码在200~399段为执行成功响应,将结果设置给对应ID的future.
+ 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应
Param... | 0.001444 |
def check_token(token):
''' Verify http header token authentification '''
user = models.User.objects(api_key=token).first()
return user or None | 0.006452 |
def sqlinsert(table, row):
"""Generates SQL insert into table ...
Returns (sql, parameters)
>>> sqlinsert('mytable', {'field1': 2, 'field2': 'toto'})
('insert into mytable (field1, field2) values (%s, %s)', [2, 'toto'])
>>> sqlinsert('t2', {'id': 1, 'name': 'Toto'})
('insert into t2 (id, name) ... | 0.001587 |
def remap_overlapping_column_names(table_op, root_table, data_columns):
"""Return an ``OrderedDict`` mapping possibly suffixed column names to
column names without suffixes.
Parameters
----------
table_op : TableNode
The ``TableNode`` we're selecting from.
root_table : TableNode
... | 0.000851 |
def to_dict(self):
"""Serialize the model into a Python dict of simple types.
Note that this method requires that the model is bound with
``@bind_schema``.
"""
try:
data, _ = self.schema.dump(self)
except ValidationError as ex:
raise ModelValidati... | 0.006865 |
def touch(self, edited=False):
"""Mark the node as dirty.
Args:
edited (bool): Whether to set the edited time.
"""
self._dirty = True
dt = datetime.datetime.utcnow()
self.timestamps.updated = dt
if edited:
self.timestamps.edited = dt | 0.006369 |
def signed_distance(mesh, points):
"""
Find the signed distance from a mesh to a list of points.
* Points OUTSIDE the mesh will have NEGATIVE distance
* Points within tol.merge of the surface will have POSITIVE distance
* Points INSIDE the mesh will have POSITIVE distance
Parameters
------... | 0.000947 |
def visit_Name(self, node):
"""
Return dependencies for given variable.
It have to be register first.
"""
if node.id in self.naming:
return self.naming[node.id]
elif node.id in self.global_declarations:
return [frozenset([self.global_declarations[... | 0.003205 |
def _parse_keys(row, line_num):
""" Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int
"""
... | 0.002401 |
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text | 0.011628 |
def cancel(self):
'''
Cancel a running workflow.
Args:
None
Returns:
None
'''
if not self.id:
raise WorkflowError('Workflow is not running. Cannot cancel.')
if self.batch_values:
self.workflow.batch_workflow_canc... | 0.005168 |
def _update_project(self, request, data):
"""Update project info"""
domain_id = identity.get_domain_id_for_operation(request)
try:
project_id = data['project_id']
# add extra information
if keystone.VERSIONS.active >= 3:
EXTRA_INFO = getattr(s... | 0.001837 |
def _get_option(config, supplement, section, option, fallback=None):
"""
Reads an option for a configuration file.
:param configparser.ConfigParser config: The main config file.
:param configparser.ConfigParser supplement: The supplement config file.
:param str section: The name... | 0.006073 |
def fnmatchcase(name, pat):
"""Test whether FILENAME matches PATTERN, including case.
This is a version of fnmatch() which doesn't case-normalize
its arguments.
"""
try:
re_pat = _cache[pat]
except KeyError:
res = translate(pat)
if len(_cache) >= _MAXCACHE:
... | 0.002165 |
def set_exception(self, exception):
"""Set the Future's exception."""
self._exception = exception
self._result_set = True
self._invoke_callbacks(self) | 0.010989 |
def save_object(filename, obj):
"""Compresses and pickles given object to the given filename."""
logging.info('saving {}...'.format(filename))
try:
with gzip.GzipFile(filename, 'wb') as f:
f.write(pickle.dumps(obj, 1))
except Exception as e:
logging.error('save failure: {}'.f... | 0.002915 |
def index_modules(idx=None, path=None):
"""
Indexes objs from all modules
"""
suppress_output()
modules = defaultdict(list)
pkglist = pkgutil.walk_packages(onerror=lambda x: True)
print(pkglist)
if path:
pkglist = pkgutil.walk_packages(path, onerror=lambda x: True)
for modl, ... | 0.002445 |
def ldap_plugin(self):
""" Configures the LDAP plugin """
name = self._ask_with_default("Authentication method name (will be displayed on the login page)", "LDAP")
prefix = self._ask_with_default("Prefix to append to the username before db storage. Usefull when you have more than one auth method... | 0.005022 |
def relaxNGValidateFullElement(self, ctxt, elem):
"""Validate a full subtree when
xmlRelaxNGValidatePushElement() returned 0 and the content
of the node has been expanded. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
... | 0.01559 |
def _bresenham(self, faces, dx):
r'''
A Bresenham line function to generate points to fill in for the fibers
'''
line_points = []
for face in faces:
# Get in hull order
fx = face[:, 0]
fy = face[:, 1]
fz = face[:, 2]
# F... | 0.001474 |
def train(
self,
true_sampler,
generative_model,
discriminative_model,
iter_n=100,
k_step=10
):
'''
Train.
Args:
true_sampler: Sampler which draws samples from the `true` distribution.
generative_... | 0.003923 |
def get_digest_keys(self):
"""Returns a list of the type choices"""
digest_keys = []
for col in xrange(self.GetNumberCols()):
digest_key = self.GetCellValue(self.has_header, col)
if digest_key == "":
digest_key = self.digest_types.keys()[0]
di... | 0.005319 |
def aesthetics(cls):
"""
Return a set of all non-computed aesthetics for this stat.
stats should not override this method.
"""
aesthetics = cls.REQUIRED_AES.copy()
calculated = get_calculated_aes(cls.DEFAULT_AES)
for ae in set(cls.DEFAULT_AES) - set(calculated):
... | 0.005319 |
def usage_example(phrase, format='json'):
"""Takes the source phrase and queries it to the urbandictionary API
:params phrase: word for which usage_example is to be found
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid... | 0.003247 |
def daily3D(inst, bin1, label1, bin2, label2, bin3, label3,
data_label, gate, returnBins=False):
"""3D Daily Occurrence Probability of data_label > gate over a season.
If data_label is greater than gate atleast once per day,
then a 100% occurrence probability results. Season delineated by... | 0.009375 |
def comment_import(r, unused_dot_list):
"""Comment out import for {dot_str}."""
unused_dot_str = ".".join(unused_dot_list)
for n in r("ImportNode"):
if n.names()[0] == unused_dot_str:
# The "!" is inserted so that this line doesn't show up when searching for
# the comment pat... | 0.00495 |
async def get_schemes(self) -> List[Scheme]:
"""Return supported uri schemes."""
return [
Scheme.make(**x)
for x in await self.services["avContent"]["getSchemeList"]()
] | 0.009217 |
def create_db(self, instance_name, instance_type,
admin_username, admin_password, security_groups=None, db_name=None,
storage_size_gb=DEFAULT_STORAGE_SIZE_GB,
timeout_s=DEFAULT_TIMEOUT_S):
"""
Creates a database instance.
This method blocks until the db insta... | 0.002218 |
def print_logins(logins):
"""Prints out the login history for a user"""
table = formatting.Table(['Date', 'IP Address', 'Successufl Login?'])
for login in logins:
table.add_row([login.get('createDate'), login.get('ipAddress'), login.get('successFlag')])
return table | 0.006897 |
def start_optimisation(self, rounds: int, max_angle: float,
max_distance: float, temp: float=298.15,
stop_when=None, verbose=None):
"""Starts the loop fitting protocol.
Parameters
----------
rounds : int
The number of Mon... | 0.006397 |
def write(self, fptr):
"""Write a Data Reference box to file.
"""
self._write_validate()
# Very similar to the way a superbox is written.
orig_pos = fptr.tell()
fptr.write(struct.pack('>I4s', 0, b'dtbl'))
# Write the number of data entry url boxes.
write... | 0.003361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.