Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def FromDictionary(cls, msg_dict):
level = msg_dict.get('level')
msg = msg_dict.get('message')
now = msg_dict.get('now_time')
created = msg_dict.get('created_time')
count = msg_dict.get('count', 1)
msg_id = msg_dict.g... | [
"Create from a dictionary with kv pairs.\n\n Args:\n msg_dict (dict): A dictionary with information as created by to_dict()\n\n Returns:\n ServiceMessage: the converted message\n "
] |
Please provide a description of the function:def to_dict(self):
msg_dict = {}
msg_dict['level'] = self.level
msg_dict['message'] = self.message
msg_dict['now_time'] = monotonic()
msg_dict['created_time'] = self.created
msg_dict['id'] = self.id
msg_dict['... | [
"Create a dictionary with the information in this message.\n\n Returns:\n dict: The dictionary with information\n "
] |
Please provide a description of the function:def get_message(self, message_id):
for message in self.messages:
if message.id == message_id:
return message
raise ArgumentError("Message ID not found", message_id=message_id) | [
"Get a message by its persistent id.\n\n Args:\n message_id (int): The id of the message that we're looking for\n "
] |
Please provide a description of the function:def post_message(self, level, message, count=1, timestamp=None, now_reference=None):
if len(self.messages) > 0 and self.messages[-1].message == message:
self.messages[-1].count += 1
else:
msg_object = ServiceMessage(level, me... | [
"Post a new message for service.\n\n Args:\n level (int): The level of the message (info, warning, error)\n message (string): The message contents\n count (int): The number of times the message has been repeated\n timestamp (float): An optional monotonic value in s... |
Please provide a description of the function:def set_headline(self, level, message, timestamp=None, now_reference=None):
if self.headline is not None and self.headline.message == message:
self.headline.created = monotonic()
self.headline.count += 1
return
m... | [
"Set the persistent headline message for this service.\n\n Args:\n level (int): The level of the message (info, warning, error)\n message (string): The message contents\n timestamp (float): An optional monotonic value in seconds for when the message was created\n n... |
Please provide a description of the function:def generate_doxygen_file(output_path, iotile):
mapping = {}
mapping['short_name'] = iotile.short_name
mapping['full_name'] = iotile.full_name
mapping['authors'] = iotile.authors
mapping['version'] = iotile.version
render_template('doxygen.txt... | [
"Fill in our default doxygen template file with info from an IOTile\n\n This populates things like name, version, etc.\n\n Arguments:\n output_path (str): a string path for where the filled template should go\n iotile (IOTile): An IOTile object that can be queried for information\n "
] |
Please provide a description of the function:def pull(name, version, force=False):
chain = DependencyResolverChain()
ver = SemanticVersionRange.FromString(version)
chain.pull_release(name, ver, force=force) | [
"Pull a released IOTile component into the current working directory\n\n The component is found using whatever DependencyResolvers are installed and registered\n as part of the default DependencyResolverChain. This is the same mechanism used in\n iotile depends update, so any component that can be updated... |
Please provide a description of the function:def add_callback(self, name, func):
if name == 'on_scan':
events = ['device_seen']
def callback(_conn_string, _conn_id, _name, event):
func(self.id, event, event.get('validity_period', 60))
elif name == 'on_re... | [
"Add a callback when device events happen.\n\n Args:\n name (str): currently support 'on_scan' and 'on_disconnect'\n func (callable): the function that should be called\n "
] |
Please provide a description of the function:def connect_async(self, conn_id, connection_string, callback):
future = self._loop.launch_coroutine(self._adapter.connect(conn_id, connection_string))
future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback)) | [
"Asynchronously connect to a device."
] |
Please provide a description of the function:def disconnect_async(self, conn_id, callback):
future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id))
future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback)) | [
"Asynchronously disconnect from a device."
] |
Please provide a description of the function:def open_interface_async(self, conn_id, interface, callback, connection_string=None):
future = self._loop.launch_coroutine(self._adapter.open_interface(conn_id, interface))
future.add_done_callback(lambda x: self._callback_future(conn_id, x, callbac... | [
"Asynchronously connect to a device."
] |
Please provide a description of the function:def probe_async(self, callback):
future = self._loop.launch_coroutine(self._adapter.probe())
future.add_done_callback(lambda x: self._callback_future(None, x, callback)) | [
"Asynchronously connect to a device."
] |
Please provide a description of the function:def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
future = self._loop.launch_coroutine(self._adapter.send_rpc(conn_id, address, rpc_id, payload, timeout))
def format_response(future):
payload = None
... | [
"Asynchronously send an RPC to this IOTile device."
] |
Please provide a description of the function:def debug_async(self, conn_id, cmd_name, cmd_args, progress_callback, callback):
def monitor_callback(_conn_string, _conn_id, _event_name, event):
if event.get('operation') != 'debug':
return
progress_callback(event.... | [
"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 send_script_async(self, conn_id, data, progress_callback, callback):
def monitor_callback(_conn_string, _conn_id, _event_name, event):
if event.get('operation') != 'script':
return
progress_callback(event.get('fi... | [
"Asynchronously send a script to the device."
] |
Please provide a description of the function:def lock(self, key, client):
self.key = key
self.client = client | [
"Set the key that will be used to ensure messages come from one party\n\n Args:\n key (string): The key used to validate future messages\n client (string): A string that will be returned to indicate who\n locked this device.\n "
] |
Please provide a description of the function:def track_change(self, tile, property_name, value, formatter=None):
if not self.tracking:
return
if len(self._whitelist) > 0 and (tile, property_name) not in self._whitelist:
return
if formatter is None:
... | [
"Record that a change happened on a given tile's property.\n\n This will as a StateChange object to our list of changes if we\n are recording changes, otherwise, it will drop the change.\n\n Args:\n tile (int): The address of the tile that the change happened on.\n propert... |
Please provide a description of the function:def dump(self, out_path, header=True):
# See https://stackoverflow.com/a/3348664/9739119 for why this is necessary
if sys.version_info[0] < 3:
mode = "wb"
else:
mode = "w"
with open(out_path, mode) as outfile... | [
"Save this list of changes as a csv file at out_path.\n\n The format of the output file will be a CSV with 4 columns:\n timestamp, tile address, property, string_value\n\n There will be a single header row starting the CSV output unless\n header=False is passed.\n\n Args:\n ... |
Please provide a description of the function:def PDFTeXLaTeXFunction(target = None, source= None, env=None):
basedir = os.path.split(str(source[0]))[0]
abspath = os.path.abspath(basedir)
if SCons.Tool.tex.is_LaTeX(source,env,abspath):
result = PDFLaTeXAuxAction(target,source,env)
if re... | [
"A builder for TeX and LaTeX that scans the source file to\n decide the \"flavor\" of the source and then executes the appropriate\n program."
] |
Please provide a description of the function:def generate(env):
global PDFTeXAction
if PDFTeXAction is None:
PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR')
global PDFLaTeXAction
if PDFLaTeXAction is None:
PDFLaTeXAction = SCons.Action.Action("$PDFLATEXCOM", "$PDF... | [
"Add Builders and construction variables for pdftex to an Environment."
] |
Please provide a description of the function:def start(self, channel):
super(TileBasedVirtualDevice, self).start(channel)
for tile in self._tiles.values():
tile.start(channel=channel) | [
"Start running this virtual device including any necessary worker threads.\n\n Args:\n channel (IOTilePushChannel): the channel with a stream and trace\n routine for streaming and tracing data through a VirtualInterface\n "
] |
Please provide a description of the function:def stop(self):
for tile in self._tiles.values():
tile.signal_stop()
for tile in self._tiles.values():
tile.wait_stopped()
super(TileBasedVirtualDevice, self).stop() | [
"Stop running this virtual device including any worker threads."
] |
Please provide a description of the function:def SetCacheMode(mode):
global cache_mode
if mode == "auto":
cache_mode = AUTO
elif mode == "force":
cache_mode = FORCE
elif mode == "cache":
cache_mode = CACHE
else:
raise ValueError("SCons.SConf.SetCacheMode: Unknown... | [
"Set the Configure cache mode. mode must be one of \"auto\", \"force\",\n or \"cache\"."
] |
Please provide a description of the function:def CreateConfigHBuilder(env):
action = SCons.Action.Action(_createConfigH,
_stringConfigH)
sconfigHBld = SCons.Builder.Builder(action=action)
env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} )
for k in list(_ac_confi... | [
"Called if necessary just before the building targets phase begins."
] |
Please provide a description of the function:def CheckHeader(context, header, include_quotes = '<>', language = None):
prog_prefix, hdr_to_check = \
createIncludesFromHeaders(header, 1, include_quotes)
res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix,
... | [
"\n A test for a C or C++ header file.\n "
] |
Please provide a description of the function:def CheckLib(context, library = None, symbol = "main",
header = None, language = None, autoadd = 1):
if library == []:
library = [None]
if not SCons.Util.is_List(library):
library = [library]
# ToDo: accept path for the librar... | [
"\n A test for a library. See also CheckLibWithHeader.\n Note that library may also be None to test whether the given symbol\n compiles without flags.\n "
] |
Please provide a description of the function:def CheckLibWithHeader(context, libs, header, language,
call = None, autoadd = 1):
# ToDo: accept path for library. Support system header files.
prog_prefix, dummy = \
createIncludesFromHeaders(header, 0)
if libs == []... | [
"\n Another (more sophisticated) test for a library.\n Checks, if library and header is available for language (may be 'C'\n or 'CXX'). Call maybe be a valid expression _with_ a trailing ';'.\n As in CheckLib, we support library=None, to test if the call compiles\n without extra link flags.\n "
] |
Please provide a description of the function:def CheckProg(context, prog_name):
res = SCons.Conftest.CheckProg(context, prog_name)
context.did_show_result = 1
return res | [
"Simple check if a program exists in the path. Returns the path\n for the application, or None if not found.\n "
] |
Please provide a description of the function:def display_cached_string(self, bi):
if not isinstance(bi, SConfBuildInfo):
SCons.Warnings.warn(SConfWarning,
"The stored build information has an unexpected class: %s" % bi.__class__)
else:
self.display("The ori... | [
"\n Logs the original builder messages, given the SConfBuildInfo instance\n bi.\n "
] |
Please provide a description of the function:def Define(self, name, value = None, comment = None):
lines = []
if comment:
comment_str = "/* %s */" % comment
lines.append(comment_str)
if value is not None:
define_str = "#define %s %s" % (name, value)
... | [
"\n Define a pre processor symbol name, with the optional given value in the\n current config header.\n\n If value is None (default), then #define name is written. If value is not\n none, then #define name value is written.\n\n comment is a string which will be put as a C comment ... |
Please provide a description of the function:def BuildNodes(self, nodes):
if self.logstream is not None:
# override stdout / stderr to write in log file
oldStdout = sys.stdout
sys.stdout = self.logstream
oldStderr = sys.stderr
sys.stderr = sel... | [
"\n Tries to build the given nodes immediately. Returns 1 on success,\n 0 on error.\n "
] |
Please provide a description of the function:def pspawn_wrapper(self, sh, escape, cmd, args, env):
return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream) | [
"Wrapper function for handling piped spawns.\n\n This looks to the calling interface (in Action.py) like a \"normal\"\n spawn, but associates the call with the PSPAWN variable from\n the construction environment and with the streams to which we\n want the output logged. This gets slid i... |
Please provide a description of the function:def TryBuild(self, builder, text = None, extension = ""):
global _ac_build_counter
# Make sure we have a PSPAWN value, and save the current
# SPAWN value.
try:
self.pspawn = self.env['PSPAWN']
except KeyError:
... | [
"Low level TryBuild implementation. Normally you don't need to\n call that - you can use TryCompile / TryLink / TryRun instead\n "
] |
Please provide a description of the function:def TryAction(self, action, text = None, extension = ""):
builder = SCons.Builder.Builder(action=action)
self.env.Append( BUILDERS = {'SConfActionBuilder' : builder} )
ok = self.TryBuild(self.env.SConfActionBuilder, text, extension)
d... | [
"Tries to execute the given action with optional source file\n contents <text> and optional source file extension <extension>,\n Returns the status (0 : failed, 1 : ok) and the contents of the\n output file.\n "
] |
Please provide a description of the function:def TryCompile( self, text, extension):
return self.TryBuild(self.env.Object, text, extension) | [
"Compiles the program given in text to an env.Object, using extension\n as file extension (e.g. '.c'). Returns 1, if compilation was\n successful, 0 otherwise. The target is saved in self.lastTarget (for\n further processing).\n "
] |
Please provide a description of the function:def TryLink( self, text, extension ):
return self.TryBuild(self.env.Program, text, extension ) | [
"Compiles the program given in text to an executable env.Program,\n using extension as file extension (e.g. '.c'). Returns 1, if\n compilation was successful, 0 otherwise. The target is saved in\n self.lastTarget (for further processing).\n "
] |
Please provide a description of the function:def TryRun(self, text, extension ):
ok = self.TryLink(text, extension)
if( ok ):
prog = self.lastTarget
pname = prog.get_internal_path()
output = self.confdir.File(os.path.basename(pname)+'.out')
node =... | [
"Compiles and runs the program given in text, using extension\n as file extension (e.g. '.c'). Returns (1, outputStr) on success,\n (0, '') otherwise. The target (a file containing the program's stdout)\n is saved in self.lastTarget (for further processing).\n "
] |
Please provide a description of the function:def _shutdown(self):
global sconf_global, _ac_config_hs
if not self.active:
raise SCons.Errors.UserError("Finish may be called only once!")
if self.logstream is not None and not dryrun:
self.logstream.write("\n")
... | [
"Private method. Reset to non-piped spawn"
] |
Please provide a description of the function:def Message(self, text):
self.Display(text)
self.sconf.cached = 1
self.did_show_result = 0 | [
"Inform about what we are doing right now, e.g.\n 'Checking for SOMETHING ... '\n "
] |
Please provide a description of the function:def Result(self, res):
if isinstance(res, str):
text = res
elif res:
text = "yes"
else:
text = "no"
if self.did_show_result == 0:
# Didn't show result yet, do it now.
self.D... | [
"Inform about the result of the test. If res is not a string, displays\n 'yes' or 'no' depending on whether res is evaluated as true or false.\n The result is only displayed when self.did_show_result is not set.\n "
] |
Please provide a description of the function:def linux_ver_normalize(vstr):
# Check for version number like 9.1.026: return 91.026
# XXX needs to be updated for 2011+ versions (like 2011.11.344 which is compiler v12.1.5)
m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', vstr)
if m:
vmaj,vmin,bu... | [
"Normalize a Linux compiler version number.\n Intel changed from \"80\" to \"9.0\" in 2005, so we assume if the number\n is greater than 60 it's an old-style number and otherwise new-style.\n Always returns an old-style float like 80 or 90 for compatibility with Windows.\n Shades of Y2K!"
] |
Please provide a description of the function:def check_abi(abi):
if not abi:
return None
abi = abi.lower()
# valid_abis maps input name to canonical name
if is_windows:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'ia64' : 'ia64',
... | [
"Check for valid ABI (application binary interface) name,\n and map into canonical one"
] |
Please provide a description of the function:def get_version_from_list(v, vlist):
if is_windows:
# Simple case, just find it in the list
if v in vlist: return v
else: return None
else:
# Fuzzy match: normalize version number first, but still return
# original non-nor... | [
"See if we can match v (string) in vlist (list of strings)\n Linux has to match in a fuzzy way."
] |
Please provide a description of the function:def get_intel_registry_value(valuename, version=None, abi=None):
# Open the key:
if is_win64:
K = 'Software\\Wow6432Node\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
else:
K = 'Software\\Intel\\Compilers\\C++\\' + version + '\\'+abi... | [
"\n Return a value from the Intel compiler registry tree. (Windows only)\n "
] |
Please provide a description of the function:def get_all_compiler_versions():
versions=[]
if is_windows:
if is_win64:
keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++'
else:
keyname = 'Software\\Intel\\Compilers\\C++'
try:
k = SCons.Util.Re... | [
"Returns a sorted list of strings, like \"70\" or \"80\" or \"9.0\"\n with most recent compiler version first.\n ",
"Given a dot-separated version string, return a tuple of ints representing it."
] |
Please provide a description of the function:def get_intel_compiler_top(version, abi):
if is_windows:
if not SCons.Util.can_read_reg:
raise NoRegistryModuleError("No Windows registry module was found")
top = get_intel_registry_value('ProductDir', version, abi)
archdir={'x86... | [
"\n Return the main path to the top-level dir of the Intel compiler,\n using the given version.\n The compiler will be in <top>/bin/icl.exe (icc on linux),\n the include dir is <top>/include, etc.\n "
] |
Please provide a description of the function:def generate(env, version=None, abi=None, topdir=None, verbose=0):
if not (is_mac or is_linux or is_windows):
# can't handle this platform
return
if is_windows:
SCons.Tool.msvc.generate(env)
elif is_linux:
SCons.Tool.gcc.gene... | [
"Add Builders and construction variables for Intel C/C++ compiler\n to an Environment.\n args:\n version: (string) compiler version to use, like \"80\"\n abi: (string) 'win32' or whatever Itanium version wants\n topdir: (string) compiler top dir, like\n \"c:\\Progra... |
Please provide a description of the function:def parse_node_descriptor(desc, model):
try:
data = graph_node.parseString(desc)
except ParseException:
raise # TODO: Fix this to properly encapsulate the parse error
stream_desc = u' '.join(data['node'])
stream = DataStream.FromStrin... | [
"Parse a string node descriptor.\n\n The function creates an SGNode object without connecting its inputs and outputs\n and returns a 3-tuple:\n\n SGNode, [(input X, trigger X)], <processing function name>\n\n Args:\n desc (str): A description of the node to be created.\n model (str): A dev... |
Please provide a description of the function:def create_binary_descriptor(descriptor):
func_names = {0: 'copy_latest_a', 1: 'average_a',
2: 'copy_all_a', 3: 'sum_a',
4: 'copy_count_a', 5: 'trigger_streamer',
6: 'call_rpc', 7: 'subtract_afromb'}
func_c... | [
"Convert a string node descriptor into a 20-byte binary descriptor.\n\n This is the inverse operation of parse_binary_descriptor and composing\n the two operations is a noop.\n\n Args:\n descriptor (str): A string node descriptor\n\n Returns:\n bytes: A 20-byte binary node descriptor.\n ... |
Please provide a description of the function:def parse_binary_descriptor(bindata):
func_names = {0: 'copy_latest_a', 1: 'average_a',
2: 'copy_all_a', 3: 'sum_a',
4: 'copy_count_a', 5: 'trigger_streamer',
6: 'call_rpc', 7: 'subtract_afromb'}
if len(bin... | [
"Convert a binary node descriptor into a string descriptor.\n\n Binary node descriptor are 20-byte binary structures that encode all\n information needed to create a graph node. They are used to communicate\n that information to an embedded device in an efficent format. This\n function exists to turn ... |
Please provide a description of the function:def _process_binary_trigger(trigger_value, condition):
ops = {
0: ">",
1: "<",
2: ">=",
3: "<=",
4: "==",
5: 'always'
}
sources = {
0: 'value',
1: 'count'
}
encoded_source = condition... | [
"Create an InputTrigger object."
] |
Please provide a description of the function:def _create_binary_trigger(trigger):
ops = {
0: ">",
1: "<",
2: ">=",
3: "<=",
4: "==",
5: 'always'
}
op_codes = {y: x for x, y in ops.items()}
source = 0
if isinstance(trigger, TrueTrigger):
... | [
"Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger."
] |
Please provide a description of the function:def _try_assign_utc_time(self, raw_time, time_base):
# Check if the raw time is encoded UTC since y2k or just uptime
if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)):
y2k_offset = self.raw_time ^ (1 << 31)
... | [
"Try to assign a UTC time to this reading."
] |
Please provide a description of the function:def asdict(self):
timestamp_str = None
if self.reading_time is not None:
timestamp_str = self.reading_time.isoformat()
return {
'stream': self.stream,
'device_timestamp': self.raw_time,
'strea... | [
"Encode the data in this reading into a dictionary.\n\n Returns:\n dict: A dictionary containing the information from this reading.\n "
] |
Please provide a description of the function:def asdict(self):
return {
'stream': self.stream,
'device_timestamp': self.raw_time,
'streamer_local_id': self.reading_id,
'timestamp': self.reading_time,
'extra_data': self.summary_data,
... | [
"Encode the data in this event into a dictionary.\n\n The dictionary returned from this method is a reference to the data\n stored in the IOTileEvent, not a copy. It should be treated as read\n only.\n\n Returns:\n dict: A dictionary containing the information from this event... |
Please provide a description of the function:def FromDict(cls, obj):
timestamp = obj.get('timestamp')
if timestamp is not None:
import dateutil.parser
timestamp = dateutil.parser.parse(timestamp)
return IOTileEvent(obj.get('device_timestamp'), obj.get('stream')... | [
"Create an IOTileEvent from the result of a previous call to asdict().\n\n Args:\n obj (dict): A dictionary produced by a call to IOTileEvent.asdict()\n\n Returns:\n IOTileEvent: The converted IOTileEvent object.\n "
] |
Please provide a description of the function:def save(self, path):
data = self.encode()
with open(path, "wb") as out:
out.write(data) | [
"Save a binary copy of this report\n\n Args:\n path (string): The path where we should save the binary copy of the report\n "
] |
Please provide a description of the function:def serialize(self):
info = {}
info['received_time'] = self.received_time
info['encoded_report'] = bytes(self.encode())
# Handle python 2 / python 3 differences
report_format = info['encoded_report'][0]
if not isinst... | [
"Turn this report into a dictionary that encodes all information including received timestamp"
] |
Please provide a description of the function:def get_contents(self):
childsigs = [n.get_csig() for n in self.children()]
return ''.join(childsigs) | [
"The contents of an alias is the concatenation\n of the content signatures of all its sources."
] |
Please provide a description of the function:def get_csig(self):
try:
return self.ninfo.csig
except AttributeError:
pass
contents = self.get_contents()
csig = SCons.Util.MD5signature(contents)
self.get_ninfo().csig = csig
return csig | [
"\n Generate a node's content signature, the digested signature\n of its content.\n\n node - the node\n cache - alternate node to use for the signature cache\n returns - the content signature\n "
] |
Please provide a description of the function:def generate(env):
import SCons.Tool
import SCons.Tool.cc
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CXXAction)
shared_obj.add_action(suffix, SCons.D... | [
"\n Add Builders and construction variables for Visual Age C++ compilers\n to an Environment.\n "
] |
Please provide a description of the function:def link_to_storage(self, sensor_log):
if self.walker is not None:
self._sensor_log.destroy_walker(self.walker)
self.walker = None
self.walker = sensor_log.create_walker(self.selector)
self._sensor_log = sensor_log | [
"Attach this DataStreamer to an underlying SensorLog.\n\n Calling this method is required if you want to use this DataStreamer\n to generate reports from the underlying data in the SensorLog.\n\n You can call it multiple times and it will unlink itself from any\n previous SensorLog each ... |
Please provide a description of the function:def triggered(self, manual=False):
if self.walker is None:
raise InternalError("You can only check if a streamer is triggered if you create it with a SensorLog")
if not self.automatic and not manual:
return False
re... | [
"Check if this streamer should generate a report.\n\n Streamers can be triggered automatically whenever they have data\n or they can be triggered manually. This method returns True if the\n streamer is currented triggered.\n\n A streamer is triggered if it:\n - (has data AND is ... |
Please provide a description of the function:def build_report(self, device_id, max_size=None, device_uptime=0, report_id=None, auth_chain=None):
if self.walker is None or self.index is None:
raise InternalError("You can only build a report with a DataStreamer if you create it with a Sensor... | [
"Build a report with all of the readings in this streamer.\n\n This method will produce an IOTileReport subclass and, if necessary,\n sign it using the passed authentication chain.\n\n Args:\n device_id (int): The UUID of the device to generate a report for.\n max_size (in... |
Please provide a description of the function:def matches(self, address, name=None):
if self.controller:
return address == 8
return self.address == address | [
"Check if this slot identifier matches the given tile.\n\n Matching can happen either by address or by module name (not currently implemented).\n\n Returns:\n bool: True if there is a match, otherwise False.\n "
] |
Please provide a description of the function:def FromString(cls, desc):
desc = str(desc)
if desc == u'controller':
return SlotIdentifier(controller=True)
words = desc.split()
if len(words) != 2 or words[0] != u'slot':
raise ArgumentError(u"Illegal slot... | [
"Create a slot identifier from a string description.\n\n The string needs to be either:\n\n controller\n OR\n slot <X> where X is an integer that can be converted with int(X, 0)\n\n Args:\n desc (str): The string description of the slot\n\n Returns:\n ... |
Please provide a description of the function:def FromEncoded(cls, bindata):
if len(bindata) != 8:
raise ArgumentError("Invalid binary slot descriptor with invalid length", length=len(bindata), expected=8, data=bindata)
slot, match_op = struct.unpack("<B6xB", bindata)
matc... | [
"Create a slot identifier from an encoded binary descriptor.\n\n These binary descriptors are used to communicate slot targeting\n to an embedded device. They are exactly 8 bytes in length.\n\n Args:\n bindata (bytes): The 8-byte binary descriptor.\n\n Returns:\n S... |
Please provide a description of the function:def encode(self):
slot = 0
match_op = self.KNOWN_MATCH_NAMES['match_controller']
if not self.controller:
slot = self.slot
match_op = self.KNOWN_MATCH_NAMES['match_slot']
return struct.pack("<B6xB", slot, mat... | [
"Encode this slot identifier into a binary descriptor.\n\n Returns:\n bytes: The 8-byte encoded slot identifier\n "
] |
Please provide a description of the function:def _scons_syntax_error(e):
etype, value, tb = sys.exc_info()
lines = traceback.format_exception_only(etype, value)
for line in lines:
sys.stderr.write(line+'\n')
sys.exit(2) | [
"Handle syntax errors. Print out a message and show where the error\n occurred.\n "
] |
Please provide a description of the function:def find_deepest_user_frame(tb):
tb.reverse()
# find the deepest traceback frame that is not part
# of SCons:
for frame in tb:
filename = frame[0]
if filename.find(os.sep+'SCons'+os.sep) == -1:
return frame
return tb[0] | [
"\n Find the deepest stack frame that is not part of SCons.\n\n Input is a \"pre-processed\" stack trace in the form\n returned by traceback.extract_tb() or traceback.extract_stack()\n "
] |
Please provide a description of the function:def _scons_user_error(e):
global print_stacktrace
etype, value, tb = sys.exc_info()
if print_stacktrace:
traceback.print_exception(etype, value, tb)
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stde... | [
"Handle user errors. Print out a message and a description of the\n error, along with the line number and routine where it occured.\n The file and line number will be the deepest stack frame that is\n not part of SCons itself.\n "
] |
Please provide a description of the function:def _scons_user_warning(e):
etype, value, tb = sys.exc_info()
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stderr.write("\nscons: warning: %s\n" % e)
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, ... | [
"Handle user warnings. Print out a message and a description of\n the warning, along with the line number and routine where it occured.\n The file and line number will be the deepest stack frame that is\n not part of SCons itself.\n "
] |
Please provide a description of the function:def _scons_internal_warning(e):
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_stack())
sys.stderr.write("\nscons: warning: %s\n" % e.args[0])
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine)) | [
"Slightly different from _scons_user_warning in that we use the\n *current call stack* rather than sys.exc_info() to get our stack trace.\n This is used by the warnings framework to print warnings."
] |
Please provide a description of the function:def _SConstruct_exists(dirname='', repositories=[], filelist=None):
if not filelist:
filelist = ['SConstruct', 'Sconstruct', 'sconstruct']
for file in filelist:
sfile = os.path.join(dirname, file)
if os.path.isfile(sfile):
ret... | [
"This function checks that an SConstruct file exists in a directory.\n If so, it returns the path of the file. By default, it checks the\n current directory.\n "
] |
Please provide a description of the function:def _load_site_scons_dir(topdir, site_dir_name=None):
if site_dir_name:
err_if_not_found = True # user specified: err if missing
else:
site_dir_name = "site_scons"
err_if_not_found = False
site_dir = os.path.join(topdir, site_d... | [
"Load the site_scons dir under topdir.\n Prepends site_scons to sys.path, imports site_scons/site_init.py,\n and prepends site_scons/site_tools to default toolpath."
] |
Please provide a description of the function:def _load_all_site_scons_dirs(topdir, verbose=None):
platform = SCons.Platform.platform_default()
def homedir(d):
return os.path.expanduser('~/'+d)
if platform == 'win32' or platform == 'cygwin':
# Note we use $ here instead of %...% becaus... | [
"Load all of the predefined site_scons dir.\n Order is significant; we load them in order from most generic\n (machine-wide) to most specific (topdir).\n The verbose argument is only for testing.\n "
] |
Please provide a description of the function:def make_ready(self):
SCons.Taskmaster.OutOfDateTask.make_ready(self)
if self.out_of_date and self.options.debug_explain:
explanation = self.out_of_date[0].explain()
if explanation:
sys.stdout.write("scons: " +... | [
"Make a task ready for execution"
] |
Please provide a description of the function:def encode(self):
begin_payload = struct.pack("<H8s", self.config_id, self.target.encode())
start_record = SendErrorCheckingRPCRecord(8, self.BEGIN_CONFIG_RPC, begin_payload, 4)
end_record = SendErrorCheckingRPCRecord(8, self.END_CONFIG_RPC,... | [
"Encode this record into binary, suitable for embedded into an update script.\n\n This function will create multiple records that correspond to the actual\n underlying rpcs that SetConfigRecord turns into.\n\n Returns:\n bytearary: The binary version of the record that could be parse... |
Please provide a description of the function:def MatchQuality(cls, record_data, record_count=1):
if record_count == 1:
cmd, address, _resp_length, _payload = SendErrorCheckingRPCRecord._parse_rpc_info(record_data)
if cmd == cls.BEGIN_CONFIG_RPC and address == 8:
... | [
"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):
rpcs = SendErrorCheckingRPCRecord.parse_multiple_rpcs(record_data)
start_rpc = rpcs[0]
push_rpcs = rpcs[1:-1]
try:
config_id, raw_target = struct.unpack("<H8s", start_rp... | [
"Create an UpdateRecord subclass from binary record data.\n\n This is a multi-action record that matches a pattern of error checking\n RPC calls:\n begin config\n push config data\n <possibly multiple>\n end config\n\n Args:\n record_data (bytearray): The ... |
Please provide a description of the function:def _unpack_version(tag_data):
tag = tag_data & ((1 << 20) - 1)
version_data = tag_data >> 20
major = (version_data >> 6) & ((1 << 6) - 1)
minor = (version_data >> 0) & ((1 << 6) - 1)
return (tag, "{}.{}".format(major, minor)) | [
"Parse a packed version info struct into tag and major.minor version.\n\n The tag and version are parsed out according to 20 bits for tag and\n 6 bits each for major and minor. The more interesting part is the\n blacklisting performed for tags that are known to be untrustworthy.\n\n In particular, the ... |
Please provide a description of the function:def _handle_reset(self):
self._logger.info("Resetting controller")
self._device.reset_count += 1
super(ReferenceController, self)._handle_reset()
# Load in all default values into our config variables before streaming
# upd... | [
"Reset this controller tile.\n\n This process will call _handle_reset() for all of the controller\n subsystem mixins in order to make sure they all return to their proper\n reset state.\n\n It will then reset all of the peripheral tiles to emulate the behavior\n of a physical POD ... |
Please provide a description of the function:async def _reset_vector(self):
# Send ourselves all of our config variable assignments
config_rpcs = self.config_database.stream_matching(8, self.name)
for rpc in config_rpcs:
await self._device.emulator.await_rpc(*rpc)
... | [
"Initialize the controller's subsystems inside the emulation thread."
] |
Please provide a description of the function:def dump_state(self):
superstate = super(ReferenceController, self).dump_state()
superstate.update({
'state_name': self.STATE_NAME,
'state_version': self.STATE_VERSION,
'app_info': self.app_info,
'os_... | [
"Dump the current state of this emulated object as a dictionary.\n\n Returns:\n dict: The current state of the object that could be passed to load_state.\n "
] |
Please provide a description of the function:def restore_state(self, state):
super(ReferenceController, self).restore_state(state)
state_name = state.get('state_name')
state_version = state.get('state_version')
if state_name != self.STATE_NAME or state_version != self.STATE_V... | [
"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:def hardware_version(self):
hardware_string = self.hardware_string
if not isinstance(hardware_string, bytes):
hardware_string = self.hardware_string.encode('utf-8')
if len(hardware_string) > 10:
self._logger.warn("T... | [
"Get a hardware identification string."
] |
Please provide a description of the function:def controller_info(self):
return [self._device.iotile_id, _pack_version(*self.os_info), _pack_version(*self.app_info)] | [
"Get the controller UUID, app tag and os tag."
] |
Please provide a description of the function:def set_app_os_tag(self, os_tag, app_tag, update_os, update_app):
update_os = bool(update_os)
update_app = bool(update_app)
if update_os:
self.os_info = _unpack_version(os_tag)
if update_app:
self.app_info =... | [
"Update the app and/or os tags."
] |
Please provide a description of the function:def load_sgf(self, sgf_data):
if '\n' not in sgf_data:
with open(sgf_data, "r") as infile:
sgf_data = infile.read()
model = DeviceModel()
parser = SensorGraphFileParser()
parser.parse_file(data=sgf_data)... | [
"Load, persist a sensor_graph file.\n\n The data passed in `sgf_data` can either be a path or the already\n loaded sgf lines as a string. It is determined to be sgf lines if\n there is a '\\n' character in the data, otherwise it is interpreted as\n a path.\n\n Note that this scen... |
Please provide a description of the function:def _parse_file(self):
# We need to set the CPU type to pull in the right register definitions
# only preprocess the file (-E) and get rid of gcc extensions that aren't
# supported in ISO C.
args = utilities.build_includes(self.arch.... | [
"Preprocess and parse C file into an AST"
] |
Please provide a description of the function:def _clear_queue(to_clear):
while not to_clear.empty():
try:
to_clear.get(False)
to_clear.task_done()
except queue.Empty:
continue | [
"Clear all items from a queue safely."
] |
Please provide a description of the function:def finish(self, status, response):
self.response = binascii.hexlify(response).decode('utf-8')
self.status = status
self.runtime = monotonic() - self._start_time | [
"Mark the end of a recorded RPC."
] |
Please provide a description of the function:def serialize(self):
return "{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}".\
format(self.connection, self.start_stamp.isoformat(), self.address, self.rpc_id,
self.status, self.runtime * 1000, self.call, self.res... | [
"Convert this recorded RPC into a string."
] |
Please provide a description of the function:def scan(self, wait=None):
min_scan = self.adapter.get_config('minimum_scan_time', 0.0)
probe_required = self.adapter.get_config('probe_required', False)
# Figure out how long and if we need to wait before returning our scan results
... | [
"Return the devices that have been found for this device adapter.\n\n If the adapter indicates that we need to explicitly tell it to probe for devices, probe now.\n By default we return the list of seen devices immediately, however there are two cases where\n we will sleep here for a fixed peri... |
Please provide a description of the function:def connect(self, uuid_value, wait=None):
if self.connected:
raise HardwareError("Cannot connect when we are already connected")
if uuid_value not in self._scanned_devices:
self.scan(wait=wait)
with self._scan_lock:... | [
"Connect to a specific device by its uuid\n\n Attempt to connect to a device that we have previously scanned using its UUID.\n If wait is not None, then it is used in the same was a scan(wait) to override\n default wait times with an explicit value.\n\n Args:\n uuid_value (int... |
Please provide a description of the function:def connect_direct(self, connection_string, no_rpc=False, force=False):
if not force and self.connected:
raise HardwareError("Cannot connect when we are already connected to '%s'" % self.connection_string)
self._loop.run_coroutine(self.... | [
"Directly connect to a device using its stream specific connection string.\n\n Normally, all connections to a device include opening the RPC\n interface to send RPCs. However, there are certain, very specific,\n circumstances when you would not want to or be able to open the RPC\n inter... |
Please provide a description of the function:def disconnect(self):
if not self.connected:
raise HardwareError("Cannot disconnect when we are not connected")
# Close the streaming and tracing interfaces when we disconnect
self._reports = None
self._traces = None
... | [
"Disconnect from the device that we are currently connected to."
] |
Please provide a description of the function:def _try_reconnect(self):
try:
if self.connection_interrupted:
self.connect_direct(self.connection_string, force=True)
self.connection_interrupted = False
self.connected = True
# R... | [
"Try to recover an interrupted connection."
] |
Please provide a description of the function:def send_rpc(self, address, rpc_id, call_payload, timeout=3.0):
if not self.connected:
raise HardwareError("Cannot send an RPC if we are not in a connected state")
if timeout is None:
timeout = 3.0
status = -1
... | [
"Send an rpc to our connected device.\n\n The device must already be connected and the rpc interface open. This\n method will synchronously send an RPC and wait for the response. Any\n RPC errors will be raised as exceptions and if there were no errors, the\n RPC's response payload wil... |
Please provide a description of the function:def send_highspeed(self, data, progress_callback):
if not self.connected:
raise HardwareError("Cannot send a script if we are not in a connected state")
if isinstance(data, str) and not isinstance(data, bytes):
raise Argumen... | [
"Send a script to a device at highspeed, reporting progress.\n\n This method takes a binary blob and downloads it to the device as fast\n as possible, calling the passed progress_callback periodically with\n updates on how far it has gotten.\n\n Args:\n data (bytes): The binar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.