_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q238000
get_modis_tile_list
train
def get_modis_tile_list(ds): """Helper function to identify MODIS tiles that intersect input geometry modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox) See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html """ from demcoreg import modis_grid modi...
python
{ "resource": "" }
q238001
get_modscag_fn_list
train
def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7): """Function to fetch and process MODSCAG fractional snow cover products for input datetime Products are tiled in MODIS sinusoidal projection example url: https://snow-data.jpl.nasa.gov/modscag-histor...
python
{ "resource": "" }
q238002
proc_modscag
train
def proc_modscag(fn_list, extent=None, t_srs=None): """Process the MODSCAG products for full date range, create composites and reproject """ #Use cubic spline here for improve upsampling ds_list = warplib.memwarp_multi_fn(fn_list, res='min', extent=extent, t_srs=t_srs, r='cubicspline') stack_fn = o...
python
{ "resource": "" }
q238003
TBDescriptor._value_length
train
def _value_length(self, value, t): """Given an integer or list of them, convert it to an array of bytes.""" if isinstance(value, int): fmt = '<%s' % (type_codes[t]) output = struct.pack(fmt, value) return len(output) elif isinstance(value, str): r...
python
{ "resource": "" }
q238004
TBDescriptor._parse_line
train
def _parse_line(self, line_no, line): """Parse a line in a TileBus file Args: line_no (int): The line number for printing useful error messages line (string): The line that we are trying to parse """ try: matched = statement.parseString(line) ...
python
{ "resource": "" }
q238005
TBDescriptor._validate_information
train
def _validate_information(self): """Validate that all information has been filled in""" needed_variables = ["ModuleName", "ModuleVersion", "APIVersion"] for var in needed_variables: if var not in self.variables: raise DataError("Needed variable was not defined in mi...
python
{ "resource": "" }
q238006
TBDescriptor.get_block
train
def get_block(self, config_only=False): """Create a TileBus Block based on the information in this descriptor""" mib = TBBlock() for cid, config in self.configs.items(): mib.add_config(cid, config) if not config_only: for key, val in self.commands.items(): ...
python
{ "resource": "" }
q238007
AggregatingDeviceAdapter.add_adapter
train
def add_adapter(self, adapter): """Add a device adapter to this aggregating adapter.""" if self._started: raise InternalError("New adapters cannot be added after start() is called") if isinstance(adapter, DeviceAdapter): self._logger.warning("Wrapping legacy device adap...
python
{ "resource": "" }
q238008
AggregatingDeviceAdapter.get_config
train
def get_config(self, name, default=_MISSING): """Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`. """ val = self._config.get(name, default) if val is _MISSING: raise ArgumentError("DeviceAdapter config {} did not exi...
python
{ "resource": "" }
q238009
AggregatingDeviceAdapter.start
train
async def start(self): """Start all adapters managed by this device adapter. If there is an error starting one or more adapters, this method will stop any adapters that we successfully started and raise an exception. """ successful = 0 try: for adapter in s...
python
{ "resource": "" }
q238010
AggregatingDeviceAdapter.visible_devices
train
def visible_devices(self): """Unify all visible devices across all connected adapters Returns: dict: A dictionary mapping UUIDs to device information dictionaries """ devs = {} for device_id, adapters in self._devices.items(): dev = None max...
python
{ "resource": "" }
q238011
AggregatingDeviceAdapter.probe
train
async def probe(self): """Probe for devices. This method will probe all adapters that can probe and will send a notification for all devices that we have seen from all adapters. See :meth:`AbstractDeviceAdapter.probe`. """ for adapter in self.adapters: if a...
python
{ "resource": "" }
q238012
AggregatingDeviceAdapter.send_script
train
async def send_script(self, conn_id, data): """Send a script to a device. See :meth:`AbstractDeviceAdapter.send_script`. """ adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_script(conn_id, data)
python
{ "resource": "" }
q238013
AggregatingDeviceAdapter.handle_adapter_event
train
async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): """Handle an event received from an adapter.""" if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, eve...
python
{ "resource": "" }
q238014
AggregatingDeviceAdapter._device_expiry_callback
train
def _device_expiry_callback(self): """Periodic callback to remove expired devices from visible_devices.""" expired = 0 for adapters in self._devices.values(): to_remove = [] now = monotonic() for adapter_id, dev in adapters.items(): if 'expir...
python
{ "resource": "" }
q238015
_PathVariableClass.PathIsDir
train
def PathIsDir(self, key, val, env): """Validator to check if Path is a directory.""" if not os.path.isdir(val): if os.path.isfile(val): m = 'Directory path for option %s is a file: %s' else: m = 'Directory path for option %s does not exist: %s' ...
python
{ "resource": "" }
q238016
_PathVariableClass.PathExists
train
def PathExists(self, key, val, env): """Validator to check if Path exists""" if not os.path.exists(val): m = 'Path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
python
{ "resource": "" }
q238017
SensorGraphSubsystem._reset_vector
train
async def _reset_vector(self): """Background task to initialize this system in the event loop.""" self._logger.debug("sensor_graph subsystem task starting") # If there is a persistent sgf loaded, send reset information. self.initialized.set() while True: stream, r...
python
{ "resource": "" }
q238018
SensorGraphSubsystem.process_input
train
def process_input(self, encoded_stream, value): """Process or drop a graph input. This method asynchronously queued an item to be processed by the sensorgraph worker task in _reset_vector. It must be called from inside the emulation loop and returns immediately before the input is ...
python
{ "resource": "" }
q238019
SensorGraphSubsystem._seek_streamer
train
def _seek_streamer(self, index, value): """Complex logic for actually seeking a streamer to a reading_id. This routine hides all of the gnarly logic of the various edge cases. In particular, the behavior depends on whether the reading id is found, and if it is found, whether it belongs ...
python
{ "resource": "" }
q238020
SensorGraphSubsystem.acknowledge_streamer
train
def acknowledge_streamer(self, index, ack, force): """Acknowledge a streamer value as received from the remote side.""" if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) old_ack = self.streamer_acks.get(index, 0) if ack !=...
python
{ "resource": "" }
q238021
SensorGraphSubsystem._handle_streamer_finished
train
def _handle_streamer_finished(self, index, succeeded, highest_ack): """Callback when a streamer finishes processing.""" self._logger.debug("Rolling back streamer %d after streaming, highest ack from streaming subsystem was %d", index, highest_ack) self.acknowledge_streamer(index, highest_ack, F...
python
{ "resource": "" }
q238022
SensorGraphSubsystem.process_streamers
train
def process_streamers(self): """Check if any streamers should be handed to the stream manager.""" # Check for any triggered streamers and pass them to stream manager in_progress = self._stream_manager.in_progress() triggered = self.graph.check_streamers(blacklist=in_progress) f...
python
{ "resource": "" }
q238023
SensorGraphSubsystem.trigger_streamer
train
def trigger_streamer(self, index): """Pass a streamer to the stream manager if it has data.""" self._logger.debug("trigger_streamer RPC called on streamer %d", index) if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) if in...
python
{ "resource": "" }
q238024
SensorGraphSubsystem.persist
train
def persist(self): """Trigger saving the current sensorgraph to persistent storage.""" self.persisted_nodes = self.graph.dump_nodes() self.persisted_streamers = self.graph.dump_streamers() self.persisted_exists = True self.persisted_constants = self._sensor_log.dump_constants()
python
{ "resource": "" }
q238025
SensorGraphSubsystem.reset
train
def reset(self): """Clear the sensorgraph from RAM and flash.""" self.persisted_exists = False self.persisted_nodes = [] self.persisted_streamers = [] self.persisted_constants = [] self.graph.clear() self.streamer_status = {}
python
{ "resource": "" }
q238026
SensorGraphSubsystem.add_node
train
def add_node(self, binary_descriptor): """Add a node to the sensor_graph using a binary node descriptor. Args: binary_descriptor (bytes): An encoded binary node descriptor. Returns: int: A packed error code. """ try: node_string = parse_bina...
python
{ "resource": "" }
q238027
SensorGraphSubsystem.add_streamer
train
def add_streamer(self, binary_descriptor): """Add a streamer to the sensor_graph using a binary streamer descriptor. Args: binary_descriptor (bytes): An encoded binary streamer descriptor. Returns: int: A packed error code """ streamer = streamer_descri...
python
{ "resource": "" }
q238028
SensorGraphSubsystem.inspect_streamer
train
def inspect_streamer(self, index): """Inspect the streamer at the given index.""" if index >= len(self.graph.streamers): return [_pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED), b'\0'*14] return [Error.NO_ERROR, streamer_descriptor.create_binary_descriptor(self.graph.streame...
python
{ "resource": "" }
q238029
SensorGraphSubsystem.inspect_node
train
def inspect_node(self, index): """Inspect the graph node at the given index.""" if index >= len(self.graph.nodes): raise RPCErrorCode(6) #FIXME: use actual error code here for UNKNOWN_ERROR status return create_binary_descriptor(str(self.graph.nodes[index]))
python
{ "resource": "" }
q238030
SensorGraphSubsystem.query_streamer
train
def query_streamer(self, index): """Query the status of the streamer at the given index.""" if index >= len(self.graph.streamers): return None info = self.streamer_status[index] highest_ack = self.streamer_acks.get(index, 0) return [info.last_attempt_time, info.las...
python
{ "resource": "" }
q238031
SensorGraphMixin.sg_graph_input
train
def sg_graph_input(self, value, stream_id): """"Present a graph input to the sensor_graph subsystem.""" self.sensor_graph.process_input(stream_id, value) return [Error.NO_ERROR]
python
{ "resource": "" }
q238032
SensorGraphMixin.sg_add_streamer
train
def sg_add_streamer(self, desc): """Add a graph streamer using a binary descriptor.""" if len(desc) == 13: desc += b'\0' err = self.sensor_graph.add_streamer(desc) return [err]
python
{ "resource": "" }
q238033
SensorGraphMixin.sg_seek_streamer
train
def sg_seek_streamer(self, index, force, value): """Ackowledge a streamer.""" force = bool(force) err = self.sensor_graph.acknowledge_streamer(index, value, force) return [err]
python
{ "resource": "" }
q238034
SensorGraphMixin.sg_query_streamer
train
def sg_query_streamer(self, index): """Query the current status of a streamer.""" resp = self.sensor_graph.query_streamer(index) if resp is None: return [struct.pack("<L", _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED))] return [struct.pack("<LLLLBBBx", *resp)]
python
{ "resource": "" }
q238035
WorkQueueThread.dispatch
train
def dispatch(self, value, callback=None): """Dispatch an item to the workqueue and optionally wait. This is the only way to add work to the background work queue. Unless you also pass a callback object, this method will synchronously wait for the work to finish and return the result. If...
python
{ "resource": "" }
q238036
WorkQueueThread.future_raise
train
def future_raise(self, tp, value=None, tb=None): """raise_ implementation from future.utils""" if value is not None and isinstance(tp, Exception): raise TypeError("instance exception may not have a separate value") if value is not None: exc = tp(value) else: ...
python
{ "resource": "" }
q238037
WorkQueueThread.flush
train
def flush(self): """Synchronously wait until this work item is processed. This has the effect of waiting until all work items queued before this method has been called have finished. """ done = threading.Event() def _callback(): done.set() self.def...
python
{ "resource": "" }
q238038
WorkQueueThread.direct_dispatch
train
def direct_dispatch(self, arg, callback): """Directly dispatch a work item. This method MUST only be called from inside of another work item and will synchronously invoke the work item as if it was passed to dispatch(). Calling this method from any other thread has undefined co...
python
{ "resource": "" }
q238039
WorkQueueThread.stop
train
def stop(self, timeout=None, force=False): """Stop the worker thread and synchronously wait for it to finish. Args: timeout (float): The maximum time to wait for the thread to stop before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError i...
python
{ "resource": "" }
q238040
WorkQueueThread.wait_stopped
train
def wait_stopped(self, timeout=None, force=False): """Wait for the thread to stop. You must have previously called signal_stop or this function will hang. Args: timeout (float): The maximum time to wait for the thread to stop before raising a TimeoutExpired...
python
{ "resource": "" }
q238041
generate
train
def generate(env): """Add Builders and construction variables for WiX to an Environment.""" if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXL...
python
{ "resource": "" }
q238042
SimulationStimulus.FromString
train
def FromString(cls, desc): """Create a new stimulus from a description string. The string must have the format: [time: ][system ]input X = Y where X and Y are integers. The time, if given must be a time_interval, which is an integer followed by a time unit such as seco...
python
{ "resource": "" }
q238043
ConnectionManager.get_connection_id
train
def get_connection_id(self, conn_or_int_id): """Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if ...
python
{ "resource": "" }
q238044
ConnectionManager._get_connection
train
def _get_connection(self, conn_or_int_id): """Get the data for a connection by either conn_id or internal_id Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data assoc...
python
{ "resource": "" }
q238045
ConnectionManager._get_connection_state
train
def _get_connection_state(self, conn_or_int_id): """Get a connection's state by either conn_id or internal_id This routine must only be called from the internal worker thread. Args: conn_or_int_id (int, string): The external integer connection id or and internal str...
python
{ "resource": "" }
q238046
ConnectionManager._check_timeouts
train
def _check_timeouts(self): """Check if any operations in progress need to be timed out Adds the corresponding finish action that fails the request due to a timeout. """ for conn_id, data in self._connections.items(): if 'timeout' in data and data['timeout'].expired:...
python
{ "resource": "" }
q238047
ConnectionManager.unexpected_disconnect
train
def unexpected_disconnect(self, conn_or_internal_id): """Notify that there was an unexpected disconnection of the device. Any in progress operations are canceled cleanly and the device is transitioned to a disconnected state. Args: conn_or_internal_id (string, int): Either ...
python
{ "resource": "" }
q238048
ConnectionManager.finish_operation
train
def finish_operation(self, conn_or_internal_id, success, *args): """Finish an operation on a connection. Args: conn_or_internal_id (string, int): Either an integer connection id or a string internal_id success (bool): Whether the operation was successful ...
python
{ "resource": "" }
q238049
ConnectionManager._finish_operation_action
train
def _finish_operation_action(self, action): """Finish an attempted operation. Args: action (ConnectionAction): the action object describing the result of the operation that we are finishing """ success = action.data['success'] conn_key = action.data[...
python
{ "resource": "" }
q238050
LaTeX.canonical_text
train
def canonical_text(self, text): """Standardize an input TeX-file contents. Currently: * removes comments, unwrapping comment-wrapped lines. """ out = [] line_continues_a_comment = False for line in text.splitlines(): line,comment = self.comment_re.f...
python
{ "resource": "" }
q238051
LaTeX.scan_recurse
train
def scan_recurse(self, node, path=()): """ do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does""" path_dict = dict(list(path)) queue = [] queue.extend( self.scan(node...
python
{ "resource": "" }
q238052
caller_trace
train
def caller_trace(back=0): """ Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution. """ global caller_bases, caller_dicts import traceback tb = traceback.extract_stack(limit=3+back) tb.reverse() callee = tb[1][:3] calle...
python
{ "resource": "" }
q238053
diff_dumps
train
def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3): """Diff 2 IntelHex objects and produce unified diff output for their hex dumps. @param ih1 first IntelHex object to compare @param ih2 second IntelHex object to compare @param tofile file-like object to writ...
python
{ "resource": "" }
q238054
IntelHex._decode_record
train
def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\r\n') if not s: return ...
python
{ "resource": "" }
q238055
IntelHex.loadhex
train
def loadhex(self, fobj): """Load hex file into internal buffer. This is not necessary if object was initialized with source set. This will overwrite addresses if object was already initialized. @param fobj file name or file-like object """ if getattr(fobj, "read"...
python
{ "resource": "" }
q238056
IntelHex.loadbin
train
def loadbin(self, fobj, offset=0): """Load bin file into internal buffer. Not needed if source set in constructor. This will overwrite addresses without warning if object was already initialized. @param fobj file name or file-like object @param offset starting addr...
python
{ "resource": "" }
q238057
IntelHex.loadfile
train
def loadfile(self, fobj, format): """Load data file into internal buffer. Preferred wrapper over loadbin or loadhex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == "hex": self.loadhex(fobj) ...
python
{ "resource": "" }
q238058
IntelHex._get_start_end
train
def _get_start_end(self, start=None, end=None, size=None): """Return default values for start and end if they are None. If this IntelHex object is empty then it's error to invoke this method with both start and end as None. """ if (start,end) == (None,None) and self._buf == {}: ...
python
{ "resource": "" }
q238059
IntelHex.tobinarray
train
def tobinarray(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert this object to binary form as array. If start and end unspecified, they will be inferred from the data. @param start start address of output bytes. @param end end address of output bytes (inclusiv...
python
{ "resource": "" }
q238060
IntelHex._tobinarray_really
train
def _tobinarray_really(self, start, end, pad, size): """Return binary array.""" if pad is None: pad = self.padding bin = array('B') if self._buf == {} and None in (start, end): return bin if size is not None and size <= 0: raise ValueError("tob...
python
{ "resource": "" }
q238061
IntelHex.tobinstr
train
def tobinstr(self, start=None, end=None, pad=_DEPRECATED, size=None): ''' Convert to binary form and return as binary string. @param start start address of output bytes. @param end end address of output bytes (inclusive). @param pad [DEPRECATED PARAMETER, please use self.pad...
python
{ "resource": "" }
q238062
IntelHex.tobinfile
train
def tobinfile(self, fobj, start=None, end=None, pad=_DEPRECATED, size=None): '''Convert to binary and write to file. @param fobj file name or file object for writing output bytes. @param start start address of output bytes. @param end end address of output bytes (inclusive)....
python
{ "resource": "" }
q238063
IntelHex.todict
train
def todict(self): '''Convert to python dictionary. @return dict suitable for initializing another IntelHex object. ''' r = {} r.update(self._buf) if self.start_addr: r['start_addr'] = self.start_addr return r
python
{ "resource": "" }
q238064
IntelHex.tofile
train
def tofile(self, fobj, format): """Write data to hex or bin file. Preferred method over tobin or tohex. @param fobj file name or file-like object @param format file format ("hex" or "bin") """ if format == 'hex': self.write_hex_file(fobj) elif f...
python
{ "resource": "" }
q238065
IntelHex.gets
train
def gets(self, addr, length): """Get string of bytes from given address. If any entries are blank from addr through addr+length, a NotEnoughDataError exception will be raised. Padding is not used. """ a = array('B', asbytes('\0'*length)) try: for i in range_g(...
python
{ "resource": "" }
q238066
IntelHex.puts
train
def puts(self, addr, s): """Put string of bytes at given address. Will overwrite any previous entries. """ a = array('B', asbytes(s)) for i in range_g(len(a)): self._buf[addr+i] = a[i]
python
{ "resource": "" }
q238067
IntelHex.getsz
train
def getsz(self, addr): """Get zero-terminated bytes string from given address. Will raise NotEnoughDataError exception if a hole is encountered before a 0. """ i = 0 try: while True: if self._buf[addr+i] == 0: break ...
python
{ "resource": "" }
q238068
IntelHex.putsz
train
def putsz(self, addr, s): """Put bytes string in object at addr and append terminating zero at end.""" self.puts(addr, s) self._buf[addr+len(s)] = 0
python
{ "resource": "" }
q238069
IntelHex.dump
train
def dump(self, tofile=None, width=16, withpadding=False): """Dump object content to specified file object or to stdout if None. Format is a hexdump with some header information at the beginning, addresses on the left, and data on right. @param tofile file-like object to dump t...
python
{ "resource": "" }
q238070
IntelHex.segments
train
def segments(self): """Return a list of ordered tuple objects, representing contiguous occupied data addresses. Each tuple has a length of two and follows the semantics of the range and xrange objects. The second entry of the tuple is always an integer greater than the first entry. """ ...
python
{ "resource": "" }
q238071
IntelHex.get_memory_size
train
def get_memory_size(self): """Returns the approximate memory footprint for data.""" n = sys.getsizeof(self) n += sys.getsizeof(self.padding) n += total_size(self.start_addr) n += total_size(self._buf) n += sys.getsizeof(self._offset) return n
python
{ "resource": "" }
q238072
Record._from_bytes
train
def _from_bytes(bytes): """Takes a list of bytes, computes the checksum, and outputs the entire record as a string. bytes should be the hex record without the colon or final checksum. @param bytes list of byte values so far to pack into record. @return String represen...
python
{ "resource": "" }
q238073
create_release_settings_action
train
def create_release_settings_action(target, source, env): """Copy module_settings.json and add release and build information """ with open(str(source[0]), "r") as fileobj: settings = json.load(fileobj) settings['release'] = True settings['release_date'] = datetime.datetime.utcnow().isoforma...
python
{ "resource": "" }
q238074
copy_extra_files
train
def copy_extra_files(tile): """Copy all files listed in a copy_files and copy_products section. Files listed in copy_files will be copied from the specified location in the current component to the specified path under the output folder. Files listed in copy_products will be looked up with a Produ...
python
{ "resource": "" }
q238075
generate
train
def generate(env): """Add Builders and construction variables for masm to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ASSuffixes: static_obj.add_action(suffix, SCons.Defaults.ASAction) shared_obj.add_action(suffix, SCons.Defaults.ASAction) ...
python
{ "resource": "" }
q238076
median
train
def median(values): """Return median value for the list of values. @param values: list of values for processing. @return: median value. """ values.sort() n = int(len(values) / 2) return values[n]
python
{ "resource": "" }
q238077
time_coef
train
def time_coef(tc, nc, tb, nb): """Return time coefficient relative to base numbers. @param tc: current test time @param nc: current test data size @param tb: base test time @param nb: base test data size @return: time coef. """ tc = float(tc) nc = float(nc)...
python
{ "resource": "" }
q238078
main
train
def main(argv=None): """Main function to run benchmarks. @param argv: command-line arguments. @return: exit code (0 is OK). """ import getopt # default values test_read = None test_write = None n = 3 # number of repeat if argv is None: argv = sys.argv[1:...
python
{ "resource": "" }
q238079
Measure.measure_one
train
def measure_one(self, data): """Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex) """ _unused, hexstr, ih = data tread, twrite = 0.0, 0.0 if self.read: tread = run_readte...
python
{ "resource": "" }
q238080
EnvAuthProvider._get_key
train
def _get_key(cls, device_id): """Attempt to get a user key from an environment variable """ var_name = "USER_KEY_{0:08X}".format(device_id) if var_name not in os.environ: raise NotFoundError("No user key could be found for devices", device_id=device_id, ...
python
{ "resource": "" }
q238081
EnvAuthProvider.decrypt_report
train
def decrypt_report(self, device_id, root, data, **kwargs): """Decrypt a buffer of report data on behalf of a device. Args: device_id (int): The id of the device that we should encrypt for root (int): The root key type that should be used to generate the report data (...
python
{ "resource": "" }
q238082
join_path
train
def join_path(path): """If given a string, return it, otherwise combine a list into a string using os.path.join""" if isinstance(path, str): return path return os.path.join(*path)
python
{ "resource": "" }
q238083
build_defines
train
def build_defines(defines): """Build a list of `-D` directives to pass to the compiler. This will drop any definitions whose value is None so that you can get rid of a define from another architecture by setting its value to null in the `module_settings.json`. """ return ['-D"%s=%s"' % (x, str...
python
{ "resource": "" }
q238084
AWSIOTDeviceAdapter._open_interface
train
def _open_interface(self, conn_id, iface, callback): """Open an interface on this device Args: conn_id (int): the unique identifier for the connection iface (string): the interface name to open callback (callback): Callback to be called when this command finishes ...
python
{ "resource": "" }
q238085
AWSIOTDeviceAdapter.stop_sync
train
def stop_sync(self): """Synchronously stop this adapter """ conn_ids = self.conns.get_connections() # If we have any open connections, try to close them here before shutting down for conn in list(conn_ids): try: self.disconnect_sync(conn) ...
python
{ "resource": "" }
q238086
AWSIOTDeviceAdapter.probe_async
train
def probe_async(self, callback): """Probe for visible devices connected to this DeviceAdapter. Args: callback (callable): A callback for when the probe operation has completed. callback should have signature callback(adapter_id, success, failure_reason) where: ...
python
{ "resource": "" }
q238087
AWSIOTDeviceAdapter.periodic_callback
train
def periodic_callback(self): """Periodically help maintain adapter internal state """ while True: try: action = self._deferred.get(False) action() except queue.Empty: break except Exception: self...
python
{ "resource": "" }
q238088
AWSIOTDeviceAdapter._bind_topics
train
def _bind_topics(self, topics): """Subscribe to all the topics we need to communication with this device Args: topics (MQTTTopicValidator): The topic validator for this device that we are connecting to. """ # FIXME: Allow for these subscriptions to fail and ...
python
{ "resource": "" }
q238089
AWSIOTDeviceAdapter._unbind_topics
train
def _unbind_topics(self, topics): """Unsubscribe to all of the topics we needed for communication with device Args: topics (MQTTTopicValidator): The topic validator for this device that we have connected to. """ self.client.unsubscribe(topics.status) ...
python
{ "resource": "" }
q238090
AWSIOTDeviceAdapter._find_connection
train
def _find_connection(self, topic): """Attempt to find a connection id corresponding with a topic The device is found by assuming the topic ends in <slug>/[control|data]/channel Args: topic (string): The topic we received a message on Returns: int: The internal ...
python
{ "resource": "" }
q238091
AWSIOTDeviceAdapter._on_report
train
def _on_report(self, sequence, topic, message): """Process a report received from 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 itself """ ...
python
{ "resource": "" }
q238092
AWSIOTDeviceAdapter._on_trace
train
def _on_trace(self, sequence, topic, message): """Process a trace received from 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 itself """ t...
python
{ "resource": "" }
q238093
AWSIOTDeviceAdapter._on_status_message
train
def _on_status_message(self, sequence, topic, message): """Process a status message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ ...
python
{ "resource": "" }
q238094
AWSIOTDeviceAdapter._on_response_message
train
def _on_response_message(self, sequence, topic, message): """Process a response message received Args: sequence (int): The sequence number of the packet received topic (string): The topic this message was received on message (dict): The message itself """ ...
python
{ "resource": "" }
q238095
write_output
train
def write_output(output, text=True, output_path=None): """Write binary or text output to a file or stdout.""" if output_path is None and text is False: print("ERROR: You must specify an output file using -o/--output for binary output formats") sys.exit(1) if output_path is not None: ...
python
{ "resource": "" }
q238096
main
train
def main(): """Main entry point for iotile-sgcompile.""" arg_parser = build_args() args = arg_parser.parse_args() model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(args.sensor_graph) if args.format == u'ast': write_output(parser.dump_tree(), True, args.outp...
python
{ "resource": "" }
q238097
load_external_components
train
def load_external_components(typesys): """Load all external types defined by iotile plugins. This allows plugins to register their own types for type annotations and allows all registered iotile components that have associated type libraries to add themselves to the global type system. """ # F...
python
{ "resource": "" }
q238098
RecipeManager.add_recipe_folder
train
def add_recipe_folder(self, recipe_folder, whitelist=None): """Add all recipes inside a folder to this RecipeManager with an optional whitelist. Args: recipe_folder (str): The path to the folder of recipes to add. whitelist (list): Only include files whose os.basename() matches ...
python
{ "resource": "" }
q238099
RecipeManager.add_recipe_actions
train
def add_recipe_actions(self, recipe_actions): """Add additional valid recipe actions to RecipeManager args: recipe_actions (list): List of tuples. First value of tuple is the classname, second value of tuple is RecipeAction Object """ for action_name, action...
python
{ "resource": "" }