text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def obj_to_string(obj):
'''Render an object into a unicode string if possible'''
if not obj:
return None
elif isinstance(obj, bytes):
return obj.decode('utf-8')
elif isinstance(obj, basestring):
return obj
elif is_lazy_string(obj):
return obj.value
elif hasattr(ob... | 0.002506 |
def is_purine(nucleotide, allow_extended_nucleotides=False):
"""Is the nucleotide a purine"""
if not allow_extended_nucleotides and nucleotide not in STANDARD_NUCLEOTIDES:
raise ValueError(
"{} is a non-standard nucleotide, neither purine or pyrimidine".format(nucleotide))
return nucleot... | 0.008696 |
def should_try_kafka_again(error):
"""Determine if the error means to retry or fail, True to retry."""
msg = 'Unable to retrieve'
return isinstance(error, KafkaException) and str(error).startswith(msg) | 0.004695 |
def sign_data(self, name, hash_input, key_version=None, hash_algorithm="sha2-256", context="", prehashed=False,
signature_algorithm="pss", mount_point=DEFAULT_MOUNT_POINT):
"""Return the cryptographic signature of the given data using the named key and the specified hash algorithm.
Th... | 0.006366 |
def run(self):
'''Run loop'''
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except ... | 0.003322 |
def map(self, callback):
"""
Run a map over each of the item.
:param callback: The map function
:type callback: callable
:rtype: Collection
"""
return self.__class__(list(map(callback, self.items))) | 0.007813 |
def _match_abbrev(s, wordmap):
"""_match_abbrev(s : string, wordmap : {string : Option}) -> string
Return the string key in 'wordmap' for which 's' is an unambiguous
abbreviation. If 's' is found to be ambiguous or doesn't match any of
'words', raise BadOptionError.
"""
# Is there an exact mat... | 0.001104 |
def bulk_write(self, requests, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent.
... | 0.009281 |
def remove(self, name):
"""Remove workspace from config file."""
if not (self.exists(name)):
raise ValueError("Workspace `%s` doesn't exists." % name)
self.config["workspaces"].pop(name, 0)
self.config.write() | 0.007874 |
def get_worksheet(self, index):
"""Returns a worksheet with specified `index`.
:param index: An index of a worksheet. Indexes start from zero.
:type index: int
:returns: an instance of :class:`gsperad.models.Worksheet`
or `None` if the worksheet is not found.
... | 0.002766 |
def from_value(cls, value):
"""This is how an instance is created when we read a
MatlabObject from a MAT file.
"""
instance = OctaveUserClass.__new__(cls)
instance._address = '%s_%s' % (instance._name, id(instance))
instance._ref().push(instance._address, value)
... | 0.005935 |
def htmlFromThing(thing,title):
"""create pretty formatted HTML from a things dictionary."""
try:
thing2 = copy.copy(thing)
except:
print("crashed copying the thing! I can't document it.")
return False
stuff=analyzeThing(thing2)
names2=list(stuff.keys())
for i,na... | 0.018507 |
def _start_element (self, tag, attrs, end):
"""
Print HTML element with end string.
@param tag: tag name
@type tag: string
@param attrs: tag attributes
@type attrs: dict
@param end: either > or />
@type end: string
@return: None
"""
... | 0.003989 |
def ec2eq(self):
"""Convert ecliptic coordinates to equatorial coordinates"""
import math
#from numpy.matlib import sin, cos, arcsin, arctan2
from math import sin, cos
from math import asin as arcsin
from math import atan2 as arctan2
from math import acos as arcc... | 0.023711 |
def unset(ctx, key):
'''Removes the given key.'''
file = ctx.obj['FILE']
quote = ctx.obj['QUOTE']
success, key = unset_key(file, key, quote)
if success:
click.echo("Successfully removed %s" % key)
else:
exit(1) | 0.004 |
def _pool_put(pool_semaphore, tasks, put_to_pool_in, pool_size, id_self, \
is_stopping):
"""
(internal) Intended to be run in a seperate thread. Feeds tasks into
to the pool whenever semaphore permits. Finishes if self._stopping is
set.
"""
log.debug(... | 0.013354 |
def add_permissions(self, grp_name, resource, permissions):
"""
Add additional permissions for the group associated with the resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to ... | 0.004831 |
def dafgn(lenout=_default_len_out):
"""
Return (get) the name for the current array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgn_c.html
:param lenout: Length of array name string.
:type lenout: int
:return: Name of current array.
:rtype: str
"""
... | 0.002155 |
def zip(self, *args):
"""
Zip together multiple lists into a single array -- elements that share
an index go together.
"""
args = list(args)
args.insert(0, self.obj)
maxLen = _(args).chain().collect(lambda x, *args: len(x)).max().value()
for i, v in enumer... | 0.005714 |
def is_valid_dir(path):
''' Returns True if provided directory exists and is a directory, or False otherwise. '''
return os.path.exists(path) and os.path.isdir(path) | 0.011561 |
def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... | 0.002981 |
def pg_ctl(self, cmd, *args, **kwargs):
"""Builds and executes pg_ctl command
:returns: `!True` when return_code == 0, otherwise `!False`"""
pg_ctl = [self._pgcommand('pg_ctl'), cmd]
return subprocess.call(pg_ctl + ['-D', self._data_dir] + list(args), **kwargs) == 0 | 0.01 |
def expand_dataset(X, y_proba, factor=10, random_state=None, extra_arrays=None):
"""
Convert a dataset with float multiclass probabilities to a dataset
with indicator probabilities by duplicating X rows and sampling
true labels.
"""
rng = check_random_state(random_state)
extra_arrays = extra... | 0.003295 |
def prep_folder(self, seq):
"""Take in a sequence string and prepares the folder for the I-TASSER run."""
itasser_dir = op.join(self.root_dir, self.id)
if not op.exists(itasser_dir):
os.makedirs(itasser_dir)
tmp = {self.id: seq}
fasta.write_fasta_file_from_dict(ind... | 0.00566 |
def dup_token(th):
'''
duplicate the access token
'''
# TODO: is `duplicate_token` the same?
sec_attr = win32security.SECURITY_ATTRIBUTES()
sec_attr.bInheritHandle = True
return win32security.DuplicateTokenEx(
th,
win32security.SecurityImpersonation,
win32con.MAXIMUM_ALL... | 0.002611 |
def get_serializer_class(self, action=None):
"""
Return the serializer class depending on request method.
Attribute of proper serializer should be defined.
"""
if action is not None:
return getattr(self, '%s_serializer_class' % action)
else:
return... | 0.005391 |
def _generic_model(self, z3_model):
"""
Converts a Z3 model to a name->primitive dict.
"""
model = { }
for m_f in z3_model:
n = _z3_decl_name_str(m_f.ctx.ctx, m_f.ast).decode()
m = m_f()
me = z3_model.eval(m)
model[n] = self._abstra... | 0.007958 |
def show(self,
clustered=False,
ax_carpet=None,
label_x_axis='time point',
label_y_axis='voxels/ROI'):
"""
Displays the carpet in the given axis.
Parameters
----------
clustered : bool, optional
Flag to indicate wh... | 0.004975 |
def git_clone(sub_repo, branch, commit = None, cwd = None, no_submodules = False):
'''
This clone mimicks the way Travis-CI clones a project's repo. So far
Travis-CI is the most limiting in the sense of only fetching partial
history of the repo.
'''
if not cwd:
... | 0.029489 |
def _initializeBucketMap(self, maxBuckets, offset):
"""
Initialize the bucket map assuming the given number of maxBuckets.
"""
# The first bucket index will be _maxBuckets / 2 and bucket indices will be
# allowed to grow lower or higher as long as they don't become negative.
# _maxBuckets is req... | 0.002909 |
def loads(content, ac_parser=None, ac_dict=None, ac_template=False,
ac_context=None, **options):
"""
:param content: Configuration file's content (a string)
:param ac_parser: Forced parser type or ID or parser object
:param ac_dict:
callable (function or class) to make mapping object w... | 0.000508 |
def extract_helices_dssp(in_pdb):
"""Uses DSSP to find alpha-helices and extracts helices from a pdb file.
Returns a length 3 list with a helix id, the chain id and a dict
containing the coordinates of each residues CA.
Parameters
----------
in_pdb : string
Path to a PDB file.
"""
... | 0.001463 |
def cookietostr(self):
"Cookie values are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8)."
self.cookies = dict((k, (v.decode(self.encoding) if not isinstance(v, str) else v)) for k,v in self.cookies.items())
return self.cookies | 0.016892 |
def fit(self, sequences, y=None):
"""Fit the kcenters clustering on the data
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries, or ``md.Trajectory``. Each
sequence may have a differ... | 0.004498 |
def get_raw(self, name=None):
'''Shortcut for getting a :class:`~statsd.raw.Raw` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Raw) | 0.007605 |
def execute(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
jid='',
kwarg=None,
**kwargs):
'''
.. versionadded:: 2017.7.0
Execute ``fun`` on all minions matched by ``tgt`` and ``tgt_type``.
Paramete... | 0.001605 |
def get_cookie_header(self, req):
"""
:param req: object with httplib.Request interface
Actually, it have to have `url` and `headers` attributes
"""
mocked_req = MockRequest(req)
self.cookiejar.add_cookie_header(mocked_req)
return mocked_req.get_new_headers().... | 0.006006 |
def latinize(mapping, bind, values):
""" Transliterate a given string into the latin alphabet. """
for v in values:
if isinstance(v, six.string_types):
v = transliterate(v)
yield v | 0.00463 |
def run(self):
"""Run robustness command."""
reaction = self._get_objective()
if not self._mm.has_reaction(reaction):
self.fail('Specified biomass reaction is not in model: {}'.format(
reaction))
varying_reaction = self._args.varying
if not self._mm.... | 0.000636 |
def read(fnames, calculation_mode='', region_constraint='',
ignore_missing_costs=(), asset_nodes=False, check_dupl=True,
tagcol=None, by_country=False):
"""
Call `Exposure.read(fname)` to get an :class:`Exposure` instance
keeping all the assets in memory or
`Exp... | 0.001902 |
def browseprofilegui(profilelog):
'''
Browse interactively a profile log in GUI using RunSnakeRun and SquareMap
'''
from runsnakerun import runsnake # runsnakerun needs wxPython lib, if it's not available then we can pass if we don't want a GUI. RunSnakeRun is only used for GUI visualisation, not for pr... | 0.008333 |
def list_resource_record_sets_by_zone_id_parser(e_root, connection, zone_id):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id`
method.
:param lxml.etree._Element e_root: The root node of the etree parsed
response from ... | 0.001057 |
def connect_xmlstream(
jid,
metadata,
negotiation_timeout=60.,
override_peer=[],
loop=None,
logger=logger):
"""
Prepare and connect a :class:`aioxmpp.protocol.XMLStream` to a server
responsible for the given `jid` and authenticate against that server using
... | 0.000217 |
def contributionStatus(self):
"""gets the contribution status of a user"""
import time
url = "%s/contributors/%s/activeContribution" % (self.root, quote(self.contributorUID))
params = {
"agolUserToken" : self._agolSH.token,
"f" : "json"
}
res = sel... | 0.013378 |
def check(somestr, check = STRING, interchange = ALL):
"""
Checks that some string, word or text are palindrome. Checking performs case-insensitive
:param str somestr:
It is some string that will be checked for palindrome
:keyword int check:
It is mode of checking. Follows modes are available:
... | 0.046275 |
def require_http_methods(request_methods):
"""
Decorator to make a function view only accept particular request methods.
Usage::
@require_http_methods(["GET", "POST"])
def function_view(request):
# HTTP methods != GET or POST results in 405 error code response
"""
if not... | 0.000473 |
def put(self, route: str(), callback: object()):
"""
Binds a PUT route with the given callback
:rtype: object
"""
self.__set_route('put', {route: callback})
return RouteMapping | 0.008929 |
def base_concrete_model(abstract, model):
"""
Used in methods of abstract models to find the super-most concrete
(non abstract) model in the inheritance chain that inherits from the
given abstract model. This is so the methods in the abstract model can
query data consistently across the correct conc... | 0.000684 |
def run_job(self, job_id, array_id = None):
"""Overwrites the run-job command from the manager to extract the correct job id before calling base class implementation."""
# get the unique job id from the given grid id
self.lock()
jobs = list(self.session.query(Job).filter(Job.id == job_id))
if len(jo... | 0.010152 |
def add_fields(self, field_dict):
"""Add a mapping of field names to PayloadField instances.
:API: public
"""
for key, field in field_dict.items():
self.add_field(key, field) | 0.010152 |
def keyPressEvent(self, keyEvent: QtGui.QKeyEvent):
"""
Undo safe wrapper for the native ``keyPressEvent`` method.
|Args|
* ``keyEvent`` (**QKeyEvent**): the key event to process.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one ... | 0.004415 |
def get_points(self):
"""Returns a ketama compatible list of (position, nodename) tuples.
"""
return [(k, self.runtime._ring[k]) for k in self.runtime._keys] | 0.01105 |
def create_datacenter(datacenter_name, service_instance=None):
'''
Creates a datacenter.
Supported proxies: esxdatacenter
datacenter_name
The datacenter name
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block:: bash
... | 0.002045 |
def decrypt(crypt_text) -> str:
""" Use config.json key to decrypt """
cipher = Fernet(current_app.config['KEY'])
if not isinstance(crypt_text, bytes):
crypt_text = str.encode(crypt_text)
return cipher.decrypt(crypt_text).decode("utf-8") | 0.006993 |
def get_environment() -> Environment:
"""
Returns the jinja2 templating environment updated with the most recent
cauldron environment configurations
:return:
"""
env = JINJA_ENVIRONMENT
loader = env.loader
resource_path = environ.configs.make_path(
'resources', 'templates',
... | 0.001704 |
def get_limit_action(self, criticity, stat_name=""):
"""Return the tuple (action, repeat) for the alert.
- action is a command line
- repeat is a bool
"""
# Get the action for stat + header
# Exemple: network_wlan0_rx_careful_action
# Action key available ?
... | 0.002584 |
def _find_module(mod_name):
"""
Iterate over each part instead of calling imp.find_module directly.
This function is able to find submodules (e.g. sickit.tree)
"""
path = None
for part in mod_name.split('.'):
if path is not None:
path = [path]
file, path, description ... | 0.002315 |
def report(policies, start_date, options, output_fh, raw_output_fh=None):
"""Format a policy's extant records into a report."""
regions = set([p.options.region for p in policies])
policy_names = set([p.name for p in policies])
formatter = Formatter(
policies[0].resource_manager.resource_type,
... | 0.001112 |
def _show(self, res, err, prefix='', colored=False):
""" Show result or error """
if self.kind is 'local':
what = res if not err else err
print(what)
return
if self.kind is 'remote':
if colored:
red, green, reset = Fore.RED, Fore.... | 0.00339 |
def stop(self, precision=0):
""" Stops the timer, adds it as an interval to :prop:intervals
@precision: #int number of decimal places to round to
-> #str formatted interval time
"""
self._stop = time.perf_counter()
return self.add_interval(precision) | 0.006515 |
def eth_getBalance(self, address):
"""Get account balance.
:param address:
:return:
"""
account = self.reader._get_account(address)
return account.balance | 0.009852 |
def getParticleInfo(self, modelId):
"""Return particle info for a specific modelId.
Parameters:
---------------------------------------------------------------------
modelId: which model Id
retval: (particleState, modelId, errScore, completed, matured)
"""
entry = self._allResults[self._... | 0.002123 |
def __build_signature(self, data, saml_type, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1):
"""
Builds the Signature
:param data: The Request data
:type data: dict
:param saml_type: The target URL the user should be redirected to
:type saml_type: string SAMLRequest ... | 0.003376 |
def open_scene(f, kwargs=None):
"""Opens the given JB_File
:param f: the file to open
:type f: :class:`jukeboxcore.filesys.JB_File`
:param kwargs: keyword arguments for the command maya.cmds file.
defaultflags that are always used:
:open: ``True``
... | 0.003405 |
def configure(root_url, **kwargs):
""""
Notice that `configure` can either apply to the default configuration or
`Client.config`, which is the configuration used by the current thread
since `Client` inherits form `threading.local`.
"""
default = kwargs.pop('default', True)
kwargs['client_ag... | 0.001639 |
def _get_classes(package_name, base_class):
"""
search monits or works classes. Class must have 'name' attribute
:param package_name: 'monits' or 'works'
:param base_class: Monit or Work
:return: tuple of tuples monit/work-name and class
"""
classes = {}
... | 0.003957 |
def compose(layers, bbox=None, layer_filter=None, color=None, **kwargs):
"""
Compose layers to a single :py:class:`PIL.Image`.
If the layers do not have visible pixels, the function returns `None`.
Example::
image = compose([layer1, layer2])
In order to skip some layers, pass `layer_filte... | 0.000397 |
def filter_active(self, *args, **kwargs):
"""
Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defa... | 0.001887 |
def show(self):
"""Controls if the viewlet should be rendered
"""
url = self.request.getURL()
# XXX: Hack to show the viewlet only on the AR base_view
if not any(map(url.endswith, ["base_view", "manage_results"])):
return False
return self.attachments_view.use... | 0.007229 |
def parse_input(tagged_string, disable_colors, keep_tags):
"""Perform the actual conversion of tags to ANSI escaped codes.
Provides a version of the input without any colors for len() and other methods.
:param str tagged_string: The input unicode value.
:param bool disable_colors: Strip all colors in ... | 0.002657 |
def platform(cls):
"""
What Operating System (and sub-system like glibc / musl)
"""
system_name = platform.system()
if system_name == "Linux":
libc = cls.libc()
return "unknown-linux-{libc}".format(libc=libc)
elif system_name == "Darwin":
... | 0.005168 |
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None):
"""
Create a service from an endpoint if it does not already exists.
"""
from models import Service
if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0:
# check if endpoint is... | 0.005842 |
def transitions(self):
"""Dense [k-1]x4 transition frequency matrix"""
if self._transitions is not None:
return self._transitions
transitions = self.array.astype(np.float)
transitions /= transitions.sum(1)[:, np.newaxis]
self._transitions = transitions
return ... | 0.006042 |
def structured_traceback(self, etype, evalue, etb, tb_offset=None,
context=5):
"""Return a nice text document describing the traceback."""
tb_offset = self.tb_offset if tb_offset is None else tb_offset
# some locals
try:
etype = etype.__name__
... | 0.007238 |
def set(self, key, value):
"""Set a configuration property."""
# Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet.
if self._jconf is not None:
self._jconf.set(key, unicode(value))
else:
self._conf[key] = unicode(value)
... | 0.008982 |
def template(filename):
"""
Decorator
"""
def method_wrapper(method):
@wraps(method)
def jinja_wrapper(*args, **kwargs):
ret = method(*args, **kwargs)
return render_template(filename, ret)
return jinja_wrapper
return method_wrapper | 0.003311 |
def _equivalent(self, other):
"""Compare two entities of the same class, excluding keys."""
if other.__class__ is not self.__class__: # TODO: What about subclasses?
raise NotImplementedError('Cannot compare different model classes. '
'%s is not %s' % (self.__class__.__name... | 0.008396 |
def token(self, value):
"""
Set the Token of the message.
:type value: String
:param value: the Token
:raise AttributeError: if value is longer than 256
"""
if value is None:
self._token = value
return
if not isinstance(value, str)... | 0.004525 |
def get_connection(self, name):
"""Returns the properties for a connection name
This method will return the settings for the configuration specified
by name. Note that the name argument should only be the name.
For instance, give the following eapi.conf file
.. code-block:: i... | 0.002058 |
def write_header(term='bash', tree_dir=None, name=None):
''' Write proper file header in a given shell format
Parameters:
term (str):
The type of shell header to write, can be "bash", "tsch", or "modules"
tree_dir (str):
The path to this repository
name (str):
... | 0.002152 |
def getHourTable(date, pos):
""" Returns an HourTable object. """
table = hourTable(date, pos)
return HourTable(table, date) | 0.007353 |
def _get_user_ns_object(shell, path):
"""Get object from the user namespace, given a path containing
zero or more dots. Return None if the path is not valid.
"""
parts = path.split('.', 1)
name, attr = parts[0], parts[1:]
if name in shell.user_ns:
if attr:
try:
... | 0.002 |
def render_koji(self):
"""
if there is yum repo in user params, don't pick stuff from koji
"""
phase = 'prebuild_plugins'
plugin = 'koji'
if not self.pt.has_plugin_conf(phase, plugin):
return
if self.user_params.yum_repourls.value:
self.pt... | 0.007862 |
def _get_updated_rows(self, auth, function):
""" Get rows updated by last update query
* `function` [function]
Function to use for searching (one of the search_* functions).
Helper function used to fetch all rows which was updated by the
latest UPDATE ... RE... | 0.003167 |
def validate_and_decode(jwt_bu64, cert_obj):
"""Example for validating the signature of a JWT using only the cryptography
library.
Note that this does NOT validate the claims in the claim set.
"""
public_key = cert_obj.public_key()
message = '.'.join(d1_common.cert.jwt.get_bu64_tup(jwt_bu64)[:... | 0.002522 |
def create_certificate_signing_request(self, body, **kwargs):
"""
create a CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_certificate_signing_request(body,... | 0.004507 |
def _parallel_exec(self, hosts):
''' handles mulitprocessing when more than 1 fork is required '''
if not hosts:
return
p = multiprocessing.Pool(self.forks)
results = []
#results = p.map(multiprocessing_runner, hosts) # can't handle keyboard interrupt
results ... | 0.009195 |
def _convert_rename(self, fc):
"""Convert a FileRenameCommand into a new FileCommand.
:return: None if the rename is being ignored, otherwise a
new FileCommand based on the whether the old and new paths
are inside or outside of the interesting locations.
"""
old = ... | 0.00219 |
def __find_pair_clusters(self, clusters):
"""!
@brief Returns pair of clusters that are best candidates for merging in line with goodness measure.
The pair of clusters for which the above goodness measure is maximum is the best pair of clusters to be merged.
@... | 0.015228 |
def back_bfs(self, start, end=None):
"""
Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=False)] | 0.009901 |
def explainParam(self, param):
"""
Explains a single param and returns its name, doc, and optional
default value and user-supplied value in a string.
"""
param = self._resolveParam(param)
values = []
if self.isDefined(param):
if param in self._defaultP... | 0.00295 |
def set_curves(self, curves):
u''' Set supported curves by name, nid or nist.
:param str | tuple(int) curves: Example "secp384r1:secp256k1", (715, 714), "P-384", "K-409:B-409:K-571", ...
:return: 1 for success and 0 for failure
'''
retVal = None
if isinstance(curves, str... | 0.005747 |
async def authenticate_with_device(atv):
"""Perform device authentication and print credentials."""
credentials = await atv.airplay.generate_credentials()
await atv.airplay.load_credentials(credentials)
try:
await atv.airplay.start_authentication()
pin = input('PIN Code: ')
awai... | 0.001919 |
def get_categories(self, job_id, category_id=None, body=None, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-category.html>`_
:arg job_id: The name of the job
:arg category_id: The identifier of the category definition of interest
:arg ... | 0.004582 |
def submit_fatjar(cl_args, unknown_args, tmp_dir):
'''
We use the packer to make a package for the jar and dump it
to a well-known location. We then run the main method of class
with the specified arguments. We pass arguments as an environment variable HERON_OPTIONS.
This will run the jar file with the topol... | 0.010079 |
def patch_ref(self, sha):
""" Patch reference on the origin master branch
:param sha: Sha to use for the branch
:return: Status of success
:rtype: str or self.ProxyError
"""
uri = "{api}/repos/{origin}/git/refs/heads/{branch}".format(
api=self.github_api_url,... | 0.001916 |
def _onSize(self, evt):
"""
Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.
"""
DEBUG_MSG("_onSize()", 2, self)
# Create a new, correctly s... | 0.005176 |
def create_log_stream(awsclient, log_group_name, log_stream_name):
"""Creates a log stream for the specified log group.
:param log_group_name: log group name
:param log_stream_name: log stream name
:return:
"""
client_logs = awsclient.get_client('logs')
response = client_logs.create_log_st... | 0.002463 |
def from_json(cls, data, result=None):
"""
Create new RelationMember element from JSON data
:param child: Element data from JSON
:type child: Dict
:param result: The result this element belongs to
:type result: overpy.Result
:return: New instance of RelationMembe... | 0.001956 |
def get_cozy_param(param):
'''
Get parameter in Cozy configuration
'''
try:
req = curl_couchdb('/cozy/_design/cozyinstance/_view/all')
rows = req.json()['rows']
if len(rows) == 0:
return None
else:
return rows[0].get('value', {}).get(param, Non... | 0.00565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.