code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
logger.info("rename(new_pid=\"%s\") [lid=%s, pid=%s]", new_pid, self.__lid, self.__pid)
evt = self._client._request_point_rename(self._type, self.__lid, self.__pid, new_pid)
self._client._wait_and_except_if_failed(evt)
self.__pid = new_pid | def rename(self, new_pid) | Rename the Point.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem b... | 5.005616 | 5.138893 | 0.974065 |
logger.info("list(limit=%s, offset=%s) [lid=%s,pid=%s]", limit, offset, self.__lid, self.__pid)
evt = self._client._request_point_value_list(self.__lid, self.__pid, self._type, limit=limit, offset=offset)
self._client._wait_and_except_if_failed(evt)
return evt.payload['values'] | def list(self, limit=50, offset=0) | List `all` the values on this Point.
Returns QAPI list function payload
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLin... | 5.85132 | 5.543556 | 1.055518 |
evt = self._client._request_point_list_detailed(self._type, self.__lid, self.__pid)
self._client._wait_and_except_if_failed(evt)
return evt.payload['subs'] | def list_followers(self) | list followers for this point, i.e. remote follows for feeds and remote attaches for controls.
Returns QAPI subscription list function payload
#!python
{
"<Subscription GUID 1>": "<GUID of follower1>",
"<Subscription GUID 2>": "<GUID of follower2>"
... | 18.740473 | 16.663063 | 1.124672 |
rdf = self.get_meta_rdf(fmt='n3')
return PointMeta(self, rdf, self._client.default_lang, fmt='n3') | def get_meta(self) | Get the metadata object for this Point
Returns a [PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) object - OR -
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkEx... | 14.794258 | 12.813622 | 1.154573 |
evt = self._client._request_point_meta_get(self._type, self.__lid, self.__pid, fmt=fmt)
self._client._wait_and_except_if_failed(evt)
return evt.payload['meta'] | def get_meta_rdf(self, fmt='n3') | Get the metadata for this Point in rdf fmt
Advanced users who want to manipulate the RDF for this Point directly without the
[PointMeta](PointMeta.m.html#IoticAgent.IOT.PointMeta.PointMeta) helper object
Returns the RDF in the format you specify. - OR -
Raises [IOTException](./Excepti... | 13.218056 | 11.74031 | 1.125869 |
evt = self._client._request_point_meta_set(self._type, self.__lid, self.__pid, rdf, fmt=fmt)
self._client._wait_and_except_if_failed(evt) | def set_meta_rdf(self, rdf, fmt='n3') | Set the metadata for this Point in rdf fmt | 12.307703 | 9.532185 | 1.291173 |
if isinstance(tags, str):
tags = [tags]
evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=False)
self._client._wait_and_except_if_failed(evt) | def create_tag(self, tags) | Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters
and the underscore. Tags will be stored lower-cased.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects ... | 8.649409 | 9.108061 | 0.949643 |
if isinstance(tags, str):
tags = [tags]
evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=True)
self._client._wait_and_except_if_failed(evt) | def delete_tag(self, tags) | Delete tags for a Point in the language you specify. Case will be ignored and any tags matching lower-cased
will be deleted.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkExcept... | 8.233328 | 8.541102 | 0.963965 |
evt = self._client._request_point_tag_list(self._type, self.__lid, self.__pid, limit=limit, offset=offset)
self._client._wait_and_except_if_failed(evt)
return evt.payload['tags'] | def list_tag(self, limit=50, offset=0) | List `all` the tags for this Point
Returns list of tags, as below
#!python
[
"mytag1",
"mytag2"
"ein_name",
"nochein_name"
]
- OR...
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Ex... | 9.439961 | 9.315436 | 1.013368 |
evt = self._client._request_point_value_create(self.__lid, self.__pid, self._type, label, vtype, lang,
description, unit)
self._client._wait_and_except_if_failed(evt) | def create_value(self, label, vtype, lang=None, description=None, unit=None) | Create a value on this Point. Values are descriptions in semantic metadata of the individual data items
you are sharing (or expecting to receive, if this Point is a control). This will help others to search for
your feed or control. If a value with the given label (and language) already exists, its fi... | 8.85575 | 8.449574 | 1.048071 |
evt = self._client._request_point_value_delete(self.__lid, self.__pid, self._type, label=label)
self._client._wait_and_except_if_failed(evt) | def delete_value(self, label=None) | Delete the labelled value (or all values) on this Point
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
... | 11.811516 | 10.128179 | 1.166203 |
evt = self.share_async(data, mime=mime, time=time)
self._client._wait_and_except_if_failed(evt) | def share(self, data, mime=None, time=None) | Share some data from this Feed
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communicati... | 8.035767 | 11.340383 | 0.708597 |
evt = self._client._request_point_recent_info(self._type, self.lid, self.pid)
self._client._wait_and_except_if_failed(evt)
return evt.payload['recent'] | def get_recent_info(self) | Retrieves statistics and configuration about recent storage for this Feed.
Returns QAPI recent info function payload
#!python
{
"maxSamples": 0,
"count": 0
}
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTExce... | 12.608125 | 13.814126 | 0.912698 |
evt = self._client._request_point_recent_config(self._type, self.lid, self.pid, max_samples)
self._client._wait_and_except_if_failed(evt)
return evt.payload | def set_recent_config(self, max_samples=0) | Update/configure recent data settings for this Feed. If the container does not support recent storage or it
is not enabled for this owner, this function will have no effect.
`max_samples` (optional) (int) how many shares to store for later retrieval. If not supported by container, this
argument... | 11.053266 | 12.250195 | 0.902293 |
if not (isinstance(text, Sequence) and all(isinstance(phrase, string_types) for phrase in text)):
raise TypeError('text should be sequence of strings')
values = ([self.__values[name] for name in self.__filter.filter_by(types=types, units=units)
if include_unset or... | def filter_by(self, text=(), types=(), units=(), include_unset=False) | Return subset of values which match the given text, types and/or units. For a value to be matched, at least
one item from each specified filter category has to apply to a value. Each of the categories must be specified
as a sequence of strings. If `include_unset` is set, unset values will also be consid... | 3.409666 | 3.327862 | 1.024582 |
return {value.label: value.value for value in self.__values if not value.unset} | def to_dict(self) | Converts the set of values into a dictionary. Unset values are excluded. | 12.720263 | 5.704887 | 2.229713 |
if not isinstance(dictionary, Mapping):
raise TypeError('dictionary should be mapping')
obj = cls(values, value_filter)
values = obj.__values
for name, value in dictionary.items():
if not isinstance(name, string_types):
raise TypeError('Ke... | def _from_dict(cls, values, value_filter, dictionary, allow_unset=True) | Instantiates new PointDataObject, populated from the given dictionary. With allow_unset=False, a ValueError
will be raised if any value has not been set. Used by PointDataObjectHandler | 3.09845 | 3.119334 | 0.993305 |
self.__parent.set_meta_rdf(self._graph.serialize(format=self.__fmt).decode('utf8'), fmt=self.__fmt) | def set(self) | Pushes the RDF metadata description back to the infrastructure. This will be searchable if you have called
[set_public()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.set_public)
at any time
`Example 1` Use of python `with` syntax and XXXXmeta class. `Recommended`
#!python
... | 14.151759 | 10.678547 | 1.325251 |
graph = Graph()
graph.parse(data=self.__parent.get_meta_rdf(fmt=self.__fmt), format=self.__fmt)
self._graph = graph | def update(self) | Gets the latest version of your metadata from the infrastructure and updates your local copy
Returns `True` if successful, `False` otherwise - OR -
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
... | 9.809756 | 14.120459 | 0.694719 |
label = Validation.label_check_convert(label)
lang = Validation.lang_check_convert(lang, default=self._default_lang)
# remove any other labels with this language before adding
self.delete_label(lang)
subj = self._get_uuid_uriref()
self._graph.add((subj, self._lab... | def set_label(self, label, lang=None) | Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
`label` (mandatory) (string) the new text o... | 6.996366 | 7.279426 | 0.961115 |
self._remove_properties_by_language(self._labelPredicate,
Validation.lang_check_convert(lang, default=self._default_lang)) | def delete_label(self, lang=None) | Deletes all the `label` metadata properties on your Thing/Point for this language
Raises `ValueError` containing an error message if the parameters fail validation
`lang` (optional) (string) The two-character ISO 639-1 language code to identify your label.
None means use the default language f... | 21.136988 | 19.365551 | 1.091474 |
description = Validation.description_check_convert(description)
lang = Validation.lang_check_convert(lang, default=self._default_lang)
# remove any other descriptions with this language before adding
self.delete_description(lang)
subj = self._get_uuid_uriref()
se... | def set_description(self, description, lang=None) | Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language,
so any other descriptions in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
`description` (mandatory)... | 8.163471 | 7.941482 | 1.027953 |
self._remove_properties_by_language(self._commentPredicate,
Validation.lang_check_convert(lang, default=self._default_lang)) | def delete_description(self, lang=None) | Deletes all the `label` metadata properties on your Thing/Point for this language
Raises `ValueError` containing an error message if the parameters fail validation
`lang` (optional) (string) The two-character ISO 639-1 language code to use for your label.
None means use the default language fo... | 26.074478 | 24.998165 | 1.043056 |
return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default) | def bool_from(obj, default=False) | Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is
None, 'default' is used. | 5.151393 | 4.148119 | 1.241862 |
if not (isinstance(var_name, string_types) and var_name):
raise TypeError('var_name must be non-empty string')
if not (isinstance(cls, type) or isinstance(cls, string_types)): # pylint: disable=consider-merging-isinstance
raise TypeError('cls not a class or string')
if __PRIVATE_NAME_P... | def private_name_for(var_name, cls) | Returns mangled variable name (if applicable) for the given variable and class instance.
See https://docs.python.org/3/tutorial/classes.html#private-variables | 2.804815 | 2.888584 | 0.971 |
if not isinstance(names, Iterable):
raise TypeError('names must be an interable')
return (private_name_for(item, cls) for item in names) | def private_names_for(cls, names) | Returns iterable of private names using privateNameFor() | 4.526996 | 3.687055 | 1.227808 |
if not isinstance(timeout, (int, float)):
raise TypeError('a float is required')
if blocking:
# blocking indefinite
if timeout == -1:
with self.__condition:
while not self.__lock.acquire(False):
# c... | def acquire(self, blocking=True, timeout=-1) | Acquire a lock, blocking or non-blocking.
Blocks until timeout, if timeout a positive float and blocking=True. A timeout
value of -1 blocks indefinitely, unless blocking=False. | 2.871145 | 2.821705 | 1.017521 |
self.__lock.release()
with self.__condition:
self.__condition.notify() | def release(self) | Release a lock. | 7.130538 | 4.873504 | 1.463123 |
'''
Set launch data from a ToolConfig.
'''
if self.launch_url == None:
self.launch_url = config.launch_url
self.custom_params.update(config.custom_params) | def set_config(self, config) | Set launch data from a ToolConfig. | 7.51781 | 3.767392 | 1.995494 |
'''
Check if required parameters for a tool launch are set.
'''
return self.consumer_key and\
self.consumer_secret and\
self.resource_link_id and\
self.launch_url | def has_required_params(self) | Check if required parameters for a tool launch are set. | 9.35218 | 4.337854 | 2.155946 |
return not self._messages and self._send_time and self._send_time < send_time_before | def _sent_without_response(self, send_time_before) | Used internally to determine whether the request has not received any response from the container and was
send before the given time. Unsent requests are not considered. | 5.856666 | 4.525537 | 1.294137 |
if self.__event.is_set():
if self.exception is not None:
# todo better way to raise errors on behalf of other Threads?
raise self.exception # pylint: disable=raising-bad-type
return True
return False | def is_set(self) | Returns True if the request has finished or False if it is still pending.
Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a
network related problem. | 7.212288 | 7.045609 | 1.023657 |
self.__event.set()
if self._complete_func:
self.__run_completion_func(self._complete_func, self.id_) | def _set(self) | Called internally by Client to indicate this request has finished | 11.252351 | 8.333549 | 1.350247 |
if self._complete_func is not None:
raise ValueError('Completion function already set for %s: %s' % (self.id_, self._complete_func))
if not self.__event.is_set():
self._complete_func = partial(func, self, *args, **kwargs)
else:
self.__run_completion_... | def _run_on_completion(self, func, *args, **kwargs) | Function to call when request has finished, after having been _set(). The first argument passed to func will
be the request itself. Additional parameters are NOT validated. If the request is already finished, the given
function will be run immediately (in same thread). | 3.666279 | 3.477576 | 1.054263 |
if self.__event.wait(timeout):
if self.exception is not None:
# todo better way to raise errors on behalf of other Threads?
raise self.exception # pylint: disable=raising-bad-type
return True
return False | def wait(self, timeout=None) | Wait for the request to finish, optionally timing out. Returns True if the request has finished or False if
it is still pending.
Raises [LinkException](AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if the request failed due to a
network related problem. | 6.228742 | 7.239172 | 0.860422 |
declared_middleware = getattr(settings, 'MIDDLEWARE', None)
if declared_middleware is None:
declared_middleware = settings.MIDDLEWARE_CLASSES # Django 1.8 support
# Filter out all the middleware except the ones we care about for ordering.
matching_middleware = [mw for mw in declared_middl... | def _check_middleware_dependencies(concerned_object, required_middleware) | Check required middleware dependencies exist and in the correct order.
Args:
concerned_object (object): The object for which the required
middleware is being checked. This is used for error messages only.
required_middleware (list of String): An ordered list representing the
... | 4.461129 | 4.007528 | 1.113187 |
'''
Validates an OAuth request using the python-oauth2 library:
https://github.com/simplegeo/python-oauth2
'''
try:
# Set the parameters to be what we were passed earlier
# if we didn't get any passed to us now
if not parameters and hasatt... | def is_valid_request(self, request, parameters={},
fake_method=None, handle_error=True) | Validates an OAuth request using the python-oauth2 library:
https://github.com/simplegeo/python-oauth2 | 4.70477 | 3.782904 | 1.243693 |
'''
Parse Flask request
'''
return (request.method,
request.url,
request.headers,
request.form.copy()) | def parse_request(self, request, parameters=None, fake_method=None) | Parse Flask request | 9.723544 | 6.749926 | 1.440541 |
'''
Parse Django request
'''
return (fake_method or request.method,
request.build_absolute_uri(),
request.META,
(dict(request.POST.iteritems())
if request.method == 'POST'
else parameters)) | def parse_request(self, request, parameters, fake_method=None) | Parse Django request | 6.245095 | 5.185947 | 1.204234 |
'''
Parse WebOb request
'''
return (request.method,
request.url,
request.headers,
request.POST.mixed()) | def parse_request(self, request, parameters=None, fake_method=None) | Parse WebOb request | 11.304902 | 7.464337 | 1.514522 |
'''
Convenience method for creating a new OutcomeResponse from a response
object.
'''
response = OutcomeResponse()
response.post_response = post_response
response.response_code = post_response.status
response.process_xml(content)
return response | def from_post_response(post_response, content) | Convenience method for creating a new OutcomeResponse from a response
object. | 5.70828 | 3.298054 | 1.730802 |
'''
Parse OutcomeResponse data form XML.
'''
try:
root = objectify.fromstring(xml)
# Get message idenifier from header info
self.message_identifier = root.imsx_POXHeader.\
imsx_POXResponseHeaderInfo.\
imsx_messageIdentif... | def process_xml(self, xml) | Parse OutcomeResponse data form XML. | 5.235535 | 4.475771 | 1.16975 |
'''
Generate XML based on the current configuration.
'''
root = etree.Element(
'imsx_POXEnvelopeResponse',
xmlns='http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0')
header = etree.SubElement(root, 'imsx_POXHeader')
header_info = etree.Sub... | def generate_response_xml(self) | Generate XML based on the current configuration. | 1.728805 | 1.668685 | 1.036028 |
def wrapper(*args, **kwargs):
profile = Profile()
profile.enable()
try:
func(*args, **kwargs)
finally:
profile.disable()
try:
thread = current_thread()
profile.dump_stats('profile_%s.%s.%s.log' % (getpid(), thread.name, th... | def profiled_thread(func) | decorator to profile a thread or function. Profiling output will be written to
'agent_profile_<process_id>.<thread_id_>.<thread_name>.log | 3.101367 | 3.105105 | 0.998796 |
if re.match("^[{charset}]*$".format(charset=MediaType.RFC7320_TOKEN_CHARSET), value):
return value
else:
return MediaType._quote(value) | def _minimally_quoted_parameter_value(value) | Per RFC 7321 (https://tools.ietf.org/html/rfc7231#section-3.1.1.1):
Parameters values don't need to be quoted if they are a "token".
Token characters are defined by RFC 7320 (https://tools.ietf.org/html/rfc7230#section-3.2.6).
Otherwise, parameters values can be a "quoted-string".
So we ... | 10.224173 | 6.952857 | 1.470499 |
if not newrelic:
return
newrelic.agent.add_custom_parameter('course_id', six.text_type(course_key))
newrelic.agent.add_custom_parameter('org', six.text_type(course_key.org)) | def set_custom_metrics_for_course_key(course_key) | Set monitoring custom metrics related to a course key.
This is not cached, and only support reporting to New Relic Insights. | 3.326142 | 2.809273 | 1.183987 |
if not newrelic:
return
newrelic.agent.set_transaction_name(name, group, priority) | def set_monitoring_transaction_name(name, group=None, priority=None) | Sets the transaction name for monitoring.
This is not cached, and only support reporting to New Relic. | 6.160859 | 4.260344 | 1.446094 |
if newrelic:
nr_transaction = newrelic.agent.current_transaction()
with newrelic.agent.FunctionTrace(nr_transaction, function_name):
yield
else:
yield | def function_trace(function_name) | Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools. | 4.37245 | 4.896129 | 0.893042 |
try:
return self.channels[channel_id]
except KeyError:
return self.Channel(self, channel_id,
auto_encode_decode=auto_encode_decode) | def channel(self, channel_id=None, auto_encode_decode=True) | Fetch a Channel object identified by the numeric channel_id, or
create that object if it doesn't already exist. See Channel for meaning
of auto_encode_decode. If the channel already exists, the auto_* flag
will not be updated. | 2.928425 | 2.703405 | 1.083236 |
chanmap = self.channels
chanid, method_sig, args, content = self._wait_multiple(
chanmap, None, timeout=timeout,
)
channel = chanmap[chanid]
if (content and
channel.auto_encode_decode and
hasattr(content, 'content_encoding'))... | def drain_events(self, timeout=None) | Wait for an event on a channel. | 4.129 | 3.986443 | 1.03576 |
if self.transport is None:
# already closed
return
args = AMQPWriter()
args.write_short(reply_code)
args.write_shortstr(reply_text)
args.write_short(method_sig[0]) # class_id
args.write_short(method_sig[1]) # method_id
try:
... | def close(self, reply_code=0, reply_text='', method_sig=(0, 0)) | Request a connection close
This method indicates that the sender wants to close the
connection. This may be due to internal conditions (e.g. a
forced shut-down) or due to an error handling a specific
method, i.e. an exception. When a close is due to an
exception, the sender pro... | 3.573128 | 3.65598 | 0.977338 |
if not (isinstance(types, Sequence) and isinstance(units, Sequence)):
raise TypeError('types/units must be a sequence')
empty = frozenset()
if types:
type_names = set()
for type_ in types:
type_names |= self.by_type.get(type_, empty)
... | def filter_by(self, types=(), units=()) | Return list of value labels, filtered by either or both type and unit. An empty
sequence for either argument will match as long as the other argument matches any values. | 2.534185 | 2.409076 | 1.051932 |
if self.__value_templates is None and self.__last_parse_ok:
try:
self.__refresh()
except RefreshException:
# Point has no (useable) values - don't try to refetch again
self.__last_parse_ok = False
... | def get_template(self, data=None): # noqa (complexity)
with self.__lock | Get new template which represents the values of this point in a
[PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject). If data is set (to a dictionary), use
this to populate the created template. | 4.85978 | 4.177513 | 1.163319 |
raw_values = self.__get_values()
if not raw_values:
raise RefreshException('Point has no values')
# individual templates
templates = []
# lookup tables by type and unit of value
by_type = {}
by_unit = {}
for raw_value in raw_values:
... | def __refresh(self) | Update local knowledge of values (to be used to create new skeletal instances). MUST be called within
lock. | 3.469198 | 3.318389 | 1.045446 |
values = []
if self.__remote:
description = self.__client.describe(self.__point)
if description is not None:
if description['type'] != 'Point':
raise IOTUnknown('%s is not a Point' % self.__point)
values = description[... | def __get_values(self) | Retrieve value information either via describe or point value listing. MUST be called within lock. | 6.084372 | 5.119683 | 1.188428 |
if filesize <= AWS_MAX_MULTIPART_COUNT * AWS_MIN_CHUNK_SIZE:
return AWS_MIN_CHUNK_SIZE
else:
div = filesize // AWS_MAX_MULTIPART_COUNT
if div * AWS_MAX_MULTIPART_COUNT < filesize:
div += 1
return ((div + MiB - 1) // MiB) * MiB | def get_s3_multipart_chunk_size(filesize) | Returns the chunk size of the S3 multipart object, given a file's size. | 2.867157 | 2.736894 | 1.047595 |
'''
Set the provided parameter in a set of extension parameters.
'''
if not self.extensions[ext_key]:
self.extensions[ext_key] = defaultdict(lambda: None)
self.extensions[ext_key][param_key] = val | def set_ext_param(self, ext_key, param_key, val) | Set the provided parameter in a set of extension parameters. | 3.949324 | 2.910286 | 1.357022 |
'''
Get specific param in set of provided extension parameters.
'''
return self.extensions[ext_key][param_key] if self.extensions[ext_key]\
else None | def get_ext_param(self, ext_key, param_key) | Get specific param in set of provided extension parameters. | 7.947646 | 4.639119 | 1.71318 |
'''
Parse tool configuration data out of the Common Cartridge LTI link XML.
'''
root = objectify.fromstring(xml, parser = etree.XMLParser())
# Parse all children of the root node
for child in root.getchildren():
if 'title' in child.tag:
self.ti... | def process_xml(self, xml) | Parse tool configuration data out of the Common Cartridge LTI link XML. | 2.133453 | 1.908563 | 1.117832 |
'''
Generate XML from the current settings.
'''
if not self.launch_url or not self.secure_launch_url:
raise InvalidLTIConfigError('Invalid LTI configuration')
root = etree.Element('cartridge_basiclti_link', attrib = {
'{%s}%s' %(NSMAP['xsi'], 'sc... | def to_xml(self, opts = defaultdict(lambda: None)) | Generate XML from the current settings. | 2.029106 | 1.997771 | 1.015685 |
d = self.declaration
if d.orientation == 'vertical':
self.widget = ScrollView(self.get_context(), None, d.style)
else:
self.widget = HorizontalScrollView(self.get_context(),
None, d.style) | def create_widget(self) | Create the underlying widget. | 3.940525 | 3.353925 | 1.1749 |
d = self.declaration
self.widget = CalendarView(self.get_context(), None,
d.style or "@attr/calendarViewStyle") | def create_widget(self) | Create the underlying widget. | 14.203938 | 11.128086 | 1.276404 |
super(AndroidCalendarView, self).init_widget()
#: Setup listener
w = self.widget
w.setOnDateChangeListener(w.getId())
w.onSelectedDayChange.connect(self.on_selected_day_change) | def init_widget(self) | Initialize the underlying widget. | 7.576652 | 6.491967 | 1.167081 |
super(AndroidFragment, self).init_widget()
f = self.fragment
f.setFragmentListener(f.getId())
f.onCreateView.connect(self.on_create_view)
f.onDestroyView.connect(self.on_destroy_view) | def init_widget(self) | Initialize the underlying widget. | 4.578075 | 4.028743 | 1.136353 |
parent = self.parent()
if parent is not None:
self.adapter = parent.adapter
self.adapter.addFragment(self.fragment) | def init_layout(self) | Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called. | 7.264454 | 7.599512 | 0.955911 |
#: Destroy fragment
fragment = self.fragment
if fragment:
#: Stop listening
fragment.setFragmentListener(None)
#: Cleanup from fragment
if self.adapter is not None:
self.adapter.removeFragment(self.fragment)
d... | def destroy(self) | Custom destructor that deletes the fragment and removes
itself from the adapter it was added to. | 7.652543 | 6.541696 | 1.16981 |
d = self.declaration
changed = not d.condition
if changed:
d.condition = True
view = self.get_view()
if changed:
self.ready.set_result(True)
return view | def on_create_view(self) | Trigger the click | 8.591599 | 8.660697 | 0.992022 |
d = self.declaration
if d.cached and self.widget:
return self.widget
if d.defer_loading:
self.widget = FrameLayout(self.get_context())
app = self.get_context()
app.deferred_call(
lambda: self.widget.addView(self.load_vi... | def get_view(self) | Get the page to display. If a view has already been created and
is cached, use that otherwise initialize the view and proxy. If defer
loading is used, wrap the view in a FrameLayout and defer add view
until later. | 5.871609 | 3.646683 | 1.610124 |
super(AndroidPagerFragment, self).init_widget()
d = self.declaration
if d.title:
self.set_title(d.title)
if d.icon:
self.set_icon(d.icon) | def init_widget(self) | Initialize the underlying widget. | 4.213401 | 3.633674 | 1.159543 |
func = _make_coroutine_wrapper(func, replace_callback=False)
@functools.wraps(func)
def wrapper(*args, **kwargs):
future = func(*args, **kwargs)
def final_callback(future):
if future.result() is not None:
raise ReturnValueIgnoredError(
"... | def engine(func) | Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is similar to `coroutine`, except it does not
return a `.Fu... | 6.018915 | 6.463134 | 0.931269 |
# On Python 3.5, set the coroutine flag on our generator, to allow it
# to be used with 'await'.
wrapped = func
if hasattr(types, 'coroutine'):
func = types.coroutine(func)
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
future = TracebackFuture()
if replac... | def _make_coroutine_wrapper(func, replace_callback) | The inner workings of ``@gen.coroutine`` and ``@gen.engine``.
The two decorators differ in their treatment of the ``callback``
argument, so we cannot simply implement ``@engine`` in terms of
``@coroutine``. | 5.428675 | 5.531119 | 0.981478 |
future = Future()
def handle_exception(typ, value, tb):
if future.done():
return False
future.set_exc_info((typ, value, tb))
return True
def set_result(result):
if future.done():
return
future.set_result(result)
with stack_context.Ex... | def Task(func, *args, **kwargs) | Adapts a callback-based asynchronous function for use in coroutines.
Takes a function (and optional additional arguments) and runs it with
those arguments plus a ``callback`` keyword argument. The argument passed
to the callback is returned as the result of the yield expression.
.. versionchanged:: 4... | 3.233616 | 4.031488 | 0.80209 |
if isinstance(children, dict):
return any(isinstance(i, YieldPoint) for i in children.values())
if isinstance(children, list):
return any(isinstance(i, YieldPoint) for i in children)
return False | def _contains_yieldpoint(children) | Returns True if ``children`` contains any YieldPoints.
``children`` may be a dict or a list, as used by `MultiYieldPoint`
and `multi_future`. | 2.159448 | 1.968907 | 1.096775 |
if _contains_yieldpoint(children):
return MultiYieldPoint(children, quiet_exceptions=quiet_exceptions)
else:
return multi_future(children, quiet_exceptions=quiet_exceptions) | def multi(children, quiet_exceptions=()) | Runs multiple asynchronous operations in parallel.
``children`` may either be a list or a dict whose values are
yieldable objects. ``multi()`` returns a new yieldable
object that resolves to a parallel structure containing their
results. If ``children`` is a list, the result is a list of
results in... | 5.562129 | 4.737733 | 1.174006 |
if isinstance(children, dict):
keys = list(children.keys())
children = children.values()
else:
keys = None
children = list(map(convert_yielded, children))
assert all(is_future(i) for i in children)
unfinished_children = set(children)
future = Future()
if not chi... | def multi_future(children, quiet_exceptions=()) | Wait for multiple asynchronous futures in parallel.
This function is similar to `multi`, but does not support
`YieldPoints <YieldPoint>`.
.. versionadded:: 4.0
.. versionchanged:: 4.2
If multiple ``Futures`` fail, any exceptions after the first (which is
raised) will be logged. Added th... | 2.450343 | 2.404547 | 1.019045 |
if is_future(x):
return x
else:
fut = Future()
fut.set_result(x)
return fut | def maybe_future(x) | Converts ``x`` into a `.Future`.
If ``x`` is already a `.Future`, it is simply returned; otherwise
it is wrapped in a new `.Future`. This is suitable for use as
``result = yield gen.maybe_future(f())`` when you don't know whether
``f()`` returns a `.Future` or not.
.. deprecated:: 4.3
This... | 2.571702 | 3.237105 | 0.794445 |
# TODO: allow YieldPoints in addition to other yieldables?
# Tricky to do with stack_context semantics.
#
# It's tempting to optimize this by cancelling the input future on timeout
# instead of creating a new one, but A) we can't know if we are the only
# one waiting on the input future, so... | def with_timeout(timeout, future, quiet_exceptions=()) | Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
complete before ``timeout``, which may be specified in any form
allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
an absolute time relative to `.IOLoop.time`)
... | 5.61456 | 5.406813 | 1.038423 |
f = Future()
IOLoop.current().call_later(duration, lambda: f.set_result(None))
return f | def sleep(duration) | Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
Note that calling this function on its own does n... | 3.423351 | 4.721095 | 0.725118 |
def wrapper(*args, **kwargs):
if kwargs or len(args) > 1:
callback(Arguments(args, kwargs))
elif args:
callback(args[0])
else:
callback(None)
return wrapper | def _argument_adapter(callback) | Returns a function that when invoked runs ``callback`` with one arg.
If the function returned by this function is called with exactly
one argument, that argument is passed to ``callback``. Otherwise
the args tuple and kwargs dict are wrapped in an `Arguments` object. | 3.24033 | 2.981478 | 1.08682 |
# Lists and dicts containing YieldPoints were handled earlier.
if yielded is None:
return moment
elif isinstance(yielded, (list, dict)):
return multi(yielded)
elif is_future(yielded):
return yielded
elif isawaitable(yielded):
return _wrap_awaitable(yielded)
e... | def convert_yielded(yielded) | Convert a yielded object into a `.Future`.
The default implementation accepts lists, dictionaries, and Futures.
If the `~functools.singledispatch` library is available, this function
may be extended to support additional types. For example::
@convert_yielded.register(asyncio.Future)
def _... | 6.292933 | 6.790099 | 0.926781 |
if self._finished or self._unfinished:
return False
# Clear the 'current' values when iteration is done.
self.current_index = self.current_future = None
return True | def done(self) | Returns True if this iterator has no more results. | 11.551064 | 9.100748 | 1.269243 |
self._running_future = TracebackFuture()
if self._finished:
self._return_result(self._finished.popleft())
return self._running_future | def next(self) | Returns a `.Future` that will yield the next available result.
Note that this `.Future` will not be the same object as any of
the inputs. | 10.997026 | 9.501191 | 1.157437 |
chain_future(done, self._running_future)
self.current_future = done
self.current_index = self._unfinished.pop(done) | def _return_result(self, done) | Called set the returned future's state that of the future
we yielded, and set the current future for the iterator. | 15.214523 | 9.949936 | 1.529108 |
if self.pending_callbacks is None:
# Lazily initialize the old-style YieldPoint data structures.
self.pending_callbacks = set()
self.results = {}
if key in self.pending_callbacks:
raise KeyReuseError("key %r is already pending" % (key,))
s... | def register_callback(self, key) | Adds ``key`` to the list of callbacks. | 5.180192 | 5.020834 | 1.031739 |
if self.pending_callbacks is None or key not in self.pending_callbacks:
raise UnknownKeyError("key %r is not pending" % (key,))
return key in self.results | def is_ready(self, key) | Returns true if a result is available for ``key``. | 5.595486 | 4.696699 | 1.191366 |
self.results[key] = result
if self.yield_point is not None and self.yield_point.is_ready():
try:
self.future.set_result(self.yield_point.get_result())
except:
self.future.set_exc_info(sys.exc_info())
self.yield_point = None
... | def set_result(self, key, result) | Sets the result for ``key`` and attempts to resume the generator. | 2.981611 | 2.757371 | 1.081324 |
self.pending_callbacks.remove(key)
return self.results.pop(key) | def pop_result(self, key) | Returns the result for ``key`` and unregisters it. | 6.14448 | 5.335835 | 1.15155 |
if self.running or self.finished:
return
try:
self.running = True
while True:
future = self.future
if not future.done():
return
self.future = None
try:
ori... | def run(self) | Starts or resumes the generator, running until it reaches a
yield point that is not ready. | 4.167887 | 4.049107 | 1.029335 |
d = self.declaration
self.widget = RadioButton(self.get_context(), None,
d.style or '@attr/radioButtonStyle') | def create_widget(self) | Create the underlying widget. | 15.886585 | 11.638226 | 1.365035 |
self.connection.write_message(data, binary) | def write_message(self, data, binary=False) | Write a message to the client | 6.264584 | 6.810112 | 0.919894 |
if root is None:
tmp = os.environ.get('TMP')
root = sys.path[1 if tmp and tmp in sys.path else 0]
items = []
for filename in os.listdir(root):
# for subdirname in dirnames:
# path = os.path.join(dirname, subdirname)
# ... | def render_files(self, root=None) | Render the file path as accordions | 3.405246 | 3.333704 | 1.02146 |
tmp_dir = os.environ.get('TMP','')
view_code = os.path.join(tmp_dir,'view.enaml')
if os.path.exists(view_code):
try:
with open(view_code) as f:
return f.read()
except:
pass
return DEFAULT_CODE | def render_code(self) | Try to load the previous code (if we had a crash or something)
I should allow saving. | 3.480903 | 3.406855 | 1.021735 |
items = [
.format(name=m.name,
type=self.render_component_types(declaration, m))
for m in self.get_component_members(declaration)]
info = []
parent = declaration.__mro__[1]
#: Superclass
info.append("<tr><td>ext... | def render_component(self, declaration) | Render a row of all the attributes | 3.975565 | 3.991861 | 0.995918 |
print("Starting debug client cwd: {}".format(os.getcwd()))
print("Sys path: {}".format(sys.path))
#: Initialize the hotswapper
self.hotswap = Hotswapper(debug=False)
if self.mode == 'server':
self.server.start(self)
else:
self.client.sta... | def start(self) | Start the dev session. Attempt to use tornado first, then try
twisted | 6.109415 | 6.175441 | 0.989308 |
host = 'localhost' if self.mode == 'remote' else self.host
return 'ws://{}:{}/dev'.format(host, self.port) | def _default_url(self) | Websocket URL to connect to and listen for reload requests | 5.80664 | 4.776743 | 1.215607 |
self.client.write_message(data, binary=binary) | def write_message(self, data, binary=False) | Write a message to the active client | 5.023196 | 4.84621 | 1.036521 |
msg = json.loads(data)
print("Dev server message: {}".format(msg))
handler_name = 'do_{}'.format(msg['type'])
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
result = handler(msg)
return {'ok': True, 'result': result}
... | def handle_message(self, data) | When we get a message | 2.927924 | 2.942255 | 0.995129 |
#: TODO: This should use the autorelaoder
app = self.app
#: Show loading screen
try:
self.app.widget.showLoading("Reloading... Please wait.", now=True)
#self.app.widget.restartPython(now=True)
#sys.exit(0)
except:
#: TODO:... | def do_reload(self, msg) | Called when the dev server wants to reload the view. | 6.382499 | 6.205283 | 1.028559 |
#: Show hotswap tooltip
try:
self.app.widget.showTooltip("Hot swapping...", now=True)
except:
pass
self.save_changed_files(msg)
hotswap = self.hotswap
app = self.app
try:
print("Attempting hotswap....")
wit... | def do_hotswap(self, msg) | Attempt to hotswap the code | 9.328998 | 9.071446 | 1.028391 |
if change['type'] == 'event':
name = 'do_'+change['name']
if hasattr(self.proxy, name):
handler = getattr(self.proxy, name)
handler()
else:
super(WebView, self)._update_proxy(change) | def _update_proxy(self, change) | An observer which sends the state change to the proxy. | 3.717755 | 3.426122 | 1.085121 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.