Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def notify_event_nowait(self, conn_string, name, event):
if self._loop.stopping:
self._logger.debug("Ignoring notification %s from %s because loop is shutting down", name, conn_string)
return
self._loop.log_coroutine(self._n... | [
"Notify an event.\n\n This will move the notification to the background event loop and\n return immediately. It is useful for situations where you cannot\n await notify_event but keep in mind that it prevents back-pressure\n when you are notifying too fast so should be used sparingly.\n... |
Please provide a description of the function:def notify_progress(self, conn_string, operation, finished, total, wait=True):
if operation not in self.PROGRESS_OPERATIONS:
raise ArgumentError("Invalid operation for progress event: {}".format(operation))
event = dict(operation=operat... | [
"Send a progress event.\n\n Progress events can be sent for ``debug`` and ``script`` operations and\n notify the caller about the progress of these potentially long-running\n operations. They have two integer properties that specify what fraction\n of the operation has been completed.\n... |
Please provide a description of the function:def generate(env):
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_THE_SAME'] = 1 | [
"Add Builders and construction variables for SGI MIPS C++ to an Environment."
] |
Please provide a description of the function:def read_packet(self, timeout=3.0):
try:
return self.queue.get(timeout=timeout)
except Empty:
raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer") | [
"read one packet, timeout if one packet is not available in the timeout period"
] |
Please provide a description of the function:def modify_dict(data, key, value, create_if_missing=False):
data_copy = copy.deepcopy(data)
key_copy = copy.deepcopy(key)
delver = data_copy
current_key = key_copy
last_key = "Root"
# Dig through the json, setting delver to the dict that contai... | [
" Change (or add) a json key/value pair.\n\n Args:\n data (dict): The original data. This will not be modified.\n key (list): A list of keys and subkeys specifing the key to change (list can be one)\n value (str): The value to change for the above key\n create_if_missing (bool): Set t... |
Please provide a description of the function:def emit_java_classes(target, source, env):
java_suffix = env.get('JAVASUFFIX', '.java')
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
target[0].must_be_same(SCons.Node.FS.Dir)
classdir = target[0]
s = source[0].rentry().disambiguate()
if... | [
"Create and return lists of source java files\n and their corresponding target class files.\n "
] |
Please provide a description of the function:def Java(env, target, source, *args, **kw):
if not SCons.Util.is_List(target):
target = [target]
if not SCons.Util.is_List(source):
source = [source]
# Pad the target list with repetitions of the last element in the
# list so we have a t... | [
"\n A pseudo-Builder wrapper around the separate JavaClass{File,Dir}\n Builders.\n "
] |
Please provide a description of the function:def generate(env):
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_classes)
java_class.add_emi... | [
"Add Builders and construction variables for javac to an Environment."
] |
Please provide a description of the function:def Add(self, key, help="", default=None, validator=None, converter=None, **kw):
if SCons.Util.is_List(key) or isinstance(key, tuple):
self._do_add(*key)
return
if not SCons.Util.is_String(key) or \
not SCons.Env... | [
"\n Add an option.\n\n\n @param key: the name of the variable, or a list or tuple of arguments\n @param help: optional help text for the options\n @param default: optional default value\n @param validator: optional function that is called to validate the option's value\n @t... |
Please provide a description of the function:def Update(self, env, args=None):
values = {}
# first set the defaults:
for option in self.options:
if not option.default is None:
values[option.key] = option.default
# next set the value specified in th... | [
"\n Update an environment with the option variables.\n\n env - the environment to update.\n "
] |
Please provide a description of the function:def Save(self, filename, env):
# Create the file and write out the header
try:
fh = open(filename, 'w')
try:
# Make an assignment in the file for each option
# within the environment that was ... | [
"\n Saves all the options in the given file. This file can\n then be used to load the options next run. This can be used\n to create an option cache file.\n\n filename - Name of the file to save into\n env - the environment get the option values from\n "
] |
Please provide a description of the function:def GenerateHelpText(self, env, sort=None):
if callable(sort):
options = sorted(self.options, key=cmp_to_key(lambda x,y: sort(x.key,y.key)))
elif sort is True:
options = sorted(self.options, key=lambda x: x.key)
else:... | [
"\n Generate the help text for the options.\n\n env - an environment that is used to get the current values\n of the options.\n cmp - Either a function as follows: The specific sort function should take two arguments and return -1, 0 or 1 \n or a boolean to indicate if... |
Please provide a description of the function:def splitext(path):
"Same as os.path.splitext() but faster."
sep = rightmost_separator(path, os.sep)
dot = path.rfind('.')
# An ext is only real if it has at least one non-digit char
if dot > sep and not containsOnly(path[dot:], "0123456789."):
re... | [] |
Please provide a description of the function:def updrive(path):
drive, rest = os.path.splitdrive(path)
if drive:
path = drive.upper() + rest
return path | [
"\n Make the drive letter (if any) upper case.\n This is useful because Windows is inconsistent on the case\n of the drive letter, which can cause inconsistencies when\n calculating command signatures.\n "
] |
Please provide a description of the function:def get_environment_var(varstr):
mo=_get_env_var.match(to_String(varstr))
if mo:
var = mo.group(1)
if var[0] == '{':
return var[1:-1]
else:
return var
else:
return None | [
"Given a string, first determine if it looks like a reference\n to a single environment variable, like \"$FOO\" or \"${FOO}\".\n If so, return that variable with no decorations (\"FOO\").\n If not, return None."
] |
Please provide a description of the function:def render_tree(root, child_func, prune=0, margin=[0], visited=None):
rname = str(root)
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
children = child_func(root)
retval = ""
for pipe in margin[:-1]:
... | [
"\n Render a tree of nodes into an ASCII tree view.\n\n :Parameters:\n - `root`: the root node of the tree\n - `child_func`: the function called to get the children of a node\n - `prune`: don't visit the same node twice\n - `margin`: the format of the left margin to ... |
Please provide a description of the function:def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
rname = str(root)
# Initialize 'visited' dict, if required
if visited is None:
visited = {}
if showtags:
if showtags == 2:
legend = (' E ... | [
"\n Print a tree of nodes. This is like render_tree, except it prints\n lines directly instead of creating a string representation in memory,\n so that huge trees can be printed.\n\n :Parameters:\n - `root` - the root node of the tree\n - `child_func` - the function called to get th... |
Please provide a description of the function:def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
return [obj]
result = []
for item in obj:
... | [
"Flatten a sequence to a non-nested list.\n\n Flatten() converts either a single scalar or a nested sequence\n to a non-nested list. Note that flatten() considers strings\n to be scalars instead of sequences like Python would.\n "
] |
Please provide a description of the function:def PrependPath(oldpath, newpath, sep = os.pathsep,
delete_existing=1, canonicalize=None):
orig = oldpath
is_list = 1
paths = orig
if not is_List(orig) and not is_Tuple(orig):
paths = paths.split(sep)
is_list = 0
if ... | [
"This prepends newpath elements to the given oldpath. Will only\n add any particular path once (leaving the first one it encounters\n and ignoring the rest, to preserve path order), and will\n os.path.normpath and os.path.normcase all paths to help assure\n this. This can also handle the case where th... |
Please provide a description of the function:def AddPathIfNotExists(env_dict, key, path, sep=os.pathsep):
try:
is_list = 1
paths = env_dict[key]
if not is_List(env_dict[key]):
paths = paths.split(sep)
is_list = 0
if os.path.normcase(path) not in list(map(... | [
"This function will take 'key' out of the dictionary\n 'env_dict', then add the path 'path' to that key if it is not\n already there. This treats the value of env_dict[key] as if it\n has a similar format to the PATH variable...a list of paths\n separated by tokens. The 'path' will get added to the li... |
Please provide a description of the function:def unique(s):
n = len(s)
if n == 0:
return []
# Try using a dict first, as that's the fastest and will usually
# work. If it doesn't work, it will usually fail quickly, so it
# usually doesn't cost much to *try* it. It requires that all ... | [
"Return a list of the elements in s, but without duplicates.\n\n For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],\n unique(\"abcabc\") some permutation of [\"a\", \"b\", \"c\"], and\n unique(([1, 2], [2, 3], [1, 2])) some permutation of\n [[2, 3], [1, 2]].\n\n For best speed, all se... |
Please provide a description of the function:def make_path_relative(path):
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:]
assert( not os.path.i... | [
" makes an absolute path name to a relative pathname.\n "
] |
Please provide a description of the function:def AddMethod(obj, function, name=None):
if name is None:
name = function.__name__
else:
function = RenameFunction(function, name)
# Note the Python version checks - WLB
# Python 3.3 dropped the 3rd parameter from types.MethodType
if... | [
"\n Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class.\n If name is ommited the name of the specified function\n is used by default.\n\n Example::\n\n a = A()\n def f(self, x, y):\n self.z = x + y\n AddMethod(f, A, ... |
Please provide a description of the function:def RenameFunction(function, name):
return FunctionType(function.__code__,
function.__globals__,
name,
function.__defaults__) | [
"\n Returns a function identical to the specified function, but with\n the specified name.\n "
] |
Please provide a description of the function:def _create_old_return_value(payload, num_ints, buff):
parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error',
'is_error': False, 'return_value': 0}
if buff:
parsed['buffer'] = bytearray(payload[-1])
return parsed | [
"Parse the response of an RPC call into a dictionary with integer and buffer results"
] |
Please provide a description of the function:def rpc(self, feature, cmd, *args, **kw):
rpc_id = (feature << 8 | cmd)
result_format = _create_resp_format(kw.get('result_type'), kw.get('result_format'))
arg_format = kw.get('arg_format')
if arg_format is None:
arg_for... | [
"Send an RPC call to this module, interpret the return value\n according to the result_type kw argument. Unless raise keyword\n is passed with value False, raise an RPCException if the command\n is not successful.\n "
] |
Please provide a description of the function:def rpc_v2(self, cmd, arg_format, result_format, *args, **kw):
if args:
packed_args = pack_rpc_payload(arg_format, list(args))
elif arg_format == "":
packed_args = b''
else:
raise RPCInvalidArgumentsError("... | [
"Send an RPC call to this module, interpret the return value\n according to the result_type kw argument. Unless raise keyword\n is passed with value False, raise an RPCException if the command\n is not successful.\n\n v2 enforces the use of arg_format and result_format\n v2 combi... |
Please provide a description of the function:def hardware_version(self):
res = self.rpc(0x00, 0x02, result_type=(0, True))
# Result is a string but with zero appended to the end to make it a fixed 10 byte size
binary_version = res['buffer']
ver = ""
for x in binary_ve... | [
"Return the embedded hardware version string for this tile.\n\n The hardware version is an up to 10 byte user readable string that is\n meant to encode any necessary information about the specific hardware\n that this tile is running on. For example, if you have multiple\n assembly vari... |
Please provide a description of the function:def check_hardware(self, expected):
if len(expected) < 10:
expected += '\0'*(10 - len(expected))
err, = self.rpc(0x00, 0x03, expected, result_format="L")
if err == 0:
return True
return False | [
"Make sure the hardware version is what we expect.\n\n This convenience function is meant for ensuring that we are talking to\n a tile that has the correct hardware version.\n\n Args:\n expected (str): The expected hardware string that is compared\n against what is rep... |
Please provide a description of the function:def status(self):
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, minor, patch),
... | [
"Query the status of an IOTile including its name and version"
] |
Please provide a description of the function:def tile_status(self):
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'] = bo... | [
"Get the current status of this tile"
] |
Please provide a description of the function:async def client_event_handler(self, client_id, event_tuple, user_data):
conn_string, event_name, _event = event_tuple
self._logger.debug("Ignoring event %s from device %s forwarded for client %s",
event_name, conn_string,... | [
"Method called to actually send an event to a client.\n\n Users of this class should override this method to actually forward\n device events to their clients. It is called with the client_id\n passed to (or returned from) :meth:`setup_client` as well as the\n user_data object that was ... |
Please provide a description of the function:def setup_client(self, client_id=None, user_data=None, scan=True, broadcast=False):
if client_id is None:
client_id = str(uuid.uuid4())
if client_id in self._clients:
raise ArgumentError("Duplicate client_id: {}".format(cli... | [
"Setup a newly connected client.\n\n ``client_id`` must be unique among all connected clients. If it is\n passed as None, a random client_id will be generated as a string and\n returned.\n\n This method reserves internal resources for tracking what devices this\n client has conne... |
Please provide a description of the function:async def stop(self):
clients = list(self._clients)
for client in clients:
self._logger.info("Tearing down client %s at server stop()", client)
await self.teardown_client(client) | [
"Stop the server and teardown any remaining clients.\n\n If your subclass overrides this method, make sure to call\n super().stop() to ensure that all devices with open connections from\n thie server are properly closed.\n\n See :meth:`AbstractDeviceServer.stop`.\n "
] |
Please provide a description of the function:async def teardown_client(self, client_id):
client_info = self._client_info(client_id)
self.adapter.remove_monitor(client_info['monitor'])
conns = client_info['connections']
for conn_string, conn_id in conns.items():
tr... | [
"Release all resources held by a client.\n\n This method must be called and awaited whenever a client is\n disconnected. It ensures that all of the client's resources are\n properly released and any devices they have connected to are\n disconnected cleanly.\n\n Args:\n ... |
Please provide a description of the function:async def connect(self, client_id, conn_string):
conn_id = self.adapter.unique_conn_id()
self._client_info(client_id)
await self.adapter.connect(conn_id, conn_string)
self._hook_connect(conn_string, conn_id, client_id) | [
"Connect to a device on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.connect`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter to connect.\n\n ... |
Please provide a description of the function:async def disconnect(self, client_id, conn_string):
conn_id = self._client_connection(client_id, conn_string)
try:
await self.adapter.disconnect(conn_id)
finally:
self._hook_disconnect(conn_string, client_id) | [
"Disconnect from a device on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.disconnect`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter to connect... |
Please provide a description of the function:async def open_interface(self, client_id, conn_string, interface):
conn_id = self._client_connection(client_id, conn_string)
# Hook first so there is no race on getting the first event
self._hook_open_interface(conn_string, interface, clien... | [
"Open a device interface on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.open_interface`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter.\n ... |
Please provide a description of the function:async def close_interface(self, client_id, conn_string, interface):
conn_id = self._client_connection(client_id, conn_string)
await self.adapter.close_interface(conn_id, interface)
self._hook_close_interface(conn_string, interface, client_i... | [
"Close a device interface on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.close_interface`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter.\n ... |
Please provide a description of the function:async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout):
conn_id = self._client_connection(client_id, conn_string)
return await self.adapter.send_rpc(conn_id, address, rpc_id, payload, timeout) | [
"Send an RPC on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.send_rpc`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter to connect.\n ... |
Please provide a description of the function:async def send_script(self, client_id, conn_string, script):
conn_id = self._client_connection(client_id, conn_string)
await self.adapter.send_script(conn_id, script) | [
"Send a script to a device on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.send_script`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter.\n ... |
Please provide a description of the function:async def debug(self, client_id, conn_string, command, args):
conn_id = self._client_info(client_id, 'connections')[conn_string]
return await self.adapter.debug(conn_id, command, args) | [
"Send a debug command to a device on behalf of a client.\n\n See :meth:`AbstractDeviceAdapter.send_script`.\n\n Args:\n client_id (str): The client we are working for.\n conn_string (str): A connection string that will be\n passed to the underlying device adapter.\... |
Please provide a description of the function:def registration_packet(self):
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],
self.exec_info[0], self.exec_info[0], self.exec_info[0], self.slot, self.unique_id) | [
"Serialize this into a tuple suitable for returning from an RPC.\n\n Returns:\n tuple: The serialized values.\n "
] |
Please provide a description of the function:def clear_to_reset(self, config_vars):
super(TileManagerState, self).clear_to_reset(config_vars)
self.registered_tiles = self.registered_tiles[:1]
self.safe_mode = False
self.debug_mode = False | [
"Clear to the state immediately after a reset."
] |
Please provide a description of the function:def insert_tile(self, tile_info):
for i, tile in enumerate(self.registered_tiles):
if tile.slot == tile_info.slot:
self.registered_tiles[i] = tile_info
return
self.registered_tiles.append(tile_info) | [
"Add or replace an entry in the tile cache.\n\n Args:\n tile_info (TileInfo): The newly registered tile.\n "
] |
Please provide a description of the function: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):
api_info = (api_major, api_minor)
fw_info = (fw_major, fw_minor, fw_patch)
exec_info = (exec_maj... | [
"Register a tile with this controller.\n\n This function adds the tile immediately to its internal cache of registered tiles\n and queues RPCs to send all config variables and start tile rpcs back to the tile.\n "
] |
Please provide a description of the function:def describe_tile(self, index):
if index >= len(self.tile_manager.registered_tiles):
tile = TileInfo.CreateInvalid()
else:
tile = self.tile_manager.registered_tiles[index]
return tile.registration_packet() | [
"Get the registration information for the tile at the given index."
] |
Please provide a description of the function:def execute_before(self, sensor_graph, scope_stack):
sensor_graph.add_constant(self.stream, 0)
new_scope = GatedClockScope(sensor_graph, scope_stack, (self.stream, self.trigger))
scope_stack.append(new_scope) | [
"Execute statement before children are executed.\n\n Args:\n sensor_graph (SensorGraph): The sensor graph that we are building or\n modifying\n scope_stack (list(Scope)): A stack of nested scopes that may influence\n how this statement allocates clocks or o... |
Please provide a description of the function:def ParseHeader(cls, script_data):
if len(script_data) < UpdateScript.SCRIPT_HEADER_LENGTH:
raise ArgumentError("Script is too short to contain a script header",
length=len(script_data), header_length=UpdateScript... | [
"Parse a script integrity header.\n\n This function makes sure any integrity hashes are correctly parsed and\n returns a ScriptHeader structure containing the information that it\n was able to parse out.\n\n Args:\n script_data (bytearray): The script that we should parse.\n\n... |
Please provide a description of the function:def FromBinary(cls, script_data, allow_unknown=True, show_rpcs=False):
curr = 0
records = []
header = cls.ParseHeader(script_data)
curr = header.header_length
cls.logger.debug("Parsed script header: %s, skipping %d bytes", ... | [
"Parse a binary update script.\n\n Args:\n script_data (bytearray): The binary data containing the script.\n allow_unknown (bool): Allow the script to contain unknown records\n so long as they have correct headers to allow us to skip them.\n show_rpcs (bool): S... |
Please provide a description of the function:def encode(self):
blob = bytearray()
for record in self.records:
blob += record.encode()
header = struct.pack("<LL", self.SCRIPT_MAGIC, len(blob) + self.SCRIPT_HEADER_LENGTH)
blob = header + blob
sha = hashlib.... | [
"Encode this record into a binary blob.\n\n This binary blob could be parsed via a call to FromBinary().\n\n Returns:\n bytearray: The binary encoded script.\n "
] |
Please provide a description of the function:def create_worker(self, func, interval, *args, **kwargs):
thread = StoppableWorkerThread(func, interval, args, kwargs)
self._workers.append(thread)
if self._started:
thread.start() | [
"Spawn a worker thread running func.\n\n The worker will be automatically be started when start() is called\n and terminated when stop() is called on this object.\n This must be called only from the main thread, not from a worker thread.\n\n create_worker must not be called after stop() ... |
Please provide a description of the function:def start_workers(self):
if self._started:
raise InternalError("The method start() was called twice on a BaseRunnable object.")
self._started = True
for worker in self._workers:
worker.start() | [
"Start running this virtual device including any necessary worker threads."
] |
Please provide a description of the function:def stop_workers(self):
self._started = False
for worker in self._workers:
worker.stop() | [
"Synchronously stop any potential workers."
] |
Please provide a description of the function:def stop_workers_async(self):
self._started = False
for worker in self._workers:
worker.signal_stop() | [
"Signal that all workers should stop without waiting."
] |
Please provide a description of the function:def clock(self, interval, basis):
cache_name = self._classify_clock(interval, basis)
cache_data = self.clock_cache.get(cache_name)
if cache_data is None:
parent_stream, trigger = self.parent.clock(interval, basis)
i... | [
"Return a NodeInput tuple for triggering an event every interval.\n\n We request each distinct type of clock at most once and combine it with our\n latch stream each time it is requested.\n\n Args:\n interval (int): The interval (in seconds) at which this input should\n ... |
Please provide a description of the function:def _download_ota_script(script_url):
try:
blob = requests.get(script_url, stream=True)
return blob.content
except Exception as e:
iprint("Failed to download OTA script")
iprint(e)
return False | [
"Download the script from the cloud service and store to temporary file location"
] |
Please provide a description of the function:def import_as(module, name):
dir = os.path.split(__file__)[0]
return imp.load_module(name, *imp.find_module(module, [dir])) | [
"\n Imports the specified module (from our local directory) as the\n specified name, returning the loaded module object.\n "
] |
Please provide a description of the function:def rename_module(new, old):
try:
sys.modules[new] = imp.load_module(old, *imp.find_module(old))
return True
except ImportError:
return False | [
"\n Attempts to import the old module and load it under the new name.\n Used for purely cosmetic name changes in Python 3.x.\n "
] |
Please provide a description of the function:def execute_before(self, sensor_graph, scope_stack):
parent = scope_stack[-1]
new_scope = Scope("Configuration Scope", sensor_graph, parent.allocator, parent)
new_scope.add_identifier('current_slot', self.slot)
scope_stack.append(new... | [
"Execute statement before children are executed.\n\n Args:\n sensor_graph (SensorGraph): The sensor graph that we are building or\n modifying\n scope_stack (list(Scope)): A stack of nested scopes that may influence\n how this statement allocates clocks or o... |
Please provide a description of the function:def _parse_conn_string(self, conn_string):
disconnection_required = False
if conn_string is None or 'device' not in conn_string:
if self._default_device_info is not None and self._device_info != self._default_device_info:
... | [
"Parse a connection string passed from 'debug -c' or 'connect_direct'\n Returns True if any settings changed in the debug port, which\n would require a jlink disconnection ",
"If device not in conn_string, set to default info"
] |
Please provide a description of the function:def _try_connect(self, connection_string):
if self._parse_conn_string(connection_string):
self._trigger_callback('on_disconnect', self.id, self._connection_id)
self.stop_sync()
if self._mux_func is not None:
... | [
"If the connecton string settings are different, try and connect to an attached device"
] |
Please provide a description of the function:def stop_sync(self):
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() | [
"Synchronously stop this adapter and release all resources."
] |
Please provide a description of the function:def probe_async(self, callback):
def _on_finished(_name, control_info, exception):
if exception is not None:
callback(self.id, False, str(exception))
return
self._control_info = control_info
... | [
"Send advertisements for all connected devices.\n\n Args:\n callback (callable): A callback for when the probe operation has completed.\n callback should have signature callback(adapter_id, success, failure_reason) where:\n success: bool\n failu... |
Please provide a description of the function:def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback):
known_commands = {
'dump_ram': JLinkControlThread.DUMP_ALL_RAM,
'program_flash': JLinkControlThread.PROGRAM_FLASH,
}
cmd_code = known_c... | [
"Asynchronously complete a named debug command.\n\n The command name and arguments are passed to the underlying device adapter\n and interpreted there. If the command is long running, progress_callback\n may be used to provide status updates. Callback is called when the command\n has f... |
Please provide a description of the function:def connect_async(self, connection_id, connection_string, callback):
self._try_connect(connection_string)
def _on_finished(_name, control_info, exception):
if exception is not None:
callback(connection_id, self.id, False,... | [
"Connect to a device by its connection_string\n\n This function asynchronously connects to a device by its BLE address\n passed in the connection_string parameter and calls callback when\n finished. Callback is called on either success or failure with the\n signature:\n\n callbac... |
Please provide a description of the function:def _open_debug_interface(self, conn_id, callback, connection_string=None):
self._try_connect(connection_string)
callback(conn_id, self.id, True, None) | [
"Enable debug interface for this IOTile device\n\n Args:\n conn_id (int): the unique identifier for the connection\n callback (callback): Callback to be called when this command finishes\n callback(conn_id, adapter_id, success, failure_reason)\n "
] |
Please provide a description of the function:def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
def _on_finished(_name, retval, exception):
if exception is not None:
callback(conn_id, self.id, False, str(exception), None, None)
r... | [
"Asynchronously send an RPC to this IOTile device.\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n address (int): the addres of the tile that we wish to send the RPC to\n rpc_id (int): the 16-bit id of the RPC we want to call\n pa... |
Please provide a description of the function:def send_script_async(self, conn_id, data, progress_callback, callback):
def _on_finished(_name, _retval, exception):
if exception is not None:
callback(conn_id, self.id, False, str(exception))
return
... | [
"Asynchronously send a a script to this IOTile device\n\n Args:\n conn_id (int): A unique identifer that will refer to this connection\n data (string): the script to send to the device\n progress_callback (callable): A function to be called with status on our progress, called... |
Please provide a description of the function:def _handle_reset(self):
self._registered.clear()
self._start_received.clear()
self._hosted_app_running.clear()
super(EmulatedPeripheralTile, self)._handle_reset() | [
"Reset this tile.\n\n This process needs to trigger the peripheral tile to reregister itself\n with the controller and get new configuration variables. It also\n needs to clear app_running.\n "
] |
Please provide a description of the function:def dump_state(self):
state = super(EmulatedPeripheralTile, self).dump_state()
state['app_started'] = self._hosted_app_running.is_set()
state['debug_mode'] = self.debug_mode
state['run_level'] = self.run_level
return state | [
"Dump the current state of this emulated tile as a dictionary.\n\n This function just dumps the status of the config variables. It is\n designed to be called in a chained fashion to serialize the complete\n state of a tile subclass.\n\n Returns:\n dict: The current state of t... |
Please provide a description of the function:def restore_state(self, state):
super(EmulatedPeripheralTile, self).restore_state(state)
self.debug_mode = state.get('debug_mode', False)
self.run_level = state.get('run_level', None)
if state.get('app_started', False):
... | [
"Restore the current state of this emulated object.\n\n Args:\n state (dict): A previously dumped state produced by dump_state.\n "
] |
Please provide a description of the function:async def start(self):
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() | [
"Start the gateway."
] |
Please provide a description of the function:async def stop(self):
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() | [
"Stop the gateway manager and synchronously wait for it to stop."
] |
Please provide a description of the function:def build_args():
parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('recipe', type=str, help="The recipe file to load and run.")
parser.add_argument('-d', '--define', action="a... | [
"Create command line argument parser."
] |
Please provide a description of the function:def load_variables(defines, config_file):
if config_file is not None:
with open(config_file, "r") as conf_file:
variables = yaml.load(conf_file)
else:
variables = {}
for define in defines:
name, equ, value = define.parti... | [
"Load all variables from cmdline args and/or a config file.\n\n Args:\n defines (list of str): A list of name=value pairs that\n define free variables.\n config_file (str): An optional path to a yaml config\n file that defines a single dict with name=value\n variabl... |
Please provide a description of the function:def main(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = build_args()
args = parser.parse_args(args=argv)
recipe_name, _ext = os.path.splitext(os.path.basename(args.recipe))
rm = RecipeManager()
rm.add_recipe_folder(os.path.... | [
"Main entry point for iotile-ship recipe runner.\n\n This is the iotile-ship command line program.\n\n Args:\n argv (list of str): An optional set of command line\n parameters. If not passed, these are taken from\n sys.argv.\n "
] |
Please provide a description of the function:def MatchQuality(cls, record_data, record_count=1):
if record_count > 1:
return MatchQuality.NoMatch
cmd, _address, _resp_length, _payload = cls._parse_rpc_info(record_data)
if cmd == PersistGraphRecord.RPC_ID:
retu... | [
"Check how well this record matches the given binary data.\n\n This function will only be called if the record matches the type code\n given by calling MatchType() and this functon should check how well\n this record matches and return a quality score between 0 and 100, with\n higher qua... |
Please provide a description of the function:def FromBinary(cls, record_data, record_count=1):
_cmd, address, _resp_length, _payload = cls._parse_rpc_info(record_data)
return PersistGraphRecord(address=address) | [
"Create an UpdateRecord subclass from binary record data.\n\n This should be called with a binary record blob (NOT including the\n record type header) and it will decode it into a PersistGraphRecord.\n\n Args:\n record_data (bytearray): The raw record data that we wish to parse\n ... |
Please provide a description of the function:def escape_list(mylist, escape_func):
def escape(obj, escape_func=escape_func):
try:
e = obj.escape
except AttributeError:
return obj
else:
return e(escape_func)
return list(map(escape, mylist)) | [
"Escape a list of arguments by running the specified escape_func\n on every object in the list that has an escape() method."
] |
Please provide a description of the function:def subst_dict(target, source):
dict = {}
if target:
def get_tgt_subst_proxy(thing):
try:
subst_proxy = thing.get_subst_proxy()
except AttributeError:
subst_proxy = thing # probably a string, just ... | [
"Create a dictionary for substitution of special\n construction variables.\n\n This translates the following special arguments:\n\n target - the target (object or array of objects),\n used to generate the TARGET and TARGETS\n construction variables\n\n source - the source (object... |
Please provide a description of the function:def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
if isinstance(strSubst, str) and strSubst.find('$') < 0:
return strSubst
class StringSubber(object):
def __init__(self, env, mode, ... | [
"Expand a string or list containing construction variable\n substitutions.\n\n This is the work-horse function for substitutions in file names\n and the like. The companion scons_subst_list() function (below)\n handles separating command lines into lists of arguments, so see\n that function if that'... |
Please provide a description of the function:def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
class ListSubber(collections.UserList):
def __init__(self, env, mode, conv, gvars):
collections.UserList.__init__(self, [])
... | [
"Substitute construction variables in a string (or list or other\n object) and separate the arguments into a command list.\n\n The companion scons_subst() function (above) handles basic\n substitutions within strings, so see that function instead\n if that's what you're looking for.\n ",
"A class t... |
Please provide a description of the function:def scons_subst_once(strSubst, env, key):
if isinstance(strSubst, str) and strSubst.find('$') < 0:
return strSubst
matchlist = ['$' + key, '${' + key + '}']
val = env.get(key, '')
def sub_match(match, val=val, matchlist=matchlist):
a = m... | [
"Perform single (non-recursive) substitution of a single\n construction variable keyword.\n\n This is used when setting a variable when copying or overriding values\n in an Environment. We want to capture (expand) the old value before\n we override it, so people can do things like:\n\n env2 = en... |
Please provide a description of the function:def escape(self, escape_func, quote_func=quote_spaces):
if self.is_literal():
return escape_func(self.data)
elif ' ' in self.data or '\t' in self.data:
return quote_func(self.data)
else:
return self.data | [
"Escape the string with the supplied function. The\n function is expected to take an arbitrary string, then\n return it with all special characters escaped and ready\n for passing to the command interpreter.\n\n After calling this function, the next call to str() will\n return th... |
Please provide a description of the function:def indent_list(inlist, level):
indent = ' '*level
joinstr = '\n' + indent
retval = joinstr.join(inlist)
return indent + retval | [
"Join a list of strings, one per line with 'level' spaces before each one"
] |
Please provide a description of the function:def process_warn_strings(arguments):
def _capitalize(s):
if s[:5] == "scons":
return "SCons" + s[5:]
else:
return s.capitalize()
for arg in arguments:
elems = arg.lower().split('-')
enable = 1
if... | [
"Process string specifications of enabling/disabling warnings,\n as passed to the --warn option or the SetOption('warn') function.\n \n\n An argument to this option should be of the form <warning-class>\n or no-<warning-class>. The warning class is munged in order\n to get an actual class name from ... |
Please provide a description of the function:def generate(env):
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 ['cygwin', 'win32']:
env['... | [
"Add Builders and construction variables for gfortran to an\n Environment."
] |
Please provide a description of the function:def _extract_device_uuid(cls, slug):
if len(slug) != 22:
raise ArgumentError("Invalid device slug", slug=slug)
hexdigits = slug[3:]
hexdigits = hexdigits.replace('-', '')
try:
rawbytes = binascii.unhexlify(h... | [
"Turn a string slug into a UUID\n "
] |
Please provide a description of the function:def start(self):
self._prepare()
self._disconnector = tornado.ioloop.PeriodicCallback(self._disconnect_hanging_devices, 1000, self._loop)
self._disconnector.start() | [
"Start this gateway agent."
] |
Please provide a description of the function:def stop(self):
if self._disconnector:
self._disconnector.stop()
self.client.disconnect() | [
"Stop this gateway agent."
] |
Please provide a description of the function:def _validate_connection(self, action, uuid, key):
if uuid not in self._connections:
self._logger.warn("Received message for device with no connection 0x%X", uuid)
return None
data = self._connections[uuid]
if key !=... | [
"Validate that a message received for a device has the right key\n\n If this action is valid the corresponding internal connection id to\n be used with the DeviceManager is returned, otherwise None is returned\n and an invalid message status is published.\n\n Args:\n slug (str... |
Please provide a description of the function:def _publish_status(self, slug, data):
status_topic = self.topics.prefix + 'devices/{}/data/status'.format(slug)
self._logger.debug("Publishing status message: (topic=%s) (message=%s)", status_topic, str(data))
self.client.publish(status_to... | [
"Publish a status message for a device\n\n Args:\n slug (string): The device slug that we are publishing on behalf of\n data (dict): The status message data to be sent back to the caller\n "
] |
Please provide a description of the function:def _publish_response(self, slug, message):
resp_topic = self.topics.gateway_topic(slug, 'data/response')
self._logger.debug("Publishing response message: (topic=%s) (message=%s)", resp_topic, message)
self.client.publish(resp_topic, message... | [
"Publish a response message for a device\n\n Args:\n slug (string): The device slug that we are publishing on behalf of\n message (dict): A set of key value pairs that are used to create the message\n that is sent.\n "
] |
Please provide a description of the function:def _on_action(self, sequence, topic, message):
try:
slug = None
parts = topic.split('/')
slug = parts[-3]
uuid = self._extract_device_uuid(slug)
except Exception as exc:
self._logger.warn(... | [
"Process a command action that we received on behalf of a device.\n\n Args:\n sequence (int): The sequence number of the packet received\n topic (string): The topic this message was received on\n message (dict): The message itself\n "
] |
Please provide a description of the function:def _on_connect(self, sequence, topic, message):
try:
slug = None
parts = topic.split('/')
slug = parts[-3]
uuid = self._extract_device_uuid(slug)
except Exception:
self._logger.exception("... | [
"Process a request to connect to an IOTile device\n\n A connection message triggers an attempt to connect to a device,\n any error checking is done by the DeviceManager that is actually\n managing the devices.\n\n A disconnection message is checked to make sure its key matches\n w... |
Please provide a description of the function:def _send_rpc(self, client, uuid, address, rpc, payload, timeout, key):
conn_id = self._validate_connection('send_rpc', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = ... | [
"Send an RPC to a connected device\n\n Args:\n client (string): The client that sent the rpc request\n uuid (int): The id of the device we're opening the interface on\n address (int): The address of the tile that we want to send the RPC to\n rpc (int): The id of th... |
Please provide a description of the function:def _send_script(self, client, uuid, chunk, key, chunk_status):
conn_id = self._validate_connection('send_script', uuid, key)
if conn_id is None:
return
conn_data = self._connections[uuid]
conn_data['last_touch'] = monot... | [
"Send a script to the connected device.\n\n Args:\n client (string): The client that sent the rpc request\n uuid (int): The id of the device we're opening the interface on\n chunk (bytes): The binary script to send to the device\n key (string): The key to authentic... |
Please provide a description of the function:def _notify_progress_sync(self, uuid, client, done_count, total_count):
# If the connection was closed, don't notify anything
conn_data = self._connections.get(uuid, None)
if conn_data is None:
return
last_progress = con... | [
"Notify progress reporting on the status of a script download.\n\n This function must be called synchronously inside of the event loop.\n\n Args:\n uuid (int): The id of the device that we are talking to\n client (string): The client identifier\n done_count (int): The ... |
Please provide a description of the function:def _notify_progress_async(self, uuid, client, done_count, total_count):
self._loop.add_callback(self._notify_progress_sync, uuid, client, done_count, total_count) | [
"Notify progress reporting on the status of a script download.\n\n This function is called asynchronously to the event loop so it cannot\n do any processing on its own. It's job is to schedule the sync version\n of itself in the event loop.\n\n Args:\n uuid (int): The id of t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.