code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with open_file(file, "rb") as f:
header = f.read(8)
f.seek(0)
if header != PNG_SIGN:
b = file_to_png(f)
else:
b = f.read()
return cls.from_bytes(b) | def open_any(cls, file) | Open an image file. If the image is not PNG format, it would convert
the image into PNG with Pillow module. If the module is not
installed, :class:`ImportError` would be raised.
:arg file: Input file.
:type file: path-like or file-like
:rtype: :class:`PNG` | 3.405565 | 3.735693 | 0.911629 |
im = cls()
im.chunks = list(parse_chunks(b))
im.init()
return im | def from_bytes(cls, b) | Create :class:`PNG` from raw bytes.
:arg bytes b: The raw bytes of the PNG file.
:rtype: :class:`PNG` | 7.076591 | 8.284366 | 0.85421 |
im = cls()
im.chunks = chunks
im.init()
return im | def from_chunks(cls, chunks) | Construct PNG from raw chunks.
:arg chunks: A list of ``(chunk_type, chunk_raw_data)``. Also see
:func:`chunks`.
:type chunks: list[tuple(str, bytes)] | 6.100677 | 6.731064 | 0.906347 |
chunks = [PNG_SIGN]
chunks.extend(c[1] for c in self.chunks)
return b"".join(chunks) | def to_bytes(self) | Convert the entire image to bytes.
:rtype: bytes | 6.222947 | 6.915537 | 0.89985 |
return struct.pack(
"!IIIIHHbb", self.width, self.height, self.x_offset, self.y_offset,
self.delay, self.delay_den, self.depose_op, self.blend_op
) | def to_bytes(self) | Convert to bytes.
:rtype: bytes | 6.324043 | 6.38676 | 0.99018 |
if not isinstance(png, PNG):
raise TypeError("Expect an instance of `PNG` but got `{}`".format(png))
control = FrameControl(**options)
if control.width is None:
control.width = png.width
if control.height is None:
control.height = png.height
self.frames.append((png, control)) | def append(self, png, **options) | Append one frame.
:arg PNG png: Append a :class:`PNG` as a frame.
:arg dict options: The options for :class:`FrameControl`. | 2.882509 | 2.559258 | 1.126307 |
self.append(PNG.open_any(file), **options) | def append_file(self, file, **options) | Create a PNG from file and append the PNG as a frame.
:arg file: Input file.
:type file: path-like or file-like.
:arg dict options: The options for :class:`FrameControl`. | 16.459822 | 16.930502 | 0.972199 |
# grab the chunks we needs
out = [PNG_SIGN]
# FIXME: it's tricky to define "other_chunks". HoneyView stop the
# animation if it sees chunks other than fctl or idat, so we put other
# chunks to the end of the file
other_chunks = []
seq = 0
# for first frame
png, control = self.frames[0]
... | def to_bytes(self) | Convert the entire image to bytes.
:rtype: bytes | 3.640769 | 3.579044 | 1.017246 |
im = cls()
for file in files:
im.append_file(file, **options)
return im | def from_files(cls, files, **options) | Create an APNG from multiple files.
This is a shortcut of::
im = APNG()
for file in files:
im.append_file(file, **options)
:arg list files: A list of filename. See :meth:`PNG.open`.
:arg dict options: Options for :class:`FrameControl`.
:rtype: APNG | 3.826815 | 3.00854 | 1.271984 |
hdr = None
head_chunks = []
end = ("IEND", make_chunk("IEND", b""))
frame_chunks = []
frames = []
num_plays = 0
frame_has_head_chunks = False
control = None
for type_, data in parse_chunks(b):
if type_ == "IHDR":
hdr = data
frame_chunks.append((type_, data))
elif type_ == "ac... | def from_bytes(cls, b) | Create an APNG from raw bytes.
:arg bytes b: The raw bytes of the APNG file.
:rtype: APNG | 2.61534 | 2.561574 | 1.020989 |
from livereload import Server
server = Server()
server.watch("README.rst", "py cute.py readme_build")
server.serve(open_url_delay=1, root="build/readme") | def readme() | Live reload readme | 8.443266 | 6.983119 | 1.209097 |
self.add_sensor(Sensor(int, 'int_sensor%d' % len(self._sensors),
'descr', 'unit', params=[-10, 10]))
return Message.reply('add-sensor', 'ok') | def request_add_sensor(self, sock, msg) | add a sensor | 9.973846 | 9.57715 | 1.041421 |
def fixup_numbers(val):
try:
# See if it is a number
return str(float(val))
except ValueError:
# ok, it is not a number we know of, perhaps a string
return str(val)
if isinstance(params, basestring):
params = params.split(' ')
# No... | def normalize_strategy_parameters(params) | Normalize strategy parameters to be a list of strings.
Parameters
----------
params : (space-delimited) string or sequence of strings/numbers Parameters
expected by :class:`SampleStrategy` object, in various forms, where the first
parameter is the name of the strategy.
Returns
----... | 5.890491 | 5.521961 | 1.066739 |
sensor_name = escape_name(sensor_name)
sensor = self.sensor[sensor_name]
try:
yield sensor.wait(condition_or_value, timeout)
except tornado.gen.TimeoutError:
raise tornado.gen.Return(False)
else:
raise tornado.gen.Return(True) | def wait(self, sensor_name, condition_or_value, timeout=5) | Wait for a sensor in this resource to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callable,
... | 2.558517 | 3.341157 | 0.765758 |
def list_sensors(self, filter="", strategy=False, status="",
use_python_identifiers=True, tuple=False, refresh=False) | List sensors available on this resource matching certain criteria.
Parameters
----------
filter : string, optional
Filter each returned sensor's name against this regexp if specified.
To ease the dichotomy between Python identifier names and actual
sensor nam... | 47,497.375 | 65,890.335938 | 0.720855 | |
sensors_strategies = {}
sensor_results = yield self.list_sensors(filter)
for sensor_reslt in sensor_results:
norm_name = sensor_reslt.object.normalised_name
try:
sensor_strat = yield self.set_sampling_strategy(norm_name, strategy_and_params)
... | def set_sampling_strategies(self, filter, strategy_and_params) | Set a sampling strategy for all sensors that match the specified filter.
Parameters
----------
filter : string
The regular expression filter to use to select the sensors to which
to apply the specified strategy. Use "" to match all sensors. Is
matched using ... | 4.080971 | 3.176811 | 1.284612 |
sensors_strategies = {}
try:
sensor_obj = self.sensor.get(sensor_name)
yield sensor_obj.set_sampling_strategy(strategy_and_params)
sensors_strategies[sensor_obj.normalised_name] = (
True, sensor_obj.sampling_strategy)
except Except... | def set_sampling_strategy(self, sensor_name, strategy_and_params) | Set a sampling strategy for a specific sensor.
Parameters
----------
sensor_name : string
The specific sensor.
strategy_and_params : seq of str or str
As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy
names and parameters are a... | 3.208283 | 2.628772 | 1.220449 |
if not params:
param_args = []
elif isinstance(params, basestring):
param_args = [str(p) for p in params.split(' ')]
else:
if not isinstance(params, collections.Iterable):
params = (params,)
param_args = [str(p) for p in pa... | def set_strategy(self, strategy, params=None) | Set current sampling strategy for sensor.
Add this footprint for backwards compatibility.
Parameters
----------
strategy : seq of str or str
As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy
names and parameters are as defined by the KATC... | 3.068521 | 2.936178 | 1.045073 |
listener_id = hashable_identity(listener)
self._listeners[listener_id] = (listener, reading)
logger.debug(
'Register listener for {}'
.format(self.name)) | def register_listener(self, listener, reading=False) | Add a callback function that is called when sensor value is updated.
The callback footprint is received_timestamp, timestamp, status, value.
Parameters
----------
listener : function
Callback signature: if reading
listener(katcp_sensor, reading) where
... | 6.094497 | 8.785133 | 0.693728 |
listener_id = hashable_identity(listener)
self._listeners.pop(listener_id, None) | def unregister_listener(self, listener) | Remove a listener callback added with register_listener().
Parameters
----------
listener : function
Reference to the callback function that should be removed | 6.118714 | 17.625242 | 0.347156 |
received_timestamp = self._manager.time()
reading = KATCPSensorReading(received_timestamp, timestamp, status, value)
self._reading = reading
self.call_listeners(reading) | def set(self, timestamp, status, value) | Set sensor with a given received value, matches :meth:`katcp.Sensor.set` | 8.99698 | 6.181375 | 1.455498 |
if timestamp is None:
timestamp = self._manager.time()
self.set(timestamp, status, value) | def set_value(self, value, status=Sensor.NOMINAL, timestamp=None) | Set sensor value with optinal specification of status and timestamp | 5.774866 | 5.85681 | 0.986009 |
yield self._manager.poll_sensor(self._name)
# By now the sensor manager should have set the reading
raise Return(self._reading) | def get_reading(self) | Get a fresh sensor reading from the KATCP resource
Returns
-------
reply : tornado Future resolving with :class:`KATCPSensorReading` object
Note
----
As a side-effect this will update the reading stored in this object, and result in
registered listeners being ... | 17.33403 | 18.151768 | 0.95495 |
yield self._manager.poll_sensor(self._name)
# By now the sensor manager should have set the reading
raise Return(self._reading.value) | def get_value(self) | Get a fresh sensor value from the KATCP resource
Returns
-------
reply : tornado Future resolving with :class:`KATCPSensorReading` object
Note
----
As a side-effect this will update the reading stored in this object, and result in
registered listeners being ca... | 22.26408 | 17.720129 | 1.256429 |
yield self._manager.poll_sensor(self._name)
# By now the sensor manager should have set the reading
raise Return(self._reading.status) | def get_status(self) | Get a fresh sensor status from the KATCP resource
Returns
-------
reply : tornado Future resolving with :class:`KATCPSensorReading` object
Note
----
As a side-effect this will update the reading stored in this object, and result in
registered listeners being c... | 22.327433 | 18.322962 | 1.218549 |
if (isinstance(condition_or_value, collections.Sequence) and not
isinstance(condition_or_value, basestring)):
raise NotImplementedError(
'Currently only single conditions are supported')
condition_test = (condition_or_value if callable(condition_or_va... | def wait(self, condition_or_value, timeout=None) | Wait for the sensor to satisfy a condition.
Parameters
----------
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callable,
condition_or_value(reading) is called, and must return True if its
cond... | 3.973233 | 3.543739 | 1.121198 |
# TODO Implement allow_any_request functionality. When True, any unknown request (even
# if there is no fake implementation) should succeed
allow_any_request = fake_options.get('allow_any_request', False)
class FakeKATCPClientResource(KATCPClientResourceClass):
def inspecting_client_factor... | def fake_KATCP_client_resource_factory(
KATCPClientResourceClass, fake_options, resource_spec, *args, **kwargs) | Create a fake KATCPClientResource-like class and a fake-manager
Parameters
----------
KATCPClientResourceClass : class
Subclass of :class:`katcp.resource_client.KATCPClientResource`
fake_options : dict
Options for the faking process. Keys:
allow_any_request : bool, default F... | 4.184691 | 3.293428 | 1.270619 |
# TODO allow_any_request see comment in fake_KATCP_client_resource_factory()
allow_any_request = fake_options.get('allow_any_request', False)
class FakeKATCPClientResourceContainer(KATCPClientResourceContainerClass):
def __init__(self, *args, **kwargs):
self.fake_client_resource_ma... | def fake_KATCP_client_resource_container_factory(
KATCPClientResourceContainerClass, fake_options, resources_spec,
*args, **kwargs) | Create a fake KATCPClientResourceContainer-like class and a fake-manager
Parameters
----------
KATCPClientResourceContainerClass : class
Subclass of :class:`katcp.resource_client.KATCPClientResourceContainer`
fake_options : dict
Options for the faking process. Keys:
allow_an... | 2.673731 | 2.313473 | 1.155722 |
if msg.arguments:
name = (msg.arguments[0],)
keys = (name, )
if name not in self.fake_sensor_infos:
return ("fail", "Unknown sensor name.")
else:
keys = self.fake_sensor_infos.keys()
num_informs = 0
for sensor_name... | def request_sensor_list(self, req, msg) | Sensor list | 3.832523 | 3.811465 | 1.005525 |
# Check sensor validity. parse_type() and parse_params should raise if not OK
for s_name, s_info in sensor_infos.items():
s_type = Sensor.parse_type(s_info[2])
s_params = Sensor.parse_params(s_type, s_info[3:])
self.fake_sensor_infos.update(sensor_infos)
... | def add_sensors(self, sensor_infos) | Add fake sensors
sensor_infos is a dict <sensor-name> : (
<description>, <unit>, <sensor-type>, <params>*)
The sensor info is string-reprs of whatever they are, as they would be on
the wire in a real KATCP connection. Values are passed to a katcp.Message object,
so some auto... | 7.001494 | 6.286239 | 1.113781 |
rh_dict = {}
for name in dir(rh_obj):
if not callable(getattr(rh_obj, name)):
continue
if name.startswith("request_"):
request_name = convert_method_name("request_", name)
req_meth = getattr(rh_obj, name)
rh... | def add_request_handlers_object(self, rh_obj) | Add fake request handlers from an object with request_* method(s)
See :meth:`FakeInspectingClientManager.add_request_handlers_dict` for more detail. | 2.700973 | 2.556452 | 1.056532 |
# Check that all the callables have docstrings as strings
for req_func in rh_dict.values():
assert req_func.__doc__, "Even fake request handlers must have docstrings"
self._fkc.request_handlers.update(rh_dict)
self._fic._interface_changed.set() | def add_request_handlers_dict(self, rh_dict) | Add fake request handler functions from a dict keyed by request name
Note the keys must be the KATCP message name (i.e. "the-request", not
"the_request")
The request-handler interface is more or less compatible with request handler API
in :class:`katcp.server.DeviceServerBase`. The fak... | 13.519594 | 11.780773 | 1.147598 |
mid = self._get_mid_and_update_msg(msg, use_mid)
if msg.name in self.request_handlers:
req = FakeClientRequestConnection(self.client_connection, msg)
reply_msg = yield tornado.gen.maybe_future(
self.request_handlers[msg.name](req, msg))
reply... | def future_request(self, msg, timeout=None, use_mid=None) | Send a request messsage, with future replies.
Parameters
----------
msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the
the timeout set when creating the AsyncClient.
us... | 4.685216 | 4.71443 | 0.993803 |
try:
self._validate_parameters()
self._base_delay = min(
self._base_delay * self.exp_fac,
self.delay_max)
self._update_delay()
except Exception:
ic_logger.exception(
'Unhandled exception trying to ca... | def failed(self) | Call whenever an action has failed, grows delay exponentially
After calling failed(), the `delay` property contains the next delay | 10.035425 | 8.386035 | 1.196683 |
# Do not hook the same callback multiple times
if callback not in self._inform_hooks[inform_name]:
self._inform_hooks[inform_name].append(callback) | def hook_inform(self, inform_name, callback) | Hookup a function to be called when an inform is received.
Useful for interface-changed and sensor-status informs.
Parameters
----------
inform_name : str
The name of the inform.
callback : function
The function to be called. | 3.562504 | 4.717937 | 0.755098 |
try:
for func in self._inform_hooks.get(msg.name, []):
func(msg)
except Exception:
self._logger.warning('Call to function "{0}" with message "{1}".'
.format(func, msg), exc_info=True)
super(_InformHookDeviceClient,... | def handle_inform(self, msg) | Call callbacks on hooked informs followed by normal processing | 5.056144 | 4.366518 | 1.157935 |
return _InformHookDeviceClient(host, port, *args, **kwargs) | def inform_hook_client_factory(self, host, port, *args, **kwargs) | Return an instance of :class:`_InformHookDeviceClient` or similar
Provided to ease testing. Dynamically overriding this method after instantiation
but before start() is called allows for deep brain surgery. See
:class:`katcp.fake_clients.TBD` | 7.313822 | 4.340995 | 1.684826 |
return self._state.until_state(desired_state, timeout=timeout) | def until_state(self, desired_state, timeout=None) | Wait until state is desired_state, InspectingClientStateType instance
Returns a future | 5.776423 | 7.32385 | 0.788714 |
# Start KATCP device client.
assert not self._running
maybe_timeout = future_timeout_manager(timeout)
self._logger.debug('Starting katcp client')
self.katcp_client.start()
try:
yield maybe_timeout(self.katcp_client.until_running())
self._... | def connect(self, timeout=None) | Connect to KATCP interface, starting what is needed
Parameters
----------
timeout : float, None
Time to wait until connected. No waiting if None.
Raises
------
:class:`tornado.gen.TimeoutError` if the connect timeout expires | 4.051088 | 3.92848 | 1.03121 |
timeout_manager = future_timeout_manager(self.sync_timeout)
sensor_index_before = copy.copy(self._sensors_index)
request_index_before = copy.copy(self._requests_index)
try:
request_changes = yield self.inspect_requests(
timeout=timeout_manager.remaini... | def inspect(self) | Inspect device requests and sensors, update model
Returns
-------
Tornado future that resolves with:
model_changes : Nested AttrDict or None
Contains sets of added/removed request/sensor names
Example structure:
{'requests': {
'add... | 4.213518 | 3.402609 | 1.23832 |
maybe_timeout = future_timeout_manager(timeout)
if name is None:
msg = katcp.Message.request('help')
else:
msg = katcp.Message.request('help', name)
reply, informs = yield self.katcp_client.future_request(
msg, timeout=maybe_timeout.remaining(... | def inspect_requests(self, name=None, timeout=None) | Inspect all or one requests on the device. Update requests index.
Parameters
----------
name : str or None, optional
Name of the request or None to get all requests.
timeout : float or None, optional
Timeout for request inspection, None for no timeout
Re... | 4.437538 | 4.327999 | 1.02531 |
timeout_hints = {}
req_msg_args = ['request-timeout-hint']
if name:
req_msg_args.append(name)
req_msg = katcp.Message.request(*req_msg_args)
reply, informs = yield self.katcp_client.future_request(
req_msg, timeout=timeout)
if not reply.re... | def _get_request_timeout_hints(self, name=None, timeout=None) | Get request timeout hints from device
Parameters
=========
name : str or None, optional
Name of the request or None to get all request timeout hints.
timeout : float seconds
Timeout for ?request-timeout-hint
Returns
-------
Tornado future... | 3.688393 | 3.220437 | 1.145308 |
if name is None:
msg = katcp.Message.request('sensor-list')
else:
msg = katcp.Message.request('sensor-list', name)
reply, informs = yield self.katcp_client.future_request(
msg, timeout=timeout)
self._logger.debug('{} received {} sensor-list i... | def inspect_sensors(self, name=None, timeout=None) | Inspect all or one sensor on the device. Update sensors index.
Parameters
----------
name : str or None, optional
Name of the sensor or None to get all sensors.
timeout : float or None, optional
Timeout for sensors inspection, None for no timeout
Returns... | 3.84319 | 3.799395 | 1.011527 |
exist = False
yield self.until_data_synced()
if name in self._sensors_index:
exist = True
else:
if update or (update is None and self._update_on_lookup):
yield self.inspect_sensors(name)
exist = yield self.future_check_sens... | def future_check_sensor(self, name, update=None) | Check if the sensor exists.
Used internally by future_get_sensor. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
Name of the sensor to verify.
update : bool or None, optional
... | 6.260334 | 5.967037 | 1.049153 |
obj = None
exist = yield self.future_check_sensor(name, update)
if exist:
sensor_info = self._sensors_index[name]
obj = sensor_info.get('obj')
if obj is None:
sensor_type = katcp.Sensor.parse_type(
sensor_info.get('... | def future_get_sensor(self, name, update=None) | Get the sensor object.
Check if we have information for this sensor, if not connect to server
and update (if allowed) to get information.
Parameters
----------
name : string
Name of the sensor.
update : bool or None, optional
True allow inspect c... | 2.816216 | 2.854047 | 0.986745 |
exist = False
yield self.until_data_synced()
if name in self._requests_index:
exist = True
else:
if update or (update is None and self._update_on_lookup):
yield self.inspect_requests(name)
exist = yield self.future_check_re... | def future_check_request(self, name, update=None) | Check if the request exists.
Used internally by future_get_request. This method is aware of
synchronisation in progress and if inspection of the server is allowed.
Parameters
----------
name : str
Name of the request to verify.
update : bool or None, optiona... | 6.348905 | 5.661349 | 1.121447 |
obj = None
exist = yield self.future_check_request(name, update)
if exist:
request_info = self._requests_index[name]
obj = request_info.get('obj')
if obj is None:
obj = self.request_factory(**request_info)
self._request... | def future_get_request(self, name, update=None) | Get the request object.
Check if we have information for this request, if not connect to server
and update (if allowed).
Parameters
----------
name : string
Name of the request.
update : bool or None, optional
True allow inspect client to inspect... | 3.719048 | 3.955206 | 0.940292 |
timestamp = msg.arguments[0]
num_sensors = int(msg.arguments[1])
assert len(msg.arguments) == 2 + num_sensors * 3
for n in xrange(num_sensors):
name = msg.arguments[2 + n * 3]
status = msg.arguments[3 + n * 3]
value = msg.arguments[4 + n * 3]
... | def _cb_inform_sensor_status(self, msg) | Update received for an sensor. | 2.4207 | 2.303614 | 1.050827 |
self._logger.debug('cb_inform_interface_change(%s)', msg)
self._interface_changed.set() | def _cb_inform_interface_change(self, msg) | Update the sensors and requests available. | 4.505548 | 3.812105 | 1.181905 |
# TODO (NM 2016-11-03) This method should really live on the lower level
# katcp_client in client.py, is generally useful IMHO
use_mid = kwargs.get('use_mid')
timeout = kwargs.get('timeout')
mid = kwargs.get('mid')
msg = katcp.Message.request(request, *args, mid=... | def simple_request(self, request, *args, **kwargs) | Create and send a request to the server.
This method implements a very small subset of the options
possible to send an request. It is provided as a shortcut to
sending a simple request.
Parameters
----------
request : str
The request to call.
*args :... | 7.683805 | 6.286361 | 1.222298 |
original_keys = set(original_keys)
updated_keys = set(updated_keys)
added_keys = updated_keys.difference(original_keys)
removed_keys = set()
if name is None:
removed_keys = original_keys.difference(updated_keys)
elif name not in updated_keys and name ... | def _difference(self, original_keys, updated_keys, name, item_index) | Calculate difference between the original and updated sets of keys.
Removed items will be removed from item_index, new items should have
been added by the discovery process. (?help or ?sensor-list)
This method is for use in inspect_requests and inspect_sensors only.
Returns
--... | 2.837766 | 2.96202 | 0.958051 |
r = random.choice(self.FRUIT + [None])
if r is None:
return ("fail", "No fruit.")
delay = random.randrange(1,5)
req.inform("Picking will take %d seconds" % delay)
def pick_handler():
self._fruit_result.set_value(r)
req.reply("ok", r)
... | def request_pick_fruit(self, req) | Pick a random fruit. | 6.846311 | 6.502358 | 1.052897 |
@wraps(update)
def wrapped_update(self, sensor, reading):
if get_thread_ident() == self._ioloop_thread_id:
update(self, sensor, reading)
else:
self.ioloop.add_callback(update, self, sensor, reading)
return wrapped_update | def update_in_ioloop(update) | Decorator that ensures an update() method is run in the tornado ioloop.
Does this by checking the thread identity. Requires that the object to
which the method is bound has the attributes :attr:`_ioloop_thread_id`
(the result of thread.get_ident() in the ioloop thread) and :attr:`ioloop`
(the ioloop in... | 3.127647 | 2.005549 | 1.559496 |
if strategyName not in cls.SAMPLING_LOOKUP_REV:
raise ValueError("Unknown sampling strategy '%s'. "
"Known strategies are %s."
% (strategyName, cls.SAMPLING_LOOKUP.values()))
strategyType = cls.SAMPLING_LOOKUP_REV[strategyNa... | def get_strategy(cls, strategyName, inform_callback, sensor,
*params, **kwargs) | Factory method to create a strategy object.
Parameters
----------
strategyName : str
Name of strategy.
inform_callback : callable, signature inform_callback(sensor, reading)
Callback to receive inform messages.
sensor : Sensor object
Sensor to... | 1.948221 | 2.032397 | 0.958583 |
strategy = self.get_sampling()
strategy = self.SAMPLING_LOOKUP[strategy]
params = [str(p) for p in self._params]
return strategy, params | def get_sampling_formatted(self) | The current sampling strategy and parameters.
The strategy is returned as a string and the values
in the parameter list are formatted as strings using
the formatter for this sensor type.
Returns
-------
strategy_name : string
KATCP name for the strategy.
... | 7.297851 | 5.420312 | 1.34639 |
s = self._sensor
self.update(s, s.read())
self._sensor.attach(self) | def attach(self) | Attach strategy to its sensor and send initial update. | 11.621017 | 6.02448 | 1.928966 |
if self.OBSERVE_UPDATES:
self.detach()
self.ioloop.add_callback(self.cancel_timeouts) | def cancel(self) | Detach strategy from its sensor and cancel ioloop callbacks. | 10.103631 | 6.46508 | 1.562801 |
def first_run():
self._ioloop_thread_id = get_thread_ident()
if self.OBSERVE_UPDATES:
self.attach()
self.ioloop.add_callback(first_run) | def start(self) | Start operating the strategy.
Subclasses that override start() should call the super method before
it does anything that uses the ioloop. This will attach to the sensor
as an observer if :attr:`OBSERVE_UPDATES` is True, and sets
:attr:`_ioloop_thread_id` using `thread.get_ident()`. | 8.956945 | 3.681215 | 2.433149 |
try:
self._inform_callback(self._sensor, reading)
except Exception:
log.exception('Unhandled exception trying to send {!r} '
'for sensor {!r} of type {!r}'
.format(reading, self._sensor.name, self._sensor.type)) | def inform(self, reading) | Inform strategy creator of the sensor status. | 4.154168 | 4.109275 | 1.010925 |
if not self._ioloop:
raise RuntimeError('Call get_ioloop() or set_ioloop() first')
self._ioloop.add_callback(self._running.set)
if self._ioloop_managed:
self._run_managed_ioloop()
else: # TODO this seems inconsistent with what the docstring ... | def start(self, timeout=None) | Start managed ioloop thread, or do nothing if not managed.
If a timeout is passed, it will block until the the event loop is alive
(or the timeout expires) even if the ioloop is not managed. | 6.662146 | 5.82982 | 1.14277 |
if timeout:
self._running.wait(timeout)
stopped_future = Future()
@gen.coroutine
def _stop():
if callback:
try:
yield gen.maybe_future(callback())
except Exception:
self._logger.exc... | def stop(self, timeout=None, callback=None) | Stop ioloop (if managed) and call callback in ioloop before close.
Parameters
----------
timeout : float or None
Seconds to wait for ioloop to have *started*.
Returns
-------
stopped : thread-safe Future
Resolves when the callback() is done | 4.325816 | 4.313943 | 1.002752 |
if not self._ioloop_managed:
# Do nothing if the loop is not managed
return
try:
self._ioloop_thread.join(timeout)
except AttributeError:
raise RuntimeError('Cannot join if not started') | def join(self, timeout=None) | Join managed ioloop thread, or do nothing if not managed. | 6.413261 | 3.974982 | 1.613406 |
@wraps(callable_)
def decorated(*args, **kwargs):
# Extract timeout from request itself or use default for ioloop wrapper
timeout = kwargs.get('timeout')
return self.call_in_ioloop(callable_, args, kwargs, timeout)
decorated.__doc__ = '\n\n'.join((
,... | def decorate_callable(self, callable_) | Decorate a callable to use call_in_ioloop | 6.599028 | 5.515461 | 1.19646 |
parents = list(self._child_to_parents[sensor])
for parent in parents:
self.recalculate(parent, (sensor,)) | def update(self, sensor, reading) | Update callback used by sensors to notify obervers of changes.
Parameters
----------
sensor : :class:`katcp.Sensor` object
The sensor whose value has changed.
reading : (timestamp, status, value) tuple
Sensor reading as would be returned by sensor.read() | 10.944119 | 14.062197 | 0.778265 |
self._parent_to_children[sensor] = set()
self._child_to_parents[sensor] = set() | def _add_sensor(self, sensor) | Add a new sensor to the tree.
Parameters
----------
sensor : :class:`katcp.Sensor` object
New sensor to add to the tree. | 4.564373 | 5.495491 | 0.830567 |
new_sensors = []
if parent not in self:
self._add_sensor(parent)
new_sensors.append(parent)
for child in children:
if child not in self:
self._add_sensor(child)
new_sensors.append(child)
self._parent_to_chil... | def add_links(self, parent, children) | Create dependency links from parent to child.
Any sensors not in the tree are added. After all dependency links have
been created, the parent is recalculated and the tree attaches to any
sensors it was not yet attached to. Links that already exist are
ignored.
Parameters
... | 2.549267 | 2.489371 | 1.024061 |
old_sensors = []
if parent in self:
for child in children:
if child not in self:
continue
self._parent_to_children[parent].discard(child)
self._child_to_parents[child].discard(parent)
if not self._ch... | def remove_links(self, parent, children) | Remove dependency links from parent to child.
Any sensors that have no dependency links are removed from the tree and
the tree detaches from each sensor removed. After all dependency links
have been removed the parent is recalculated. Links that don't exist
are ignored.
Paramet... | 2.413444 | 2.316703 | 1.041758 |
if parent not in self._parent_to_children:
raise ValueError("Parent sensor %r not in tree." % parent)
return self._parent_to_children[parent].copy() | def children(self, parent) | Return set of children of parent.
Parameters
----------
parent : :class:`katcp.Sensor` object
Parent whose children to return.
Returns
-------
children : set of :class:`katcp.Sensor` objects
The child sensors of parent. | 4.703393 | 3.925156 | 1.198269 |
if child not in self._child_to_parents:
raise ValueError("Child sensor %r not in tree." % child)
return self._child_to_parents[child].copy() | def parents(self, child) | Return set of parents of child.
Parameters
----------
child : :class:`katcp.Sensor` object
Child whose parents to return.
Returns
-------
parents : set of :class:`katcp.Sensor` objects
The parent sensors of child. | 4.752187 | 3.921698 | 1.211768 |
if parent not in self:
if parent.stype != "boolean":
raise ValueError("Parent sensor %r is not boolean" % child)
self._parent_to_not_ok[parent] = set()
if child not in self:
if child.stype != "boolean":
raise ValueError("Child ... | def add(self, parent, child) | Add a pair of boolean sensors.
Parent depends on child.
Parameters
----------
parent : boolean instance of :class:`katcp.Sensor`
The sensor that depends on child.
child : boolean instance of :class:`katcp.Sensor`
The sensor parent depends on. | 4.125157 | 3.763869 | 1.095989 |
self.remove_links(parent, (child,))
if parent not in self and parent in self._parent_to_not_ok:
del self._parent_to_not_ok[parent]
if child not in self and child in self._parent_to_not_ok:
del self._parent_to_not_ok[child] | def remove(self, parent, child) | Remove a dependency between parent and child.
Parameters
----------
parent : boolean instance of :class:`katcp.Sensor`
The sensor that used to depend on child.
child : boolean instance of :class:`katcp.Sensor` or None
The sensor parent used to depend on. | 3.095586 | 3.410023 | 0.90779 |
not_ok = self._parent_to_not_ok[parent]
children = self.children(parent) if parent in self else set()
for sensor in updates:
if sensor not in children or sensor.value():
not_ok.discard(sensor)
else:
not_ok.add(sensor)
paren... | def recalculate(self, parent, updates) | Re-calculate the value of parent sensor.
Parent's value is the boolean AND of all child sensors.
Parameters
----------
parent : :class:`katcp.Sensor` object
The sensor that needs to be updated.
updates : sequence of :class:`katcp.Sensor` objects
The chil... | 4.799489 | 4.427958 | 1.083906 |
if parent in self._aggregates or parent in self._incomplete_aggregates:
raise ValueError("Sensor %r already has an aggregate rule "
"associated" % parent)
self._aggregates[parent] = (rule_function, children)
self.add_links(parent, children) | def add(self, parent, rule_function, children) | Create an aggregation rule.
Parameters
----------
parent : :class:`katcp.Sensor` object
The aggregate sensor.
rule_function : f(parent, children)
Function to update the parent sensor value.
children : sequence of :class:`katcp.Sensor` objects
... | 5.304725 | 4.535813 | 1.16952 |
if parent in self._aggregates or parent in self._incomplete_aggregates:
raise ValueError("Sensor %r already has an aggregate rule"
" associated" % parent)
reg = self._registered_sensors
names = set(name for name in child_names if name not in reg)... | def add_delayed(self, parent, rule_function, child_names) | Create an aggregation rule before child sensors are present.
Parameters
----------
parent : :class:`katcp.Sensor` object
The aggregate sensor.
rule_function : f(parent, children)
Function to update the parent sensor value.
child_names : sequence of str
... | 3.911915 | 3.408548 | 1.147678 |
child_name = self._get_sensor_reference(child)
if child_name in self._registered_sensors:
raise ValueError("Sensor %r already registered with aggregate"
" tree" % child)
self._registered_sensors[child_name] = child
completed = []
... | def register_sensor(self, child) | Register a sensor required by an aggregate sensor registered with
add_delayed.
Parameters
----------
child : :class:`katcp.Sensor` object
A child sensor required by one or more delayed aggregate sensors. | 3.636192 | 3.75152 | 0.969258 |
for child in self._child_to_parents:
if self._get_sensor_reference(child) == reference:
return child | def _child_from_reference(self, reference) | Returns the child sensor from its reference.
Parameters
----------
reference : str
Reference to sensor (typically its name).
Returns
-------
child : :class:`katcp.Sensor` object
A child sensor linked to one or more aggregate sensors. | 8.020343 | 6.85673 | 1.169704 |
if parent not in self._aggregates:
raise ValueError("Sensor %r does not have an aggregate rule "
"associated" % parent)
children = self.children(parent)
try:
self.remove_links(parent, children)
except Exception:
pa... | def remove(self, parent) | Remove an aggregation rule.
Parameters
----------
parent : :class:`katcp.Sensor` object
The aggregate sensor to remove. | 5.40076 | 4.059456 | 1.330415 |
rule_function, children = self._aggregates[parent]
rule_function(parent, children) | def recalculate(self, parent, updates) | Re-calculate the value of parent sensor.
Parent's value is calculated by calling the associate aggregation rule.
Parameters
----------
parent : :class:`katcp.Sensor` object
The sensor that needs to be updated.
updates : sequence of :class:`katcp.Sensor` objects
... | 18.868553 | 17.878021 | 1.055405 |
include_msg = options.pop('include_msg', False)
has_req = options.pop('has_req', True)
major = options.pop('major', DEFAULT_KATCP_MAJOR)
check_req = options.pop('_check_req', True)
if len(options) > 0:
raise TypeError('does not take keyword argument(s) %r.'
% opt... | def request(*types, **options) | Decorator for request handler methods.
The method being decorated should take a req argument followed
by arguments matching the list of types. The decorator will
unpack the request message into the arguments.
Parameters
----------
types : list of kattypes
The types of the request messa... | 2.962966 | 2.645799 | 1.119876 |
major = options.pop('major', DEFAULT_KATCP_MAJOR)
if len(options) > 0:
raise TypeError('return_reply does not take keyword argument(s) %r.'
% options.keys())
# Check that only the last type has multiple=True
if len(types) > 1:
for type_ in types[:-1]:
... | def return_reply(*types, **options) | Decorator for returning replies from request handler methods.
The method being decorated should return an iterable of result
values. If the first value is 'ok', the decorator will check the
remaining values against the specified list of types (if any).
If the first value is 'fail' or 'error', there mus... | 4.838656 | 5.013787 | 0.96507 |
major = options.pop('major', DEFAULT_KATCP_MAJOR)
if len(options) > 0:
raise TypeError('send_reply does not take keyword argument(s) %r.'
% options.keys())
def decorator(handler):
@wraps(handler)
def raw_handler(self, *args):
reply_args = han... | def send_reply(*types, **options) | Decorator for sending replies from request callback methods.
This decorator constructs a reply from a list or tuple returned
from a callback method, but unlike the return_reply decorator it
also sends the reply rather than returning it.
The list/tuple returned from the callback method must have req (a... | 3.712602 | 3.890224 | 0.954341 |
status = arguments[0]
if status == "fail":
return Message.reply(
msgname, *pack_types((Str(), Str()), arguments, major))
if status == "ok":
return Message.reply(
msgname, *pack_types((Str(),) + types, arguments, major))
raise ValueError("First returned value ... | def make_reply(msgname, types, arguments, major) | Helper method for constructing a reply message from a list or tuple.
Parameters
----------
msgname : str
Name of the reply message.
types : list of kattypes
The types of the reply message parameters (in order).
arguments : list of objects
The (unpacked) reply message paramet... | 5.532859 | 6.694808 | 0.82644 |
version_tuple = (major, minor)
def decorator(handler):
handler._minimum_katcp_version = version_tuple
return handler
return decorator | def minimum_katcp_version(major, minor=0) | Decorator; exclude handler if server's protocol version is too low
Useful for including default handler implementations for KATCP features that
are only present in certain KATCP protocol versions
Examples
--------
>>> class MyDevice(DeviceServer):
... '''This device server will expose ?myr... | 5.404253 | 5.551869 | 0.973411 |
if timeout_hint is not None:
timeout_hint = float(timeout_hint)
def decorator(handler):
handler.request_timeout_hint = timeout_hint
return handler
return decorator | def request_timeout_hint(timeout_hint) | Decorator; add recommended client timeout hint to a request for request
Useful for requests that take longer than average to reply. Hint is provided
to clients via ?request-timeout-hint. Note this is only exposed if the
device server sets the protocol version to KATCP v5.1 or higher and enables
the REQ... | 2.76016 | 4.006677 | 0.68889 |
arguments = yield arguments_future
raise gen.Return(make_reply(msgname, types, arguments, major)) | def async_make_reply(msgname, types, arguments_future, major) | Wrap future that will resolve with arguments needed by make_reply(). | 4.002659 | 3.509778 | 1.140431 |
if len(types) > 0:
multiple = types[-1]._multiple
else:
multiple = False
if len(types) < len(args) and not multiple:
raise FailReply("Too many parameters given.")
# Wrap the types in parameter objects
params = []
for i, kattype in enumerate(types):
name = "... | def unpack_types(types, args, argnames, major) | Parse arguments according to types list.
Parameters
----------
types : list of kattypes
The types of the arguments (in order).
args : list of strings
The arguments to parse.
argnames : list of strings
The names of the arguments.
major : integer
Major version of K... | 3.568252 | 3.602418 | 0.990516 |
if len(types) > 0:
multiple = types[-1]._multiple
else:
multiple = False
if len(types) < len(args) and not multiple:
raise ValueError("Too many arguments to pack.")
if len(args) < len(types):
# this passes in None for missing args
retvals = map(lambda ktype... | def pack_types(types, args, major) | Pack arguments according the the types list.
Parameters
----------
types : list of kattypes
The types of the arguments (in order).
args : list of objects
The arguments to format.
major : integer
Major version of KATCP to use when packing types | 2.818601 | 2.806288 | 1.004388 |
if value is None:
value = self.get_default()
if value is None:
raise ValueError("Cannot pack a None value.")
if not nocheck:
self.check(value, major)
return self.encode(value, major) | def pack(self, value, nocheck=False, major=DEFAULT_KATCP_MAJOR) | Return the value formatted as a KATCP parameter.
Parameters
----------
value : object
The value to pack.
nocheck : bool, optional
Whether to check that the value is valid before
packing it.
major : int, optional
Major version of KA... | 3.233964 | 3.707254 | 0.872334 |
if packed_value is None:
value = self.get_default()
else:
try:
value = self.decode(packed_value, major)
except Exception:
raise
if value is not None:
self.check(value, major)
return value | def unpack(self, packed_value, major=DEFAULT_KATCP_MAJOR) | Parse a KATCP parameter into an object.
Parameters
----------
packed_value : str
The unescaped KATCP string to parse into a value.
major : int, optional
Major version of KATCP to use when interpreting types.
Defaults to latest implemented KATCP versio... | 3.019921 | 3.367472 | 0.896792 |
if self._min is not None and value < self._min:
raise ValueError("Integer %d is lower than minimum %d."
% (value, self._min))
if self._max is not None and value > self._max:
raise ValueError("Integer %d is higher than maximum %d."
... | def check(self, value, major) | Check whether the value is between the minimum and maximum.
Raise a ValueError if it is not. | 1.977981 | 1.859249 | 1.06386 |
if self._case_insensitive:
value = value.lower()
values = self._valid_values_lower
caseflag = " (case-insensitive)"
else:
values = self._valid_values
caseflag = ""
if value not in values:
raise ValueError("Discrete ... | def check(self, value, major) | Check whether the value in the set of allowed values.
Raise a ValueError if it is not. | 3.558244 | 3.25071 | 1.094605 |
for v in value:
super(DiscreteMulti, self).check(v, major) | def check(self, value, major) | Check that each item in the value list is in the allowed set. | 9.796257 | 7.857124 | 1.246799 |
# Wrap errors in FailReplies with information identifying the parameter
try:
return self._kattype.unpack(value, self.major)
except ValueError, message:
raise FailReply("Error in parameter %s (%s): %s" %
(self.position, self.name, messa... | def unpack(self, value) | Unpack the parameter using its kattype.
Parameters
----------
packed_value : str
The unescaped KATCP string to unpack.
Returns
-------
value : object
The unpacked value. | 14.075402 | 11.597549 | 1.213653 |
@wraps(fn)
def decorated(*args, **kwargs):
return gen.maybe_future(fn(*args, **kwargs))
return decorated | def return_future(fn) | Decorator that turns a synchronous function into one returning a future.
This should only be applied to non-blocking functions. Will do set_result()
with the return value, or set_exc_info() if an exception is raised. | 2.705869 | 3.480808 | 0.777368 |
if pattern is None:
return False, lambda name: True
if pattern.startswith('/') and pattern.endswith('/'):
name_re = re.compile(pattern[1:-1])
return False, lambda name: name_re.search(name) is not None
return True, lambda name: name == pattern | def construct_name_filter(pattern) | Return a function for filtering sensor names based on a pattern.
Parameters
----------
pattern : None or str
If None, the returned function matches all names.
If pattern starts and ends with '/' the text between the slashes
is used as a regular expression to search the names.
... | 2.518484 | 2.166012 | 1.162728 |
self._server._disconnect_client(self._conn_key, self, reason) | def disconnect(self, reason) | Disconnect this client connection for specified reason | 10.54631 | 10.386719 | 1.015365 |
assert (msg.mtype == Message.INFORM)
return self._send_message(msg) | def inform(self, msg) | Send an inform message to a particular client.
Should only be used for asynchronous informs. Informs
that are part of the response to a request should use
:meth:`reply_inform` so that the message identifier
from the original request can be attached to the
inform.
Parame... | 8.472341 | 10.852576 | 0.780676 |
assert (inform.mtype == Message.INFORM)
assert (inform.name == orig_req.name)
inform.mid = orig_req.mid
return self._send_message(inform) | def reply_inform(self, inform, orig_req) | Send an inform as part of the reply to an earlier request.
Parameters
----------
inform : Message object
The inform message to send.
orig_req : Message object
The request message being replied to. The inform message's
id is overridden with the id from... | 4.796948 | 4.593643 | 1.044258 |
assert (msg.mtype == Message.INFORM)
return self._mass_send_message(msg) | def mass_inform(self, msg) | Send an inform message to all clients.
Parameters
----------
msg : Message object
The inform message to send. | 9.708404 | 10.728312 | 0.904933 |
assert (reply.mtype == Message.REPLY)
assert reply.name == orig_req.name
reply.mid = orig_req.mid
return self._send_message(reply) | def reply(self, reply, orig_req) | Send an asynchronous reply to an earlier request.
Parameters
----------
reply : Message object
The reply message to send.
orig_req : Message object
The request message being replied to. The reply message's
id is overridden with the id from orig_req be... | 5.694724 | 5.687832 | 1.001212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.