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 between you and the infrastructure
`new_pid` (required) (string) the new local identifier of your Point | 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.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure
`limit` (optional) (integer) Return this many value details
`offset` (optional) (integer) Return value details starting at this offset | 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>"
}
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 between you and the infrastructure
`limit` (optional) (integer) Return this many value details
`offset` (optional) (integer) Return value details starting at this offset | 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 [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure | 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](./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 between you and the infrastructure
`fmt` (optional) (string) The format of RDF you want returned.
Valid formats are: "xml", "n3", "turtle" | 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 a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure
tags (mandatory) (list) - the list of tags you want to add to your Point, e.g.
["garden", "soil"] | 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 [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure
`tags` (mandatory) (list) - the list of tags you want to delete from your Point, e.g.
["garden", "soil"] | 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.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 between you and the infrastructure
`limit` (optional) (integer) Return at most this many tags
`offset` (optional) (integer) Return tags starting at this offset | 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 fields are updated
with the provided ones (or unset, if None).
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 between you and the infrastructure
`label` (mandatory) (string) the label for this value e.g. "Temperature". The label must be unique for this
Point. E.g. You can't have two data values called "Volts" but you can have "volts1" and "volts2".
`lang` (optional) (string) The two-character ISO 639-1 language code to use for the description. None means use
the default language for your agent.
See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
`vtype` (mandatory) (xsd:datatype) the datatype of the data you are describing, e.g. dateTime
We recommend you use a Iotic Labs-defined constant from
[Datatypes](../Datatypes.m.html#IoticAgent.Datatypes.Datatypes) such as:
[DECIMAL](../Datatypes.m.html#IoticAgent.Datatypes.DECIMAL)
`description` (optional) (string) The longer descriptive text for this value.
`unit` (optional) (ontology url) The url of the ontological description of the unit of your value
We recommend you use a constant from [Units](../Units.m.html#IoticAgent.Units.Units), such as:
[CELSIUS](../Units.m.html#IoticAgent.Units.Units.CELSIUS)
#!python
# example with no units as time is unit-less
my_feed.create_value("timestamp",
Datatypes.DATETIME,
"en",
"time of reading")
# example with a unit from the Units class
my_feed.create_value("temperature",
Datatypes.DECIMAL,
"en",
"Fish-tank temperature in celsius",
Units.CELSIUS) | 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)
if there is a communications problem between you and the infrastructure
`label` (optional) (string) the label for the value you want to delete. If not specified, all values for this
point will be removed. | 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 communications problem between you and the infrastructure
`data` (mandatory) (as applicable) The data you want to share
`mime` (optional) (string) The mime type of the data you're sharing. There are some
Iotic Labs-defined default values:
`"idx/1"` - Corresponds to "application/ubjson" - the recommended way to send mixed data.
Share a python dictionary as the data and the agent will to the encoding and decoding for you.
#!python
data = {}
data["temperature"] = self._convert_to_celsius(ADC.read(1))
# ...etc...
my_feed.share(data)
`"idx/2"` Corresponds to "text/plain" - the recommended way to send textual data.
Share a utf8 string as data and the agent will pass it on, unchanged.
#!python
my_feed.share(u"string data")
`"text/xml"` or any other valid mime type. To show the recipients that
you're sending something more than just bytes
#!python
my_feed.share("<xml>...</xml>".encode('utf8'), mime="text/xml")
`time` (optional) (datetime) UTC time for this share. If not specified, the container's time will be used. Thus
it makes almost no sense to specify `datetime.utcnow()` here. This parameter can be used to indicate that the
share time does not correspond to the time to which the data applies, e.g. to populate recent storgage with
historical data. | 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.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 between you and the infrastructure | 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 will be ignored. A value of zero disables this feature whilst a negative value requests the maximum
sample store amount.
Returns QAPI recent config function payload
#!python
{
"maxSamples": 0
}
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 between you and the infrastructure | 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 not self.__values[name].unset]
if types or units else self.__values)
if text:
# avoid unexpected search by individual characters if a single string was specified
if isinstance(text, string_types):
text = (ensure_unicode(text),)
text = [phrase.lower() for phrase in text]
new_values = []
for value in values:
label = value.label.lower()
description = value.description.lower() if value.description else ''
if any(phrase in label or (description and phrase in description) for phrase in text):
new_values.append(value)
values = new_values
return values | 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 considered. | 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('Key %s is not a string' % str(name))
setattr(values, name, value)
if obj.missing and not allow_unset:
raise ValueError('%d value(s) are unset' % len(obj.missing))
return obj | 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
# using with calls set() for you so you don't forget
with thing_solar_panels.get_meta() as meta_thing_solar_panels:
meta_thing_solar_panels.set_label("Mark's Solar Panels")
meta_thing_solar_panels.set_description("Solar Array 3.3kW")
meta_thing_solar_panels.set_location(52.1965071,0.6067687)
`Example 2` Explicit use of set
#!python
meta_thing_solar_panels = thing_solar_panels.get_meta()
meta_thing_solar_panels.set_label("Mark's Solar Panels")
meta_thing_solar_panels.set_description("Solar Array 3.3kW")
meta_thing_solar_panels.set_location(52.1965071,0.6067687)
meta_thing_solar_panels.set()
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 between you and the infrastructure
Raises rdflib.plugins.parsers.notation3.`BadSyntax` Exception if the RDF is badly formed `n3`
Raises xml.sax._exceptions.`SAXParseException` if the RDF is badly formed `xml` | 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
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure | 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._labelPredicate, Literal(label, lang))) | 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 of the label
`lang` (optional) (string) The two-character ISO 639-1 language code to use for your label.
None means use the default language for your agent.
See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) | 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 for your agent.
See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) | 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()
self._graph.add((subj, self._commentPredicate, Literal(description, lang))) | 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) (string) the new text of the description
`lang` (optional) (string) The two-character ISO 639-1 language code to use for your label.
None means use the default language for your agent.
See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) | 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 for your agent.
See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__) | 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_PATTERN.match(var_name):
class_name = cls.__name__ if isinstance(cls, type) else cls
return '_%s%s' % (class_name.lstrip('_'), var_name)
else:
return var_name | 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):
# condition with timeout is interruptable
self.__condition.wait(60)
return True
# same as non-blocking
elif timeout == 0:
return self.__lock.acquire(False)
elif timeout < 0:
raise ValueError('timeout value must be strictly positive (or -1)')
# blocking finite
else:
start = time()
waited_time = 0
with self.__condition:
while waited_time < timeout:
if self.__lock.acquire(False):
return True
else:
self.__condition.wait(timeout - waited_time)
waited_time = time() - start
return False
elif timeout != -1:
raise ValueError('can\'t specify a timeout for a non-blocking call')
else:
# non-blocking
return self.__lock.acquire(False) | 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_func(partial(func, self, *args, **kwargs), self.id_) | 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_middleware if mw in required_middleware]
if required_middleware != matching_middleware:
raise AssertionError(
"{} requires middleware order {} but matching middleware was {}".format(
concerned_object, required_middleware, matching_middleware
)
) | 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
required middleware to be checked.
Usage:
Add in __init__ method to a Middleware class to have its dependencies
checked on startup.
def __init__(self):
super(SomeMiddleware, self).__init__()
_check_middleware_dependencies(self, required_middleware=[
'edx_django_utils.cache.middleware.RequestCacheMiddleware',
])
Raises:
AssertionError if the provided dependencies don't appear in
MIDDLEWARE_CLASSES in the correct order. | 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 hasattr(self, 'params'):
parameters = self.params
method, url, headers, parameters = self.parse_request(
request, parameters, fake_method)
oauth_request = oauth2.Request.from_request(
method,
url,
headers=headers,
parameters=parameters)
self.oauth_server.verify_request(
oauth_request, self.oauth_consumer, {})
except oauth2.MissingSignature, e:
if handle_error:
return False
else:
raise e
# Signature was valid
return True | 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_messageIdentifier
status_node = root.imsx_POXHeader.\
imsx_POXResponseHeaderInfo.\
imsx_statusInfo
# Get status parameters from header info status
self.code_major = status_node.imsx_codeMajor
self.severity = status_node.imsx_severity
self.description = status_node.imsx_description
self.message_ref_identifier = str(
status_node.imsx_messageRefIdentifier)
self.operation = status_node.imsx_operationRefIdentifier
try:
# Try to get the score
self.score = str(root.imsx_POXBody.readResultResponse.
result.resultScore.textString)
except AttributeError:
# Not a readResult, just ignore!
pass
except:
pass | 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.SubElement(header, 'imsx_POXResponseHeaderInfo')
version = etree.SubElement(header_info, 'imsx_version')
version.text = 'V1.0'
message_identifier = etree.SubElement(header_info,
'imsx_messageIdentifier')
message_identifier.text = str(self.message_identifier)
status_info = etree.SubElement(header_info, 'imsx_statusInfo')
code_major = etree.SubElement(status_info, 'imsx_codeMajor')
code_major.text = str(self.code_major)
severity = etree.SubElement(status_info, 'imsx_severity')
severity.text = str(self.severity)
description = etree.SubElement(status_info, 'imsx_description')
description.text = str(self.description)
message_ref_identifier = etree.SubElement(
status_info,
'imsx_messageRefIdentifier')
message_ref_identifier.text = str(self.message_ref_identifier)
operation_ref_identifier = etree.SubElement(
status_info,
'imsx_operationRefIdentifier')
operation_ref_identifier.text = str(self.operation)
body = etree.SubElement(root, 'imsx_POXBody')
response = etree.SubElement(body, '%s%s' % (self.operation,
'Response'))
if self.score:
result = etree.SubElement(response, 'result')
result_score = etree.SubElement(result, 'resultScore')
language = etree.SubElement(result_score, 'language')
language.text = 'en'
text_string = etree.SubElement(result_score, 'textString')
text_string.text = str(self.score)
return '<?xml version="1.0" encoding="UTF-8"?>' + etree.tostring(root) | 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, thread.ident))
except:
logger.exception('Failed to dump stats')
return wrapper | 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 will quote values that contain characters other than the standard token characters. | 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')):
try:
content.body = content.body.decode(content.content_encoding)
except Exception:
pass
amqp_method = (self._method_override.get(method_sig) or
channel._METHOD_MAP.get(method_sig, None))
if amqp_method is None:
raise AMQPNotImplementedError(
'Unknown AMQP method {0!r}'.format(method_sig))
if content is None:
return amqp_method(channel, args)
else:
return amqp_method(channel, args, content) | 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:
self._send_method((10, 50), args)
return self.wait(allowed_methods=[
(10, 50), # Connection.close
(10, 51), # Connection.close_ok
])
except (socket.timeout, socket.error) as e:
# no point in waiting anymore
if isinstance(e, socket.timeout):
try:
self.sock.settimeout(0.1)
except:
pass
# lack of communication should not prevent tidy-up
self._do_close() | 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 provides the class and method id of the
method which caused the exception.
RULE:
After sending this method any received method except the
Close-OK method MUST be discarded.
RULE:
The peer sending this method MAY use a counter or timeout
to detect failure of the other peer to respond correctly
with the Close-OK method.
RULE:
When a server receives the Close method from a client it
MUST delete all server-side resources associated with the
client's context. A client CANNOT reconnect to a context
after sending or receiving a Close method.
PARAMETERS:
reply_code: short
The reply code. The AMQ reply codes are defined in AMQ
RFC 011.
reply_text: shortstr
The localised reply text. This text can be logged as an
aid to resolving issues.
class_id: short
failing method class
When the close is provoked by a method exception, this
is the class of the method.
method_id: short
failing method ID
When the close is provoked by a method exception, this
is the ID of the method. | 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)
if not units:
return type_names
if units:
unit_names = set()
for unit in units:
unit_names |= self.by_unit.get(unit, empty)
if not types:
return unit_names
return (type_names & unit_names) if (types and units) else 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
raise
if self.__value_templates is None:
raise ValueError('Point has no values')
if data is None:
template = PointDataObject(self.__value_templates, self.__filter)
else:
while True:
try:
template = PointDataObject._from_dict(self.__value_templates, self.__filter, data)
except:
# parsing has failed for first time since refresh so try again
if self.__last_parse_ok:
logger.debug('Failed to parse data from for point %s, refreshing', self.__point)
self.__last_parse_ok = False
try:
self.__refresh()
except RefreshException:
break
else:
raise
else:
self.__last_parse_ok = True
break
return template | 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:
label = raw_value['label']
if not valid_identifier(label) or label.startswith('__'):
raise RefreshException('Value "%s" unsuitable for object wrapper' % label)
value = Value(label, raw_value['type'], raw_value['unit'], raw_value['comment'])
templates.append(value)
try:
by_type[value.type_].add(label)
except KeyError:
by_type[value.type_] = {label}
if value.unit:
try:
by_unit[value.unit].add(label)
except KeyError:
by_unit[value.unit] = {label}
self.__value_templates = templates
self.__filter = _ValueFilter(by_type, by_unit) | 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['meta']['values']
else:
limit = 100
offset = 0
while True:
new = self.__point.list(limit=limit, offset=offset)
values += new
if len(new) < limit:
break
offset += limit
# Unlike for describe, value comments are keyed by language here, so unwrap to have same layout as for
# describe call (default language only, if available).
lang = self.__client.default_lang
for value in values:
value['comment'] = value['comment'].get(lang, None) if value['comment'] else None
return values | 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.title = child.text
if 'description' in child.tag:
self.description = child.text
if 'secure_launch_url' in child.tag:
self.secure_launch_url = child.text
elif 'launch_url' in child.tag:
self.launch_url = child.text
if 'icon' in child.tag:
self.icon = child.text
if 'secure_icon' in child.tag:
self.secure_icon = child.text
if 'cartridge_bundle' in child.tag:
self.cartridge_bundle = child.attrib['identifierref']
if 'catridge_icon' in child.tag:
self.cartridge_icon = child.atrib['identifierref']
if 'vendor' in child.tag:
# Parse vendor tag
for v_child in child.getchildren():
if 'code' in v_child.tag:
self.vendor_code = v_child.text
if 'description' in v_child.tag:
self.vendor_description = v_child.text
if 'name' in v_child.tag:
self.vendor_name = v_child.text
if 'url' in v_child.tag:
self.vendor_url = v_child.text
if 'contact' in v_child.tag:
# Parse contact tag for email and name
for c_child in v_child:
if 'name' in c_child.tag:
self.vendor_contact_name = c_child.text
if 'email' in c_child.tag:
self.vendor_contact_email = c_child.text
if 'custom' in child.tag:
# Parse custom tags
for custom_child in child.getchildren():
self.custom_params[custom_child.attrib['name']] =\
custom_child.text
if 'extensions' in child.tag:
platform = child.attrib['platform']
properties = {}
# Parse extension tags
for ext_child in child.getchildren():
if 'property' in ext_child.tag:
properties[ext_child.attrib['name']] = ext_child.text
elif 'options' in ext_child.tag:
opt_name = ext_child.attrib['name']
options = {}
for option_child in ext_child.getchildren():
options[option_child.attrib['name']] =\
option_child.text
properties[opt_name] = options
self.set_ext_params(platform, properties) | 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'], 'schemaLocation'): 'http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd',
'xmlns': 'http://www.imsglobal.org/xsd/imslticc_v1p0'
}, nsmap = NSMAP)
for key in ['title', 'description', 'launch_url', 'secure_launch_url']:
option = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'], key))
option.text = getattr(self, key)
vendor_keys = ['name', 'code', 'description', 'url']
if any('vendor_' + key for key in vendor_keys) or\
self.vendor_contact_email:
vendor_node = etree.SubElement(root, '{%s}%s'
%(NSMAP['blti'], 'vendor'))
for key in vendor_keys:
if getattr(self, 'vendor_' + key) != None:
v_node = etree.SubElement(vendor_node,
'{%s}%s' %(NSMAP['lticp'], key))
v_node.text = getattr(self, 'vendor_' + key)
if getattr(self, 'vendor_contact_email'):
v_node = etree.SubElement(vendor_node,
'{%s}%s' %(NSMAP['lticp'], 'contact'))
c_name = etree.SubElement(v_node,
'{%s}%s' %(NSMAP['lticp'], 'name'))
c_name.text = self.vendor_contact_name
c_email = etree.SubElement(v_node,
'{%s}%s' %(NSMAP['lticp'], 'email'))
c_email.text = self.vendor_contact_email
# Custom params
if len(self.custom_params) != 0:
custom_node = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'],
'custom'))
for (key, val) in sorted(self.custom_params.items()):
c_node = etree.SubElement(custom_node, '{%s}%s'
%(NSMAP['lticm'], 'property'))
c_node.set('name', key)
c_node.text = val
# Extension params
if len(self.extensions) != 0:
for (key, params) in sorted(self.extensions.items()):
extension_node = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'],
'extensions'), platform = key)
self.recursive_options(extension_node,params)
if getattr(self, 'cartridge_bundle'):
identifierref = etree.SubElement(root, 'cartridge_bundle',
identifierref = self.cartridge_bundle)
if getattr(self, 'cartridge_icon'):
identifierref = etree.SubElement(root, 'cartridge_icon',
identifierref = self.cartridge_icon)
return '<?xml version="1.0" encoding="UTF-8"?>' + etree.tostring(root) | 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)
del self.fragment
super(AndroidFragment, self).destroy() | 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_view(), 0))
else:
self.widget = self.load_view()
return self.widget | 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(
"@gen.engine functions cannot return values: %r" %
(future.result(),))
# The engine interface doesn't give us any way to return
# errors but to raise them into the stack context.
# Save the stack context here to use when the Future has resolved.
future.add_done_callback(stack_context.wrap(final_callback))
return wrapper | 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 `.Future` and the ``callback`` argument is not treated
specially.
In most cases, functions decorated with `engine` should take
a ``callback`` argument and invoke it with their result when
they are finished. One notable exception is the
`~tornado.web.RequestHandler` :ref:`HTTP verb methods <verbs>`,
which use ``self.finish()`` in place of a callback argument. | 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 replace_callback and 'callback' in kwargs:
callback = kwargs.pop('callback')
IOLoop.current().add_future(
future, lambda future: callback(future.result()))
try:
result = func(*args, **kwargs)
except (Return, StopIteration) as e:
result = _value_from_stopiteration(e)
except Exception:
future.set_exc_info(sys.exc_info())
return future
else:
if isinstance(result, GeneratorType):
# Inline the first iteration of Runner.run. This lets us
# avoid the cost of creating a Runner when the coroutine
# never actually yields, which in turn allows us to
# use "optional" coroutines in critical path code without
# performance penalty for the synchronous case.
try:
orig_stack_contexts = stack_context._state.contexts
yielded = next(result)
if stack_context._state.contexts is not orig_stack_contexts:
yielded = TracebackFuture()
yielded.set_exception(
stack_context.StackContextInconsistentError(
'stack_context inconsistency (probably caused '
'by yield within a "with StackContext" block)'))
except (StopIteration, Return) as e:
future.set_result(_value_from_stopiteration(e))
except Exception:
future.set_exc_info(sys.exc_info())
else:
_futures_to_runners[future] = Runner(result, future, yielded)
yielded = None
try:
return future
finally:
# Subtle memory optimization: if next() raised an exception,
# the future's exc_info contains a traceback which
# includes this stack frame. This creates a cycle,
# which will be collected at the next full GC but has
# been shown to greatly increase memory usage of
# benchmarks (relative to the refcount-based scheme
# used in the absence of cycles). We can avoid the
# cycle by clearing the local variable after we return it.
future = None
future.set_result(result)
return future
wrapper.__wrapped__ = wrapped
wrapper.__tornado_coroutine__ = True
return wrapper | 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.ExceptionStackContext(handle_exception):
func(*args, callback=_argument_adapter(set_result), **kwargs)
return future | 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.0
``gen.Task`` is now a function that returns a `.Future`, instead of
a subclass of `YieldPoint`. It still behaves the same way when
yielded. | 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 the same order; if it is a dict, the result is a dict
with the same keys.
That is, ``results = yield multi(list_of_futures)`` is equivalent
to::
results = []
for future in list_of_futures:
results.append(yield future)
If any children raise exceptions, ``multi()`` will raise the first
one. All others will be logged, unless they are of types
contained in the ``quiet_exceptions`` argument.
If any of the inputs are `YieldPoints <YieldPoint>`, the returned
yieldable object is a `YieldPoint`. Otherwise, returns a `.Future`.
This means that the result of `multi` can be used in a native
coroutine if and only if all of its children can be.
In a ``yield``-based coroutine, it is not normally necessary to
call this function directly, since the coroutine runner will
do it automatically when a list or dict is yielded. However,
it is necessary in ``await``-based coroutines, or to pass
the ``quiet_exceptions`` argument.
This function is available under the names ``multi()`` and ``Multi()``
for historical reasons.
.. versionchanged:: 4.2
If multiple yieldables fail, any exceptions after the first
(which is raised) will be logged. Added the ``quiet_exceptions``
argument to suppress this logging for selected exception types.
.. versionchanged:: 4.3
Replaced the class ``Multi`` and the function ``multi_future``
with a unified function ``multi``. Added support for yieldables
other than `YieldPoint` and `.Future`. | 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 children:
future.set_result({} if keys is not None else [])
def callback(f):
unfinished_children.remove(f)
if not unfinished_children:
result_list = []
for f in children:
try:
result_list.append(f.result())
except Exception as e:
if future.done():
if not isinstance(e, quiet_exceptions):
app_log.error("Multiple exceptions in yield list",
exc_info=True)
else:
future.set_exc_info(sys.exc_info())
if not future.done():
if keys is not None:
future.set_result(dict(zip(keys, result_list)))
else:
future.set_result(result_list)
listening = set()
for f in children:
if f not in listening:
listening.add(f)
f.add_done_callback(callback)
return future | 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 the ``quiet_exceptions``
argument to suppress this logging for selected exception types.
.. deprecated:: 4.3
Use `multi` instead. | 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 function only handles ``Futures``, not other yieldable objects.
Instead of `maybe_future`, check for the non-future result types
you expect (often just ``None``), and ``yield`` anything unknown. | 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 cancelling it might disrupt other
# callers and B) concurrent futures can only be cancelled while they are
# in the queue, so cancellation cannot reliably bound our waiting time.
future = convert_yielded(future)
result = Future()
chain_future(future, result)
io_loop = IOLoop.current()
def error_callback(future):
try:
future.result()
except Exception as e:
if not isinstance(e, quiet_exceptions):
app_log.error("Exception in Future %r after timeout",
future, exc_info=True)
def timeout_callback():
result.set_exception(TimeoutError("Timeout"))
# In case the wrapped future goes on to fail, log it.
future.add_done_callback(error_callback)
timeout_handle = io_loop.add_timeout(
timeout, timeout_callback)
if isinstance(future, Future):
# We know this future will resolve on the IOLoop, so we don't
# need the extra thread-safety of IOLoop.add_future (and we also
# don't care about StackContext here.
future.add_done_callback(
lambda future: io_loop.remove_timeout(timeout_handle))
else:
# concurrent.futures.Futures may resolve on any thread, so we
# need to route them back to the IOLoop.
io_loop.add_future(
future, lambda future: io_loop.remove_timeout(timeout_handle))
return result | 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`)
If the wrapped `.Future` fails after it has timed out, the exception
will be logged unless it is of a type contained in ``quiet_exceptions``
(which may be an exception type or a sequence of types).
Does not support `YieldPoint` subclasses.
.. versionadded:: 4.0
.. versionchanged:: 4.1
Added the ``quiet_exceptions`` argument and the logging of unhandled
exceptions.
.. versionchanged:: 4.4
Added support for yieldable objects other than `.Future`. | 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 nothing; you must
wait on the `.Future` it returns (usually by yielding it).
.. versionadded:: 4.1 | 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)
else:
raise BadYieldError("yielded unknown object %r" % (yielded,)) | 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 _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
.. versionadded:: 4.1 | 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,))
self.pending_callbacks.add(key) | 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
self.run() | 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:
orig_stack_contexts = stack_context._state.contexts
exc_info = None
try:
value = future.result()
except Exception:
self.had_exception = True
exc_info = sys.exc_info()
future = None
if exc_info is not None:
try:
yielded = self.gen.throw(*exc_info)
finally:
# Break up a reference to itself
# for faster GC on CPython.
exc_info = None
else:
yielded = self.gen.send(value)
if stack_context._state.contexts is not orig_stack_contexts:
self.gen.throw(
stack_context.StackContextInconsistentError(
'stack_context inconsistency (probably caused '
'by yield within a "with StackContext" block)'))
except (StopIteration, Return) as e:
self.finished = True
self.future = _null_future
if self.pending_callbacks and not self.had_exception:
# If we ran cleanly without waiting on all callbacks
# raise an error (really more of a warning). If we
# had an exception then some callbacks may have been
# orphaned, so skip the check in that case.
raise LeakedCallbackError(
"finished without waiting for callbacks %r" %
self.pending_callbacks)
self.result_future.set_result(_value_from_stopiteration(e))
self.result_future = None
self._deactivate_stack_context()
return
except Exception:
self.finished = True
self.future = _null_future
self.result_future.set_exc_info(sys.exc_info())
self.result_future = None
self._deactivate_stack_context()
return
if not self.handle_yield(yielded):
return
yielded = None
finally:
self.running = False | 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)
# items.append(FOLDER_TMPL.format(
# name=subdirname,
# id=path,
# items=self.render_files(path)
# ))
#for filename in filenames:
f,ext = os.path.splitext(filename)
if ext in ['.py', '.enaml']:
items.append(FILE_TMPL.format(
name=filename,
id=filename
))
return "".join(items) | 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>extends component</td>"
"<td><a href='#component-{id}'>{name}</a></td></td>"
.format(id=parent.__name__.lower(), name=parent.__name__))
#: Source and example, only works with enamlnative builtins
source_path = inspect.getfile(declaration).replace(
".pyo", ".py").replace(".pyc", ".py")
if 'enamlnative' in source_path:
source_link = "https://github.com/frmdstryr/" \
"enaml-native/tree/master/src/{}".format(
source_path.split("assets/python")[1]
)
info.append("<tr><td>source code</td>"
"<td><a href='{}' target='_blank'>show</a></td></td>"
.format(source_link))
#: Examples link
example_link = "https://www.codelv.com/projects/" \
"enaml-native/docs/components#{}" \
.format(declaration.__name__.lower())
info.append("<tr><td>example usage</td>"
"<td><a href='{}' target='_blank'>view</a></td></td>"
.format(example_link))
return COMPONENT_TMPL.format(id=declaration.__name__.lower(),
name=declaration.__name__,
info="".join(info),
items="".join(items)) | 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.start(self) | 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}
else:
err = "Warning: Unhandled message: {}".format(msg)
print(err)
return {'ok': False, 'message': err} | 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: Implement for iOS...
pass
self.save_changed_files(msg)
if app.load_view is None:
print("Warning: Reloading the view is not implemented. "
"Please set `app.load_view` to support this.")
return
if app.view is not None:
try:
app.view.destroy()
except:
pass
def wrapped(f):
def safe_reload(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
#: Display the error
app.send_event(Command.ERROR, traceback.format_exc())
return safe_reload
app.deferred_call(wrapped(app.load_view), app) | 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....")
with hotswap.active():
hotswap.update(app.view)
except:
#: Display the error
app.send_event(Command.ERROR, traceback.format_exc()) | 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.