_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q52800 | coerceBigInt | train | def coerceBigInt(x):
"""
Retrieves a BigInt from @x or returns None if @x is not a type that can be
converted.
"""
# BigInt's are easy.
if isinstance(x, BigInt):
return x
# Convert ints and longs using the constructor
elif isinstance(x, (long, int)):
return BigInt(x)
... | python | {
"resource": ""
} |
q52801 | inverse | train | def inverse(x, p, errorOnFail=False):
"""
Find the inverse of BigInt @x in a field of (prime) order @p.
"""
# Check types
assertType(x, BigInt)
# There are a number of ways in RELIC to compute this inverse, but
# for simplicity, we'll use the extended GCD algorithm because it
# involve... | python | {
"resource": ""
} |
q52802 | randomZ | train | def randomZ(maximum=None, bits=256):
"""
Retrieve a random BigInt.
@maximum: If specified, the value will be no larger than this modulus.
@bits: If no maximum is specified, the value will have @bits.
"""
result = BigInt()
# Select a random number smaller than the maximum.
if maximum:
... | python | {
"resource": ""
} |
q52803 | emit_event | train | def emit_event(project_slug, action_slug):
"""Publish message to action.
Rio will trigger all registered webhooks related to this action and
trace running process.
"""
if request.headers.get('Content-Type') == 'application/json':
payload = request.get_json()
elif request.method == 'POS... | python | {
"resource": ""
} |
q52804 | strict_resolve | train | def strict_resolve(self, context, ignore_failures=False):
"""
Resolves a ``FilterExpression`` within the context of the template.
This patched method acts as a proxy to the original, but forces
``ignore_failures`` to False so that an exception is always raised when a
variable is accessed out of sco... | python | {
"resource": ""
} |
q52805 | debug_variable_node_render | train | def debug_variable_node_render(self, context):
"""
Like DebugVariableNode.render, but doesn't catch UnicodeDecodeError.
"""
try:
output = self.filter_expression.resolve(context)
output = template_localtime(output, use_tz=context.use_tz)
output = localize(output, use_l10n=context.... | python | {
"resource": ""
} |
q52806 | variable_node_render | train | def variable_node_render(self, context):
"""
Like VariableNode.render, but doesn't catch UnicodeDecodeError.
"""
output = self.filter_expression.resolve(context)
return render_value_in_context(output, context) | python | {
"resource": ""
} |
q52807 | _disallow_catching_UnicodeDecodeError | train | def _disallow_catching_UnicodeDecodeError(f):
"""
Patches a template modules to prevent catching UnicodeDecodeError.
Note that this has the effect of also making Template raise a
UnicodeDecodeError instead of a TemplateEncodingError if the template
string is not UTF-8 or unicode.
"""
patch_... | python | {
"resource": ""
} |
q52808 | fail_on_template_errors | train | def fail_on_template_errors(f, *args, **kwargs):
"""
Decorator that causes templates to fail on template errors.
"""
decorators = [
_fail_template_string_if_invalid,
_always_strict_resolve,
_disallow_catching_UnicodeDecodeError,
]
if django.VERSION < (1, 8):
decor... | python | {
"resource": ""
} |
q52809 | log_template_errors | train | def log_template_errors(logger, log_level=logging.ERROR):
"""
Decorator to log template errors to the specified logger.
@log_template_errors(logging.getLogger('mylogger'), logging.INFO)
def my_view(*args):
pass
Will log template errors at INFO. The default log level is ERROR.
"""
... | python | {
"resource": ""
} |
q52810 | ApiDocWriter._parse_module_with_import | train | def _parse_module_with_import(self, uri):
"""Look for functions and classes in an importable module.
Parameters
----------
uri : str
The name of the module to be parsed. This module needs to be
importable.
Returns
-------
functions : list... | python | {
"resource": ""
} |
q52811 | ApiDocWriter.generate_api_doc | train | def generate_api_doc(self, uri):
'''Make autodoc documentation template string for a module
Parameters
----------
uri : string
python location of module - e.g 'sphinx.builder'
Returns
-------
head : string
Module name, table of contents.
... | python | {
"resource": ""
} |
q52812 | tmp | train | def tmp(p_queue, host=None):
if host is not None:
return _path(_c.FSQ_TMP, root=_path(host, root=hosts(p_queue)))
'''Construct a path to the tmp dir for a queue'''
return _path(p_queue, _c.FSQ_TMP) | python | {
"resource": ""
} |
q52813 | queue | train | def queue(p_queue, host=None):
'''Construct a path to the queue dir for a queue'''
if host is not None:
return _path(_c.FSQ_QUEUE, root=_path(host, root=hosts(p_queue)))
return _path(p_queue, _c.FSQ_QUEUE) | python | {
"resource": ""
} |
q52814 | fail | train | def fail(p_queue, host=None):
if host is not None:
return _path(_c.FSQ_FAIL, root=_path(host, root=hosts(p_queue)))
'''Construct a path to the fail dir for a queue'''
return _path(p_queue, _c.FSQ_FAIL) | python | {
"resource": ""
} |
q52815 | done | train | def done(p_queue, host=None):
if host is not None:
return _path(_c.FSQ_DONE, root=_path(host, root=hosts(p_queue)))
'''Construct a path to the done dir for a queue'''
return _path(p_queue, _c.FSQ_DONE) | python | {
"resource": ""
} |
q52816 | down | train | def down(p_queue, host=None):
if host is not None:
return _path(_c.FSQ_DOWN, root=_path(host, root=hosts(p_queue)))
'''Construct a path to the down file for a queue'''
return _path(p_queue, _c.FSQ_DOWN) | python | {
"resource": ""
} |
q52817 | item | train | def item(p_queue, queue_id, host=None):
if host is not None:
return os.path.join(_path(host, _c.FSQ_QUEUE, root=hosts(p_queue)),
valid_name(queue_id))
'''Construct a path to a queued item'''
return os.path.join(_path(p_queue, _c.FSQ_QUEUE), valid_name(queue_id)) | python | {
"resource": ""
} |
q52818 | StorageBlobContext.upload | train | def upload(self, storagemodel:object, modeldefinition = None):
""" insert blob message into storage """
if (storagemodel.content is None) or (storagemodel.properties.content_settings.content_type is None):
# No content to upload
raise AzureStorageWrapException(storagemodel, "Sto... | python | {
"resource": ""
} |
q52819 | StorageBlobContext.download | train | def download(self, storagemodel:object, modeldefinition = None):
""" load blob from storage into StorageBlobModelInstance """
if (storagemodel.name is None):
# No content to download
raise AzureStorageWrapException(storagemodel, "StorageBlobModel does not contain content nor con... | python | {
"resource": ""
} |
q52820 | StorageBlobContext.list | train | def list(self, storagemodel:object, modeldefinition = None, where=None) ->list:
""" list blob messages in container """
try:
blobnames = []
if where is None:
generator = modeldefinition['blobservice'].list_blobs(modeldefinition['container'])
else:
... | python | {
"resource": ""
} |
q52821 | naa_correct | train | def naa_correct(G):
"""
This function resets the fits and corrects shifts in the spectra.
It uses uses the NAA peak at 2.0ppm as a guide to replaces the existing
f_ppm values!
"""
G.reset_fits()
# calculate diff
diff = np.mean(G.diff_spectra, 0)
# find index of NAA peak in diff sp... | python | {
"resource": ""
} |
q52822 | baseline_correct | train | def baseline_correct(G):
"""
This function zeroes the baseline from 2.5ppm upwards
"""
# define ppm ranges that are known to be at baseline, get indices
baseidx =[]
baseidx.extend(range(np.min(np.where(G.f_ppm<5.0)),np.max(np.where(G.f_ppm>4.0))+1))
baseidx.extend(range(np.min(np.where... | python | {
"resource": ""
} |
q52823 | StorageTableModel.entity | train | def entity(self) -> dict:
""" parse self into dictionary """
image = {}
image['PartitionKey'] = self.getPartitionKey()
image['RowKey'] = self.getRowKey()
for key, value in vars(self).items():
if not key.startswith('_') and key not in ['','PartitionKey','Ro... | python | {
"resource": ""
} |
q52824 | StorageTableContext.getmodeldefinition | train | def getmodeldefinition(self, storageobject, required=False):
""" find modeldefinition for StorageTableModel or StorageTableQuery """
if isinstance(storageobject, StorageTableModel):
definitionlist = [definition for definition in self._modeldefinitions if definition['modelname'] == storageob... | python | {
"resource": ""
} |
q52825 | StorageTableContext.get | train | def get(self, storagemodel) -> StorageTableModel:
""" load entity data from storage to vars in self """
modeldefinition = self.getmodeldefinition(storagemodel, True)
try:
pk = storagemodel.getPartitionKey()
rk = storagemodel.getRowKey()
entity = modeldefin... | python | {
"resource": ""
} |
q52826 | StorageTableContext.insert | train | def insert(self, storagemodel) -> StorageTableModel:
""" insert model into storage """
modeldefinition = self.getmodeldefinition(storagemodel, True)
try:
modeldefinition['tableservice'].insert_or_replace_entity(modeldefinition['tablename'], storagemodel.entity())
storag... | python | {
"resource": ""
} |
q52827 | StorageTableContext.merge | train | def merge(self, storagemodel) -> StorageTableModel:
""" try to merge entry """
modeldefinition = self.getmodeldefinition(storagemodel, True)
try:
pk = storagemodel.getPartitionKey()
rk = storagemodel.getRowKey()
entity = modeldefinition['tableservice']... | python | {
"resource": ""
} |
q52828 | StorageTableContext.delete | train | def delete(self,storagemodel):
""" delete existing Entity """
modeldefinition = self.getmodeldefinition(storagemodel, True)
pk = storagemodel.getPartitionKey()
rk = storagemodel.getRowKey()
try:
modeldefinition['tableservice'].delete_entity(modeldefinit... | python | {
"resource": ""
} |
q52829 | load | train | def load(*, name="dummy", options={}, dry_run=False, **kwargs):
"""
Load a backup driver
:param name(str, optional): name of the backup driver to load
:param options(dict, optional): A dictionary passed to the driver
:param dry_run(bool, optional): Whether to activate dry run mode
:param \*\*kw... | python | {
"resource": ""
} |
q52830 | backup_file | train | def backup_file(*, file, host):
"""
Perform backup action on set driver
:param file: Name of the file to be used by the driver
:param host: Corresponding host name associated with file
"""
if _driver:
log.msg_debug("[{driver}] Backing up file '{file}'"
.format(driv... | python | {
"resource": ""
} |
q52831 | dispose | train | def dispose():
"""
Perform cleanup on set driver
"""
if _driver:
log.msg_debug("[{driver}] dispose".format(driver=_driver.get_name()))
_driver.dispose() | python | {
"resource": ""
} |
q52832 | parametrized_class | train | def parametrized_class(decorator):
'''Decorator used to make simple class decorator with arguments.
Doesn't really do anything, just here to have a central
implementation of the simple class decorator.'''
def decorator_builder(*args, **kwargs):
def meta_decorator(cls):
return decor... | python | {
"resource": ""
} |
q52833 | get_creation_date_tags | train | def get_creation_date_tags(url, domain, as_dicts=False):
"""
Put together all data sources in this module and return it's output.
Args:
url (str): URL of the web. With relative paths and so on.
domain (str): Just the domain of the web.
as_dicts (bool, default False): Convert output ... | python | {
"resource": ""
} |
q52834 | render_category | train | def render_category(slug):
"""Template tag to render a category with all it's entries."""
try:
category = EntryCategory.objects.get(slug=slug)
except EntryCategory.DoesNotExist:
pass
else:
return {'category': category}
return {} | python | {
"resource": ""
} |
q52835 | get_Name | train | def get_Name(name, short=False):
"""
Return the distinguished name of an X509 Certificate
:param name: Name object to return the DN from
:param short: Use short form (Default: False)
:type name: :class:`cryptography.x509.Name`
:type short: Boolean
:rtype: str
"... | python | {
"resource": ""
} |
q52836 | APK.get_all_dex | train | def get_all_dex(self):
"""
Return the raw data of all classes dex files
:rtype: a generator
"""
try:
yield self.get_file("classes.dex")
# Multidex support
basename = "classes%d.dex"
for i in range(2, sys.maxsize):
... | python | {
"resource": ""
} |
q52837 | APK.get_elements | train | def get_elements(self, tag_name, attribute):
"""
Return elements in xml files which match with the tag name and the specific attribute
:param tag_name: a string which specify the tag name
:param attribute: a string which specify the attribute
"""
l = []
... | python | {
"resource": ""
} |
q52838 | APK.get_element | train | def get_element(self, tag_name, attribute, **attribute_filter):
"""
Return element in xml files which match with the tag name and the specific attribute
:param tag_name: specify the tag name
:type tag_name: string
:param attribute: specify the attribute
... | python | {
"resource": ""
} |
q52839 | APK.get_certificate | train | def get_certificate(self, filename):
"""
Return a certificate object by giving the name in the apk file
"""
pkcs7message = self.get_file(filename)
message, _ = decode(pkcs7message)
cert = encode(message[1][3])
# Remove the first identifier·
# byte 0 =... | python | {
"resource": ""
} |
q52840 | APK.get_signature_names | train | def get_signature_names(self):
"""
Return a list of the signature file names.
"""
signature_expr = re.compile("^(META-INF/)(.*)(\.RSA|\.EC|\.DSA)$")
signatures = []
for i in self.get_files():
if signature_expr.search(i):
signatures.append... | python | {
"resource": ""
} |
q52841 | extract_view | train | def extract_view(view, decorators=None):
"""
Extract a view object out of any wrapping decorators.
"""
# http://stackoverflow.com/questions/9222129/python-inspect-getmembers-does-not-return-the-actual-function-when-used-with-dec
if decorators is None:
decorators = []
if getattr(view, 'fu... | python | {
"resource": ""
} |
q52842 | get_decorators | train | def get_decorators(func):
"""
Return a list of decorator names for this function.
"""
decorators = []
# Parse the source code of the function with ast to find the names of
# all of its decorators.
tree = ast.parse(inspect.getsource(func))
for node in ast.iter_child_nodes(tree):
f... | python | {
"resource": ""
} |
q52843 | Replay.snapshot_registry | train | def snapshot_registry(self):
'''
Give the dictionary of recorders detached from the existing instances.
It is safe to store those references for future use. Used by feattool.
'''
unserializer = banana.Unserializer(externalizer=self)
serializer = banana.Serializer(external... | python | {
"resource": ""
} |
q52844 | get_driver | train | def get_driver(secret_key=config.DEFAULT_SECRET_KEY, userid=config.DEFAULT_USERID,
provider=config.DEFAULT_PROVIDER):
"""A driver represents successful authentication. They become
stale, so obtain them as late as possible, and don't cache them."""
if hasattr(config, 'get_driver'):
... | python | {
"resource": ""
} |
q52845 | substitute | train | def substitute(script, submap):
"""Check for presence of template indicator and if found, perform
variable substition on script based on template type, returning
script."""
match = config.TEMPLATE_RE.search(script)
if match:
template_type = match.groupdict()['type']
try:
... | python | {
"resource": ""
} |
q52846 | script_deployment | train | def script_deployment(path, script, submap=None):
"""Return a ScriptDeployment from script with possible template
substitutions."""
if submap is None:
submap = {}
script = substitute(script, submap)
return libcloud.compute.deployment.ScriptDeployment(script, path) | python | {
"resource": ""
} |
q52847 | merge | train | def merge(items, amap, load=False):
"""Merge list of tuples into dict amap, and optionally load source as value"""
for target, source in items:
if amap.get(target):
logger.warn('overwriting {0}'.format(target))
if load:
amap[target] = open(source).read()
else:
... | python | {
"resource": ""
} |
q52848 | merge_keyvals_into_map | train | def merge_keyvals_into_map(keyvals, amap):
"""Merge list of 'key=val' strings into dict amap, warning of duplicate keys"""
for kv in keyvals:
k,v = kv.split('=')
if k in amap:
logger.warn('overwriting {0} with {1}'.format(k, v))
amap[k] = v | python | {
"resource": ""
} |
q52849 | size_from_name | train | def size_from_name(size, sizes):
"""Return a size from a list of sizes."""
by_name = [s for s in sizes if s.name == size]
if len(by_name) > 1:
raise Exception('more than one image named %s exists' % size)
return by_name[0] | python | {
"resource": ""
} |
q52850 | image_from_name | train | def image_from_name(name, images):
"""Return an image from a list of images. If the name is an exact
match, return the last exactly matching image. Otherwise, sort
images by 'natural' order, using decorate-sort-undecorate, and
return the largest.
see:
http://code.activestate.com/recipes/2852... | python | {
"resource": ""
} |
q52851 | destroy_by_name | train | def destroy_by_name(name, driver):
"""Destroy all nodes matching specified name"""
matches = [node for node in list_nodes(driver) if node.name == name]
if len(matches) == 0:
logger.warn('no node named %s' % name)
return False
else:
return all([node.destroy() for node in matches... | python | {
"resource": ""
} |
q52852 | NodeProxy.destroy | train | def destroy(self):
"""Insure only destroyable nodes are destroyed"""
node = self.node
if not config.is_node_destroyable(node.name):
logger.error('node %s has non-destroyable prefix' % node.name)
return False
logger.info('destroying node %s' % node)
retur... | python | {
"resource": ""
} |
q52853 | Deployment.deploy | train | def deploy(self, driver, location_id=config.DEFAULT_LOCATION_ID,
size=config.DEFAULT_SIZE):
"""Use driver to deploy node, with optional ability to specify
location id and size id.
First, obtain location object from driver. Next, get the
size. Then, get the image. Final... | python | {
"resource": ""
} |
q52854 | option | train | def option(value, is_default=False, label=None):
"""
Annotates a possible value for IValueOptions,
will be validated at instance creation time.
@param value: a possible value for the IValueOptions being defined.
@type value: Any
@param is_default: if the option should be the default ... | python | {
"resource": ""
} |
q52855 | _eq | train | def _eq(field, value, document):
"""
Returns True if the value of a document field is equal to a given value
"""
try:
return document.get(field, None) == value
except TypeError: # pragma: no cover Python < 3.0
return False | python | {
"resource": ""
} |
q52856 | _gt | train | def _gt(field, value, document):
"""
Returns True if the value of a document field is greater than a given value
"""
try:
return document.get(field, None) > value
except TypeError: # pragma: no cover Python < 3.0
return False | python | {
"resource": ""
} |
q52857 | _lt | train | def _lt(field, value, document):
"""
Returns True if the value of a document field is less than a given value
"""
try:
return document.get(field, None) < value
except TypeError: # pragma: no cover Python < 3.0
return False | python | {
"resource": ""
} |
q52858 | _gte | train | def _gte(field, value, document):
"""
Returns True if the value of a document field is greater than or
equal to a given value
"""
try:
return document.get(field, None) >= value
except TypeError: # pragma: no cover Python < 3.0
return False | python | {
"resource": ""
} |
q52859 | _lte | train | def _lte(field, value, document):
"""
Returns True if the value of a document field is less than or
equal to a given value
"""
try:
return document.get(field, None) <= value
except TypeError: # pragma: no cover Python < 3.0
return False | python | {
"resource": ""
} |
q52860 | _all | train | def _all(field, value, document):
"""
Returns True if the value of document field contains all the values
specified by ``value``. If supplied value is not an iterable, a
MalformedQueryException is raised. If the value of the document field
is not an iterable, False is returned
"""
try:
... | python | {
"resource": ""
} |
q52861 | _exists | train | def _exists(field, value, document):
"""
Ensures a document has a given field or not. ``value`` must be either True or
False, otherwise a MalformedQueryException is raised
"""
if value not in (True, False):
raise MalformedQueryException("'$exists' must be supplied a boolean")
if value:
... | python | {
"resource": ""
} |
q52862 | Connection.connect | train | def connect(self, *args, **kwargs):
"""
Connect to a sqlite database only if no connection exists. Isolation level
for the connection is automatically set to autocommit
"""
self.db = sqlite3.connect(*args, **kwargs)
self.db.isolation_level = None | python | {
"resource": ""
} |
q52863 | Collection.remove | train | def remove(self, document):
"""
Removes a document from this collection. This will raise AssertionError if the
document does not have an _id attribute
"""
assert '_id' in document, 'Document must have an id'
self.db.execute("delete from %s where id = ?" % self.name, (docu... | python | {
"resource": ""
} |
q52864 | Collection._load | train | def _load(self, id, data):
"""
Loads a JSON document taking care to apply the document id
"""
if isinstance(data, bytes): # pragma: no cover Python >= 3.0
data = data.decode('utf-8')
document = json.loads(data)
document['_id'] = id
return document | python | {
"resource": ""
} |
q52865 | Collection.find | train | def find(self, query=None, limit=None):
"""
Returns a list of documents in this collection that match a given query
"""
results = []
query = query or {}
# TODO: When indexes are implemented, we'll need to intelligently hit one of the
# index stores so we don't do... | python | {
"resource": ""
} |
q52866 | Collection._apply_query | train | def _apply_query(self, query, document):
"""
Applies a query to a document. Returns True if the document meets the criteria of
the supplied query. The ``query`` argument generally follows mongodb style syntax
and consists of the following logical checks and operators.
Logical: $... | python | {
"resource": ""
} |
q52867 | Collection.find_and_modify | train | def find_and_modify(self, query=None, update=None):
"""
Finds documents in this collection that match a given query and updates them
"""
update = update or {}
for document in self.find(query=query):
document.update(update)
self.update(document) | python | {
"resource": ""
} |
q52868 | Collection.rename | train | def rename(self, new_name):
"""
Rename this collection
"""
new_collection = Collection(self.db, new_name, create=False)
assert not new_collection.exists()
self.db.execute("alter table %s rename to %s" % (self.name, new_name))
self.name = new_name | python | {
"resource": ""
} |
q52869 | Collection.distinct | train | def distinct(self, key):
"""
Get a set of distinct values for the given key excluding an implicit
None for documents that do not contain the key
"""
return set(d[key] for d in filter(lambda d: key in d, self.find())) | python | {
"resource": ""
} |
q52870 | Channel.request_done | train | def request_done(self, request):
"""Called by the active request when it is done writing"""
if self._requests is None:
# Channel been cleaned up because the connection was lost.
return
assert request == self._requests[0], "Unexpected request done"
del self._reque... | python | {
"resource": ""
} |
q52871 | meta | train | def meta(name, value, scheme=None):
"""
Adds meta information to a class definition.
@param name: name of the meta data class
@type name: str or unicode
@param value: metadata value
@type value: str or unicode
@param scheme: format information about the value
@type scheme: str or unicode... | python | {
"resource": ""
} |
q52872 | main | train | def main():
"""Do some stuff"""
# Parse all command line argument
args = parse_arguments().parse_args()
# Setup logging
configure_logging(args)
logging.debug(args)
# Prompt for a password if necessary
if not args.password:
password = getpass.getpass(prompt='Password ({0}): '.fo... | python | {
"resource": ""
} |
q52873 | configure_logging | train | def configure_logging(args):
"""Logging to console"""
log_format = logging.Formatter('%(levelname)s:%(name)s:line %(lineno)s:%(message)s')
log_level = logging.INFO if args.verbose else logging.WARN
log_level = logging.DEBUG if args.debug else log_level
console = logging.StreamHandler()
console.s... | python | {
"resource": ""
} |
q52874 | get_html_titles | train | def get_html_titles(index_page):
"""
Return list of titles parsed from HTML.
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceString` objects.
"""
dom = dhtmlparser.parseString(index_page)
title_tags = dom.find("ti... | python | {
"resource": ""
} |
q52875 | PowerViewUtil.create_scene | train | async def create_scene(self, scene_name, room_id) -> Scene:
"""Create a scene and returns the scene object.
:raises PvApiError when something is wrong with the hub.
"""
_raw = await self._scenes_entry_point.create_scene(room_id, scene_name)
result = Scene(_raw, self.request)
... | python | {
"resource": ""
} |
q52876 | PowerViewUtil.get_shade | train | async def get_shade(self, shade_id, from_cache=True) -> BaseShade:
"""Get a shade instance based on shade id."""
if not from_cache:
await self.get_shades()
for _shade in self.shades:
if _shade.id == shade_id:
return _shade
raise ResourceNotFoundExc... | python | {
"resource": ""
} |
q52877 | PowerViewUtil.activate_scene | train | async def activate_scene(self, scene_id: int):
"""Activate a scene
:param scene_id: Scene id.
:return:
"""
_scene = await self.get_scene(scene_id)
await _scene.activate() | python | {
"resource": ""
} |
q52878 | PowerViewUtil.delete_scene | train | async def delete_scene(self, scene_id: int):
"""Delete a scene
:param scene_id:
:return:
"""
_scene = await self.get_scene(scene_id, from_cache=False)
return await _scene.delete() | python | {
"resource": ""
} |
q52879 | PowerViewUtil.add_shade_to_scene | train | async def add_shade_to_scene(self, shade_id, scene_id, position=None):
"""Add a shade to a scene."""
if position is None:
_shade = await self.get_shade(shade_id)
position = await _shade.get_current_position()
await (SceneMembers(self.request)).create_scene_member(
... | python | {
"resource": ""
} |
q52880 | View.reset_bars | train | def reset_bars(self):
"""
Set all progress bars to zero and hide them.
"""
self.url_progressbar.reset()
self.url_progressbar.show([0, 0])
self.issn_progressbar.reset()
self.urlbox_error.reset()
self.issnbox_error.reset()
InputController._reset_t... | python | {
"resource": ""
} |
q52881 | View.get_all_properties | train | def get_all_properties(self):
"""
Get dictionary with all properties readable by this class.
"""
properties = {
prop_name: getattr(self, prop_name)
for prop_name in self._property_list
}
return properties | python | {
"resource": ""
} |
q52882 | View.validate | train | def validate(self):
"""
Validate all inputs. Highlight invalid inputs.
"""
properties = (
getattr(self.__class__, prop)
for prop in self._property_list
if hasattr(self.__class__, prop)
)
all_valid = True
for prop in properties:... | python | {
"resource": ""
} |
q52883 | View.reset | train | def reset(self):
"""
Reset all inputs back to default.
"""
self.reset_bars()
self.url_progressbar.reset()
# reset all resetable components
for prop in dir(self):
if prop.startswith("__"):
continue
prop_obj = getattr(self, ... | python | {
"resource": ""
} |
q52884 | require_sender | train | def require_sender(f):
"""A decorator that protect emit view function is triggered by a trusted sender.
Currently, Rio only support Basic Authorization.
"""
@wraps(f)
def decorator(*args, **kwargs):
if not request.authorization:
return jsonify({'message': 'unauthorized'}), 401
... | python | {
"resource": ""
} |
q52885 | ADBB2G.wait_for_net | train | def wait_for_net(self, timeout=None, wait_polling_interval=None):
"""Wait for the device to be assigned an IP address.
:param timeout: Maximum time to wait for an IP address to be defined
:param wait_polling_interval: Interval at which to poll for ip address.
"""
if timeout is N... | python | {
"resource": ""
} |
q52886 | ADBB2G.start | train | def start(self, wait=True, timeout=None, wait_polling_interval=None):
"""Start b2g, waiting for the adb connection to become stable.
:param wait:
:param timeout: Maximum time to wait for restart.
:param wait_polling_interval: Interval at which to poll for device readiness.
"""
... | python | {
"resource": ""
} |
q52887 | ADBB2G.restart | train | def restart(self, wait=True, timeout=None, wait_polling_interval=None):
"""Restart b2g, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for restart.
:param wait_polling_interval: Interval at which to poll for device readiness.
"""
self.stop(... | python | {
"resource": ""
} |
q52888 | ADBB2G.reboot | train | def reboot(self, timeout=None, wait_polling_interval=None):
"""Reboot the device, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for reboot.
:param wait_polling_interval: Interval at which to poll for device readiness.
"""
if timeout is Non... | python | {
"resource": ""
} |
q52889 | ADBB2G.get_profiles | train | def get_profiles(self, profile_base="/data/b2g/mozilla", timeout=None):
"""Return a list of paths to gecko profiles on the device,
:param timeout: Timeout of each adb command run
:param profile_base: Base directory containing the profiles.ini file
"""
rv = {}
if timeou... | python | {
"resource": ""
} |
q52890 | ADBB2G.devices | train | def devices(self, timeout=None):
"""Executes adb devices -l and returns a list of objects describing attached devices.
:param timeout: optional integer specifying the maximum time in
seconds for any spawned adb process to complete before
throwing an ADBTimeoutError. This timeou... | python | {
"resource": ""
} |
q52891 | adjust_bounding_box | train | def adjust_bounding_box(bbox):
"""Adjust the bounding box as specified by user.
Returns the adjusted bounding box.
- bbox: Bounding box computed from the canvas drawings.
It must be a four-tuple of numbers.
"""
for i in range(0, 4):
if i in bounding_box:
bbox[i] = bounding_b... | python | {
"resource": ""
} |
q52892 | ContainerNode.resolve_path | train | def resolve_path(self, address):
'''
Resolve the given address in this tree branch
'''
match = self.find_one(address)
if not match:
return [self]
# Go further up the tree if possible
if isinstance(match, ContainerNode):
return match.resolv... | python | {
"resource": ""
} |
q52893 | ContainerNode.find_one | train | def find_one(self, address):
'''
Find the given address or prefix
'''
# Convert to a network and find all matches
prefix = ip_network(address)
matches = self.find_all(prefix)
if not matches:
# Nothing found
return None
if len(matc... | python | {
"resource": ""
} |
q52894 | ContainerNode.find_exact | train | def find_exact(self, prefix):
'''
Find the exact child with the given prefix
'''
matches = self.find_all(prefix)
if len(matches) == 1:
match = matches.pop()
if match.prefix == prefix:
return match
return None | python | {
"resource": ""
} |
q52895 | ContainerNode.find_all | train | def find_all(self, prefix):
'''
Find everything in the given prefix
'''
prefix = ip_network(prefix)
# Check that we are authoritative for the given prefix
if not self.prefix.overlaps(prefix) \
or self.prefix[0] > prefix[0] \
or self.prefix[-1] < prefix[-1... | python | {
"resource": ""
} |
q52896 | register_suite | train | def register_suite():
"""
Call this method in a module containing a test suite. The stack trace from
which call descriptor hashes are derived will be truncated at this module.
"""
global test_suite
frm = inspect.stack()[1]
test_suite = ".".join(os.path.basename(frm[1]).split('.')[0:-1]) | python | {
"resource": ""
} |
q52897 | recache | train | def recache( methodname=None, filename=None ):
"""
Deletes entries corresponding to methodname in filename. If no arguments are passed it recaches the entire table.
:param str methodname: The name of the method to target. This will delete ALL entries this method appears in the stack trace for.
:param s... | python | {
"resource": ""
} |
q52898 | get_stack | train | def get_stack(method_name):
"""
Returns the stack trace to hash to identify a call descriptor
:param str method_name: The calling method.
:rtype str:
"""
global test_suite
trace_string = method_name + " "
for f in inspect.stack():
module_name = os.path.basename(f[1])
... | python | {
"resource": ""
} |
q52899 | Commands.get_document | train | def get_document(self, doc_id):
'''Download the document given the id.'''
conn = self.agency._database.get_connection()
return conn.get_document(doc_id) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.