_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q238400
RemoteBridgeMixin.begin_script
train
def begin_script(self): """Indicate we are going to start loading a script.""" if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING): return [1] #FIXME: Return correct error here self.remote_bridge.status = BRIDGE_STATUS.WAITING...
python
{ "resource": "" }
q238401
RemoteBridgeMixin.end_script
train
def end_script(self): """Indicate that we have finished receiving a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] #FIXME: State change self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
python
{ "resource": "" }
q238402
RemoteBridgeMixin.trigger_script
train
def trigger_script(self): """Actually process a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,): return [1] #FIXME: State change # This is asynchronous in real life so just cache the error try: self.remote_bridge.parsed_script = UpdateSc...
python
{ "resource": "" }
q238403
RemoteBridgeMixin.reset_script
train
def reset_script(self): """Clear any partially received script.""" self.remote_bridge.status = BRIDGE_STATUS.IDLE self.remote_bridge.error = 0 self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
python
{ "resource": "" }
q238404
render_template_inplace
train
def render_template_inplace(template_path, info, dry_run=False, extra_filters=None, resolver=None): """Render a template file in place. This function expects template path to be a path to a file that ends in .tpl. It will be rendered to a file in the same directory with the .tpl suffix removed. A...
python
{ "resource": "" }
q238405
render_template
train
def render_template(template_name, info, out_path=None): """Render a template using the variables in info. You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package ...
python
{ "resource": "" }
q238406
render_recursive_template
train
def render_recursive_template(template_folder, info, out_folder, preserve=None, dry_run=False): """Copy a directory tree rendering all templates found within. This function inspects all of the files in template_folder recursively. If any file ends .tpl, it is rendered using render_template and the .tpl ...
python
{ "resource": "" }
q238407
_find_monitor
train
def _find_monitor(monitors, handle): """Find all devices and events with a given monitor installed.""" found_devs = set() found_events = set() for conn_string, device in monitors.items(): for event, handles in device.items(): if handle in handles: found_events.add(e...
python
{ "resource": "" }
q238408
_add_monitor
train
def _add_monitor(monitors, handle, callback, devices, events): """Add the given monitor to the listed devices and events.""" for conn_string in devices: data = monitors.get(conn_string) if data is None: data = dict() monitors[conn_string] = data for event in eve...
python
{ "resource": "" }
q238409
_remove_monitor
train
def _remove_monitor(monitors, handle, devices, events): """Remove the given monitor from the listed devices and events.""" empty_devices = [] for conn_string in devices: data = monitors.get(conn_string) if data is None: continue for event in events: event_d...
python
{ "resource": "" }
q238410
BasicNotificationMixin.register_monitor
train
def register_monitor(self, devices, events, callback): """Register a callback when events happen. If this method is called, it is guaranteed to take effect before the next call to ``_notify_event`` after this method returns. This method is safe to call from within a callback that is it...
python
{ "resource": "" }
q238411
BasicNotificationMixin.adjust_monitor
train
def adjust_monitor(self, handle, action, devices, events): """Adjust a previously registered callback. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ events = list(events) devices = list(devices) for event in events: if event not in self.SUPPORTED_EV...
python
{ "resource": "" }
q238412
BasicNotificationMixin.remove_monitor
train
def remove_monitor(self, handle): """Remove a previously registered monitor. See :meth:`AbstractDeviceAdapter.adjust_monitor`. """ action = (handle, "delete", None, None) if self._currently_notifying: self._deferred_adjustments.append(action) else: ...
python
{ "resource": "" }
q238413
BasicNotificationMixin._notify_event_internal
train
async def _notify_event_internal(self, conn_string, name, event): """Notify that an event has occured. This method will send a notification and ensure that all callbacks registered for it have completed by the time it returns. In particular, if the callbacks are awaitable, this method ...
python
{ "resource": "" }
q238414
BasicNotificationMixin.notify_progress
train
def notify_progress(self, conn_string, operation, finished, total, wait=True): """Send a progress event. Progress events can be sent for ``debug`` and ``script`` operations and notify the caller about the progress of these potentially long-running operations. They have two integer prop...
python
{ "resource": "" }
q238415
generate
train
def generate(env): """Add Builders and construction variables for SGI MIPS C++ to an Environment.""" cplusplus.generate(env) env['CXX'] = 'CC' env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std') env['SHCXX'] = '$CXX' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE...
python
{ "resource": "" }
q238416
AsyncPacketBuffer.read_packet
train
def read_packet(self, timeout=3.0): """read one packet, timeout if one packet is not available in the timeout period""" try: return self.queue.get(timeout=timeout) except Empty: raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer")
python
{ "resource": "" }
q238417
generate
train
def generate(env): """Add Builders and construction variables for javac to an Environment.""" java_file = SCons.Tool.CreateJavaFileBuilder(env) java_class = SCons.Tool.CreateJavaClassFileBuilder(env) java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env) java_class.add_emitter(None, emit_java_cl...
python
{ "resource": "" }
q238418
Variables.Add
train
def Add(self, key, help="", default=None, validator=None, converter=None, **kw): """ Add an option. @param key: the name of the variable, or a list or tuple of arguments @param help: optional help text for the options @param default: optional default value @param valida...
python
{ "resource": "" }
q238419
Variables.Update
train
def Update(self, env, args=None): """ Update an environment with the option variables. env - the environment to update. """ values = {} # first set the defaults: for option in self.options: if not option.default is None: values[optio...
python
{ "resource": "" }
q238420
Variables.Save
train
def Save(self, filename, env): """ Saves all the options in the given file. This file can then be used to load the options next run. This can be used to create an option cache file. filename - Name of the file to save into env - the environment get the option values fr...
python
{ "resource": "" }
q238421
Variables.GenerateHelpText
train
def GenerateHelpText(self, env, sort=None): """ Generate the help text for the options. env - an environment that is used to get the current values of the options. cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or ...
python
{ "resource": "" }
q238422
render_tree
train
def render_tree(root, child_func, prune=0, margin=[0], visited=None): """ Render a tree of nodes into an ASCII tree view. :Parameters: - `root`: the root node of the tree - `child_func`: the function called to get the children of a node - `prune`: don't visit the same nod...
python
{ "resource": "" }
q238423
print_tree
train
def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None): """ Print a tree of nodes. This is like render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be printed. :Parameters: - `root` - the ...
python
{ "resource": "" }
q238424
flatten
train
def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be ...
python
{ "resource": "" }
q238425
unique
train
def unique(s): """Return a list of the elements in s, but without duplicates. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], unique("abcabc") some permutation of ["a", "b", "c"], and unique(([1, 2], [2, 3], [1, 2])) some permutation of [[2, 3], [1, 2]]. For best speed, all ...
python
{ "resource": "" }
q238426
make_path_relative
train
def make_path_relative(path): """ makes an absolute path name to a relative pathname. """ if os.path.isabs(path): drive_s,path = os.path.splitdrive(path) import re if not drive_s: path=re.compile("/*(.*)").findall(path)[0] else: path=path[1:] ass...
python
{ "resource": "" }
q238427
RenameFunction
train
def RenameFunction(function, name): """ Returns a function identical to the specified function, but with the specified name. """ return FunctionType(function.__code__, function.__globals__, name, function.__defaults__)
python
{ "resource": "" }
q238428
_create_old_return_value
train
def _create_old_return_value(payload, num_ints, buff): """Parse the response of an RPC call into a dictionary with integer and buffer results""" parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error', 'is_error': False, 'return_value': 0} if buff: parsed['buffer'] ...
python
{ "resource": "" }
q238429
TileBusProxyObject.hardware_version
train
def hardware_version(self): """Return the embedded hardware version string for this tile. The hardware version is an up to 10 byte user readable string that is meant to encode any necessary information about the specific hardware that this tile is running on. For example, if you have m...
python
{ "resource": "" }
q238430
TileBusProxyObject.check_hardware
train
def check_hardware(self, expected): """Make sure the hardware version is what we expect. This convenience function is meant for ensuring that we are talking to a tile that has the correct hardware version. Args: expected (str): The expected hardware string that is compared ...
python
{ "resource": "" }
q238431
TileBusProxyObject.status
train
def status(self): """Query the status of an IOTile including its name and version""" hw_type, name, major, minor, patch, status = self.rpc(0x00, 0x04, result_format="H6sBBBB") status = { 'hw_type': hw_type, 'name': name.decode('utf-8'), 'version': (major, mi...
python
{ "resource": "" }
q238432
TileBusProxyObject.tile_status
train
def tile_status(self): """Get the current status of this tile""" stat = self.status() flags = stat['status'] # FIXME: This needs to stay in sync with lib_common: cdb_status.h status = {} status['debug_mode'] = bool(flags & (1 << 3)) status['configured'] = bool(f...
python
{ "resource": "" }
q238433
StandardDeviceServer.client_event_handler
train
async def client_event_handler(self, client_id, event_tuple, user_data): """Method called to actually send an event to a client. Users of this class should override this method to actually forward device events to their clients. It is called with the client_id passed to (or returned fr...
python
{ "resource": "" }
q238434
StandardDeviceServer.setup_client
train
def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False): """Setup a newly connected client. ``client_id`` must be unique among all connected clients. If it is passed as None, a random client_id will be generated as a string and returned. This method ...
python
{ "resource": "" }
q238435
StandardDeviceServer.stop
train
async def stop(self): """Stop the server and teardown any remaining clients. If your subclass overrides this method, make sure to call super().stop() to ensure that all devices with open connections from thie server are properly closed. See :meth:`AbstractDeviceServer.stop`. ...
python
{ "resource": "" }
q238436
StandardDeviceServer.teardown_client
train
async def teardown_client(self, client_id): """Release all resources held by a client. This method must be called and awaited whenever a client is disconnected. It ensures that all of the client's resources are properly released and any devices they have connected to are discon...
python
{ "resource": "" }
q238437
StandardDeviceServer.connect
train
async def connect(self, client_id, conn_string): """Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to ...
python
{ "resource": "" }
q238438
StandardDeviceServer.disconnect
train
async def disconnect(self, client_id, conn_string): """Disconnect from a device on behalf of a client. See :meth:`AbstractDeviceAdapter.disconnect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be ...
python
{ "resource": "" }
q238439
StandardDeviceServer.open_interface
train
async def open_interface(self, client_id, conn_string, interface): """Open a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.open_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will ...
python
{ "resource": "" }
q238440
StandardDeviceServer.close_interface
train
async def close_interface(self, client_id, conn_string, interface): """Close a device interface on behalf of a client. See :meth:`AbstractDeviceAdapter.close_interface`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that wi...
python
{ "resource": "" }
q238441
StandardDeviceServer.send_rpc
train
async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout): """Send an RPC on behalf of a client. See :meth:`AbstractDeviceAdapter.send_rpc`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will ...
python
{ "resource": "" }
q238442
StandardDeviceServer.send_script
train
async def send_script(self, client_id, conn_string, script): """Send a script to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be ...
python
{ "resource": "" }
q238443
StandardDeviceServer.debug
train
async def debug(self, client_id, conn_string, command, args): """Send a debug command to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.send_script`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will...
python
{ "resource": "" }
q238444
TileInfo.registration_packet
train
def registration_packet(self): """Serialize this into a tuple suitable for returning from an RPC. Returns: tuple: The serialized values. """ return (self.hw_type, self.api_info[0], self.api_info[1], self.name, self.fw_info[0], self.fw_info[1], self.fw_info[2], ...
python
{ "resource": "" }
q238445
TileManagerState.clear_to_reset
train
def clear_to_reset(self, config_vars): """Clear to the state immediately after a reset.""" super(TileManagerState, self).clear_to_reset(config_vars) self.registered_tiles = self.registered_tiles[:1] self.safe_mode = False self.debug_mode = False
python
{ "resource": "" }
q238446
TileManagerState.insert_tile
train
def insert_tile(self, tile_info): """Add or replace an entry in the tile cache. Args: tile_info (TileInfo): The newly registered tile. """ for i, tile in enumerate(self.registered_tiles): if tile.slot == tile_info.slot: self.registered_tiles[i] =...
python
{ "resource": "" }
q238447
TileManagerMixin.register_tile
train
def register_tile(self, hw_type, api_major, api_minor, name, fw_major, fw_minor, fw_patch, exec_major, exec_minor, exec_patch, slot, unique_id): """Register a tile with this controller. This function adds the tile immediately to its internal cache of registered tiles and queues RPCs to send all...
python
{ "resource": "" }
q238448
TileManagerMixin.describe_tile
train
def describe_tile(self, index): """Get the registration information for the tile at the given index.""" if index >= len(self.tile_manager.registered_tiles): tile = TileInfo.CreateInvalid() else: tile = self.tile_manager.registered_tiles[index] return tile.regist...
python
{ "resource": "" }
q238449
UpdateScript.ParseHeader
train
def ParseHeader(cls, script_data): """Parse a script integrity header. This function makes sure any integrity hashes are correctly parsed and returns a ScriptHeader structure containing the information that it was able to parse out. Args: script_data (bytearray): Th...
python
{ "resource": "" }
q238450
UpdateScript.FromBinary
train
def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False): """Parse a binary update script. Args: script_data (bytearray): The binary data containing the script. allow_unknown (bool): Allow the script to contain unknown records so long as they have co...
python
{ "resource": "" }
q238451
UpdateScript.encode
train
def encode(self): """Encode this record into a binary blob. This binary blob could be parsed via a call to FromBinary(). Returns: bytearray: The binary encoded script. """ blob = bytearray() for record in self.records: blob += record.encode() ...
python
{ "resource": "" }
q238452
BaseRunnable.create_worker
train
def create_worker(self, func, interval, *args, **kwargs): """Spawn a worker thread running func. The worker will be automatically be started when start() is called and terminated when stop() is called on this object. This must be called only from the main thread, not from a worker threa...
python
{ "resource": "" }
q238453
BaseRunnable.stop_workers
train
def stop_workers(self): """Synchronously stop any potential workers.""" self._started = False for worker in self._workers: worker.stop()
python
{ "resource": "" }
q238454
BaseRunnable.stop_workers_async
train
def stop_workers_async(self): """Signal that all workers should stop without waiting.""" self._started = False for worker in self._workers: worker.signal_stop()
python
{ "resource": "" }
q238455
_download_ota_script
train
def _download_ota_script(script_url): """Download the script from the cloud service and store to temporary file location""" try: blob = requests.get(script_url, stream=True) return blob.content except Exception as e: iprint("Failed to download OTA script") iprint(e) ...
python
{ "resource": "" }
q238456
rename_module
train
def rename_module(new, old): """ Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x. """ try: sys.modules[new] = imp.load_module(old, *imp.find_module(old)) return True except ImportError: return False
python
{ "resource": "" }
q238457
JLinkAdapter._parse_conn_string
train
def _parse_conn_string(self, conn_string): """Parse a connection string passed from 'debug -c' or 'connect_direct' Returns True if any settings changed in the debug port, which would require a jlink disconnection """ disconnection_required = False """If device not in con...
python
{ "resource": "" }
q238458
JLinkAdapter._try_connect
train
def _try_connect(self, connection_string): """If the connecton string settings are different, try and connect to an attached device""" if self._parse_conn_string(connection_string): self._trigger_callback('on_disconnect', self.id, self._connection_id) self.stop_sync() ...
python
{ "resource": "" }
q238459
JLinkAdapter.stop_sync
train
def stop_sync(self): """Synchronously stop this adapter and release all resources.""" if self._control_thread is not None and self._control_thread.is_alive(): self._control_thread.stop() self._control_thread.join() if self.jlink is not None: self.jlink.close...
python
{ "resource": "" }
q238460
JLinkAdapter.probe_async
train
def probe_async(self, callback): """Send advertisements for all connected devices. Args: callback (callable): A callback for when the probe operation has completed. callback should have signature callback(adapter_id, success, failure_reason) where: succes...
python
{ "resource": "" }
q238461
JLinkAdapter._open_debug_interface
train
def _open_debug_interface(self, conn_id, callback, connection_string=None): """Enable debug interface for this IOTile device Args: conn_id (int): the unique identifier for the connection callback (callback): Callback to be called when this command finishes callba...
python
{ "resource": "" }
q238462
EmulatedPeripheralTile._reset_vector
train
async def _reset_vector(self): """Main background task for the tile executive. The tile executive is in charge registering the tile with the controller and then handing control over to the tile's application firmware after proper configuration values have been received. """ ...
python
{ "resource": "" }
q238463
EmulatedPeripheralTile._handle_reset
train
def _handle_reset(self): """Reset this tile. This process needs to trigger the peripheral tile to reregister itself with the controller and get new configuration variables. It also needs to clear app_running. """ self._registered.clear() self._start_received.cl...
python
{ "resource": "" }
q238464
IOTileGateway.start
train
async def start(self): """Start the gateway.""" self._logger.info("Starting all device adapters") await self.device_manager.start() self._logger.info("Starting all servers") for server in self.servers: await server.start()
python
{ "resource": "" }
q238465
IOTileGateway.stop
train
async def stop(self): """Stop the gateway manager and synchronously wait for it to stop.""" self._logger.info("Stopping all servers") for server in self.servers: await server.stop() self._logger.info("Stopping all device adapters") await self.device_manager.stop()
python
{ "resource": "" }
q238466
main
train
def main(argv=None): """Main entry point for iotile-ship recipe runner. This is the iotile-ship command line program. Args: argv (list of str): An optional set of command line parameters. If not passed, these are taken from sys.argv. """ if argv is None: a...
python
{ "resource": "" }
q238467
subst_dict
train
def subst_dict(target, source): """Create a dictionary for substitution of special construction variables. This translates the following special arguments: target - the target (object or array of objects), used to generate the TARGET and TARGETS construction variables so...
python
{ "resource": "" }
q238468
CmdStringHolder.escape
train
def escape(self, escape_func, quote_func=quote_spaces): """Escape the string with the supplied function. The function is expected to take an arbitrary string, then return it with all special characters escaped and ready for passing to the command interpreter. After calling this...
python
{ "resource": "" }
q238469
indent_list
train
def indent_list(inlist, level): """Join a list of strings, one per line with 'level' spaces before each one""" indent = ' '*level joinstr = '\n' + indent retval = joinstr.join(inlist) return indent + retval
python
{ "resource": "" }
q238470
generate
train
def generate(env): """Add Builders and construction variables for gfortran to an Environment.""" fortran.generate(env) for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03', 'F08']: env['%s' % dialect] = 'gfortran' env['SH%s' % dialect] = '$%s' % dialect if env['PLATFORM'] in ['...
python
{ "resource": "" }
q238471
AWSIOTGatewayAgent._extract_device_uuid
train
def _extract_device_uuid(cls, slug): """Turn a string slug into a UUID """ if len(slug) != 22: raise ArgumentError("Invalid device slug", slug=slug) hexdigits = slug[3:] hexdigits = hexdigits.replace('-', '') try: rawbytes = binascii.unhexlify(h...
python
{ "resource": "" }
q238472
AWSIOTGatewayAgent.start
train
def start(self): """Start this gateway agent.""" self._prepare() self._disconnector = tornado.ioloop.PeriodicCallback(self._disconnect_hanging_devices, 1000, self._loop) self._disconnector.start()
python
{ "resource": "" }
q238473
AWSIOTGatewayAgent.stop
train
def stop(self): """Stop this gateway agent.""" if self._disconnector: self._disconnector.stop() self.client.disconnect()
python
{ "resource": "" }
q238474
AWSIOTGatewayAgent._validate_connection
train
def _validate_connection(self, action, uuid, key): """Validate that a message received for a device has the right key If this action is valid the corresponding internal connection id to be used with the DeviceManager is returned, otherwise None is returned and an invalid message status ...
python
{ "resource": "" }
q238475
AWSIOTGatewayAgent._publish_status
train
def _publish_status(self, slug, data): """Publish a status message for a device Args: slug (string): The device slug that we are publishing on behalf of data (dict): The status message data to be sent back to the caller """ status_topic = self.topics.prefix + 'd...
python
{ "resource": "" }
q238476
AWSIOTGatewayAgent._publish_response
train
def _publish_response(self, slug, message): """Publish a response message for a device Args: slug (string): The device slug that we are publishing on behalf of message (dict): A set of key value pairs that are used to create the message that is sent. """ ...
python
{ "resource": "" }
q238477
AWSIOTGatewayAgent._on_action
train
def _on_action(self, sequence, topic, message): """Process a command action that we received on behalf of a device. Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message its...
python
{ "resource": "" }
q238478
AWSIOTGatewayAgent._on_connect
train
def _on_connect(self, sequence, topic, message): """Process a request to connect to an IOTile device A connection message triggers an attempt to connect to a device, any error checking is done by the DeviceManager that is actually managing the devices. A disconnection message i...
python
{ "resource": "" }
q238479
AWSIOTGatewayAgent._send_rpc
train
def _send_rpc(self, client, uuid, address, rpc, payload, timeout, key): """Send an RPC to a connected device Args: client (string): The client that sent the rpc request uuid (int): The id of the device we're opening the interface on address (int): The address of the ...
python
{ "resource": "" }
q238480
AWSIOTGatewayAgent._send_script
train
def _send_script(self, client, uuid, chunk, key, chunk_status): """Send a script to the connected device. Args: client (string): The client that sent the rpc request uuid (int): The id of the device we're opening the interface on chunk (bytes): The binary script to s...
python
{ "resource": "" }
q238481
AWSIOTGatewayAgent._open_interface
train
def _open_interface(self, client, uuid, iface, key): """Open an interface on a connected device. Args: client (string): The client id who is requesting this operation uuid (int): The id of the device we're opening the interface on iface (string): The name of the inte...
python
{ "resource": "" }
q238482
AWSIOTGatewayAgent._disconnect_hanging_devices
train
def _disconnect_hanging_devices(self): """Periodic callback that checks for devices that haven't been used and disconnects them.""" now = monotonic() for uuid, data in self._connections.items(): if (now - data['last_touch']) > self.client_timeout: self._logger.info("...
python
{ "resource": "" }
q238483
AWSIOTGatewayAgent._disconnect_from_device
train
def _disconnect_from_device(self, uuid, key, client, unsolicited=False): """Disconnect from a device that we have previously connected to. Args: uuid (int): The unique id of the device key (string): A 64 byte string used to secure this connection client (string): The...
python
{ "resource": "" }
q238484
AWSIOTGatewayAgent._notify_report
train
def _notify_report(self, device_uuid, event_name, report): """Notify that a report has been received from a device. This routine is called synchronously in the event loop by the DeviceManager """ if device_uuid not in self._connections: self._logger.debug("Dropping report f...
python
{ "resource": "" }
q238485
AWSIOTGatewayAgent._notify_trace
train
def _notify_trace(self, device_uuid, event_name, trace): """Notify that we have received tracing data from a device. This routine is called synchronously in the event loop by the DeviceManager """ if device_uuid not in self._connections: self._logger.debug("Dropping trace d...
python
{ "resource": "" }
q238486
AWSIOTGatewayAgent._send_accum_trace
train
def _send_accum_trace(self, device_uuid): """Send whatever accumulated tracing data we have for the device.""" if device_uuid not in self._connections: self._logger.debug("Dropping trace data for device without an active connection, uuid=0x%X", device_uuid) return conn_...
python
{ "resource": "" }
q238487
AWSIOTGatewayAgent._on_scan_request
train
def _on_scan_request(self, sequence, topic, message): """Process a request for scanning information Args: sequence (int:) The sequence number of the packet received topic (string): The topic this message was received on message_type (string): The type of the packet r...
python
{ "resource": "" }
q238488
AWSIOTGatewayAgent._publish_scan_response
train
def _publish_scan_response(self, client): """Publish a scan response message The message contains all of the devices that are currently known to this agent. Connection strings for direct connections are translated to what is appropriate for this agent. Args: client...
python
{ "resource": "" }
q238489
_versioned_lib_suffix
train
def _versioned_lib_suffix(env, suffix, version): """For suffix='.so' and version='0.1.2' it returns '.so.0.1.2'""" Verbose = False if Verbose: print("_versioned_lib_suffix: suffix={:r}".format(suffix)) print("_versioned_lib_suffix: version={:r}".format(version)) if not suffix.endswith(ve...
python
{ "resource": "" }
q238490
_setup_versioned_lib_variables
train
def _setup_versioned_lib_variables(env, **kw): """ Setup all variables required by the versioning machinery """ tool = None try: tool = kw['tool'] except KeyError: pass use_soname = False try: use_soname = kw['use_soname'] except KeyError: pass # The $_SHLIBVERSIONFLAGS define...
python
{ "resource": "" }
q238491
main
train
def main(argv=None, loop=SharedLoop, max_time=None): """Main entry point for iotile-gateway.""" should_raise = argv is not None if argv is None: argv = sys.argv[1:] parser = build_parser() cmd_args = parser.parse_args(argv) configure_logging(cmd_args.verbose) logger = logging.getL...
python
{ "resource": "" }
q238492
_TimeAnchor.copy
train
def copy(self): """Return a copy of this _TimeAnchor.""" return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact)
python
{ "resource": "" }
q238493
UTCAssigner.anchor_stream
train
def anchor_stream(self, stream_id, converter="rtc"): """Mark a stream as containing anchor points.""" if isinstance(converter, str): converter = self._known_converters.get(converter) if converter is None: raise ArgumentError("Unknown anchor converter string: %s"...
python
{ "resource": "" }
q238494
UTCAssigner.id_range
train
def id_range(self): """Get the range of archor reading_ids. Returns: (int, int): The lowest and highest reading ids. If no reading ids have been loaded, (0, 0) is returned. """ if len(self._anchor_points) == 0: return (0, 0) return (self._a...
python
{ "resource": "" }
q238495
UTCAssigner._convert_epoch_anchor
train
def _convert_epoch_anchor(cls, reading): """Convert a reading containing an epoch timestamp to datetime.""" delta = datetime.timedelta(seconds=reading.value) return cls._EpochReference + delta
python
{ "resource": "" }
q238496
UTCAssigner.add_point
train
def add_point(self, reading_id, uptime=None, utc=None, is_break=False): """Add a time point that could be used as a UTC reference.""" if reading_id == 0: return if uptime is None and utc is None: return if uptime is not None and uptime & (1 << 31): ...
python
{ "resource": "" }
q238497
UTCAssigner.add_reading
train
def add_reading(self, reading): """Add an IOTileReading.""" is_break = False utc = None if reading.stream in self._break_streams: is_break = True if reading.stream in self._anchor_streams: utc = self._anchor_streams[reading.stream](reading) sel...
python
{ "resource": "" }
q238498
UTCAssigner.add_report
train
def add_report(self, report, ignore_errors=False): """Add all anchors from a report.""" if not isinstance(report, SignedListReport): if ignore_errors: return raise ArgumentError("You can only add SignedListReports to a UTCAssigner", report=report) for r...
python
{ "resource": "" }
q238499
UTCAssigner.assign_utc
train
def assign_utc(self, reading_id, uptime=None, prefer="before"): """Assign a utc datetime to a reading id. This method will return an object with assignment information or None if a utc value cannot be assigned. The assignment object returned contains a utc property that has the asssign...
python
{ "resource": "" }