_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q238900
makeHierarchy
train
def makeHierarchy(sources): '''Break a list of files into a hierarchy; for each value, if it is a string, then it is a file. If it is a dictionary, it is a folder. The string is the original path of the file.''' hierarchy = {} for file in sources: path = splitFully(file) if ...
python
{ "resource": "" }
q238901
GenerateDSP
train
def GenerateDSP(dspfile, source, env): """Generates a Project file based on the version of MSVS that is being used""" version_num = 6.0 if 'MSVS_VERSION' in env: version_num, suite = msvs_parse_version(env['MSVS_VERSION']) if version_num >= 10.0: g = _GenerateV10DSP(dspfile, source, env...
python
{ "resource": "" }
q238902
solutionEmitter
train
def solutionEmitter(target, source, env): """Sets up the DSW dependencies.""" # todo: Not sure what sets source to what user has passed as target, # but this is what happens. When that is fixed, we also won't have # to make the user always append env['MSVSSOLUTIONSUFFIX'] to target. if source[0] ==...
python
{ "resource": "" }
q238903
generate
train
def generate(env): """Add Builders and construction variables for Microsoft Visual Studio project files to an Environment.""" try: env['BUILDERS']['MSVSProject'] except KeyError: env['BUILDERS']['MSVSProject'] = projectBuilder try: env['BUILDERS']['MSVSSolution'] except ...
python
{ "resource": "" }
q238904
_GenerateV6DSW.PrintWorkspace
train
def PrintWorkspace(self): """ writes a DSW file """ name = self.name dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path) self.file.write(V6DSWHeader % locals())
python
{ "resource": "" }
q238905
OperationManager.waiters
train
def waiters(self, path=None): """Iterate over all waiters. This method will return the waiters in unspecified order including the future or callback object that will be invoked and a list containing the keys/value that are being matched. Yields: list, future or call...
python
{ "resource": "" }
q238906
OperationManager.every_match
train
def every_match(self, callback, **kwargs): """Invoke callback every time a matching message is received. The callback will be invoked directly inside process_message so that you can guarantee that it has been called by the time process_message has returned. The callback can be ...
python
{ "resource": "" }
q238907
OperationManager.remove_waiter
train
def remove_waiter(self, waiter_handle): """Remove a message callback. This call will remove a callback previously registered using every_match. Args: waiter_handle (object): The opaque handle returned by the previous call to every_match(). """ ...
python
{ "resource": "" }
q238908
OperationManager.clear
train
def clear(self): """Clear all waiters. This method will remove any current scheduled waiter with an asyncio.CancelledError exception. """ for _, waiter in self.waiters(): if isinstance(waiter, asyncio.Future) and not waiter.done(): waiter.set_excepti...
python
{ "resource": "" }
q238909
OperationManager.wait_for
train
def wait_for(self, timeout=None, **kwargs): """Wait for a specific matching message or timeout. You specify the message by passing name=value keyword arguments to this method. The first message received after this function has been called that has all of the given keys with the given v...
python
{ "resource": "" }
q238910
OperationManager.process_message
train
async def process_message(self, message, wait=True): """Process a message to see if it wakes any waiters. This will check waiters registered to see if they match the given message. If so, they are awoken and passed the message. All matching waiters will be woken. This method ...
python
{ "resource": "" }
q238911
generate
train
def generate(env): """Add Builders and construction variables for zip to an Environment.""" try: bld = env['BUILDERS']['Zip'] except KeyError: bld = ZipBuilder env['BUILDERS']['Zip'] = bld env['ZIP'] = 'zip' env['ZIPFLAGS'] = SCons.Util.CLVar('') env['ZIPCOM'] ...
python
{ "resource": "" }
q238912
one_line_desc
train
def one_line_desc(obj): """Get a one line description of a class.""" logger = logging.getLogger(__name__) try: doc = ParsedDocstring(obj.__doc__) return doc.short_desc except: # pylint:disable=bare-except; We don't want a misbehaving exception to break the program logger.warni...
python
{ "resource": "" }
q238913
instantiate_device
train
def instantiate_device(virtual_dev, config, loop): """Find a virtual device by name and instantiate it Args: virtual_dev (string): The name of the pkg_resources entry point corresponding to the device. It should be in group iotile.virtual_device. If virtual_dev ends in .py, it...
python
{ "resource": "" }
q238914
instantiate_interface
train
def instantiate_interface(virtual_iface, config, loop): """Find a virtual interface by name and instantiate it Args: virtual_iface (string): The name of the pkg_resources entry point corresponding to the interface. It should be in group iotile.virtual_interface config (dict): A dic...
python
{ "resource": "" }
q238915
generate
train
def generate(env): """Add Builders and construction variables for tar to an Environment.""" try: bld = env['BUILDERS']['Tar'] except KeyError: bld = TarBuilder env['BUILDERS']['Tar'] = bld env['TAR'] = env.Detect(tars) or 'gtar' env['TARFLAGS'] = SCons.Util.CLVar('-...
python
{ "resource": "" }
q238916
AsyncValidatingWSServer.register_command
train
def register_command(self, name, handler, validator): """Register a coroutine command handler. This handler will be called whenever a command message is received from the client, whose operation key matches ``name``. The handler will be called as:: response_payload = await...
python
{ "resource": "" }
q238917
AsyncValidatingWSServer.start
train
async def start(self): """Start the websocket server. When this method returns, the websocket server will be running and the port property of this class will have its assigned port number. This method should be called only once in the lifetime of the server and must be paired w...
python
{ "resource": "" }
q238918
AsyncValidatingWSServer._run_server_task
train
async def _run_server_task(self, started_signal): """Create a BackgroundTask to manage the server. This allows subclasess to attach their server related tasks as subtasks that are properly cleaned up when this parent task is stopped and not require them all to overload start() and stop(...
python
{ "resource": "" }
q238919
AsyncValidatingWSServer.send_event
train
async def send_event(self, con, name, payload): """Send an event to a client connection. This method will push an event message to the client with the given name and payload. You need to have access to the the ``connection`` object for the client, which is only available once the clien...
python
{ "resource": "" }
q238920
DviPdfPsFunction
train
def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None): """A builder for DVI files that sets the TEXPICTS environment variable before running dvi2ps or dvipdf.""" try: abspath = source[0].attributes.path except AttributeError : abspath = '' saved_env = SCons....
python
{ "resource": "" }
q238921
PDFEmitter
train
def PDFEmitter(target, source, env): """Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file. """ def strip_suffixes(n): return n...
python
{ "resource": "" }
q238922
generate
train
def generate(env): """Add Builders and construction variables for dvipdf to an Environment.""" global PDFAction if PDFAction is None: PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR') global DVIPDFAction if DVIPDFAction is None: DVIPDFAction = SCons.Action.Action(DviPdf...
python
{ "resource": "" }
q238923
TimeBasedStopCondition.FromString
train
def FromString(cls, desc): """Parse this stop condition from a string representation. The string needs to match: run_time number [seconds|minutes|hours|days|months|years] Args: desc (str): The description Returns: TimeBasedStopCondition """ ...
python
{ "resource": "" }
q238924
collectintargz
train
def collectintargz(target, source, env): """ Puts all source files into a tar.gz file. """ # the rpm tool depends on a source package, until this is changed # this hack needs to be here that tries to pack all sources in. sources = env.FindSourceFiles() # filter out the target we are building the so...
python
{ "resource": "" }
q238925
build_specfile
train
def build_specfile(target, source, env): """ Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes. """ file = open(target[0].get_abspath(), 'w') try: file.write( build_specfile_header(env) ) file.write( build_specfile_sections(env) ) ...
python
{ "resource": "" }
q238926
build_specfile_sections
train
def build_specfile_sections(spec): """ Builds the sections of a rpm specfile. """ str = "" mandatory_sections = { 'DESCRIPTION' : '\n%%description\n%s\n\n', } str = str + SimpleTagCompiler(mandatory_sections).compile( spec ) optional_sections = { 'DESCRIPTION_' : '%%de...
python
{ "resource": "" }
q238927
build_specfile_header
train
def build_specfile_header(spec): """ Builds all sections but the %file of a rpm specfile """ str = "" # first the mandatory sections mandatory_header_fields = { 'NAME' : '%%define name %s\nName: %%{name}\n', 'VERSION' : '%%define version %s\nVersion: %%{version}\n',...
python
{ "resource": "" }
q238928
build_specfile_filesection
train
def build_specfile_filesection(spec, files): """ builds the %file section of the specfile """ str = '%files\n' if 'X_RPM_DEFATTR' not in spec: spec['X_RPM_DEFATTR'] = '(-,root,root)' str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR'] supported_tags = { 'PACKAGING_CONFIG' ...
python
{ "resource": "" }
q238929
SimpleTagCompiler.compile
train
def compile(self, values): """ Compiles the tagset and returns a str containing the result """ def is_international(tag): return tag.endswith('_') def get_country_code(tag): return tag[-2:] def strip_country_code(tag): return tag[:-2] ...
python
{ "resource": "" }
q238930
generate
train
def generate(env): """Add Builders and construction variables for ifl to an Environment.""" fscan = FortranScan("FORTRANPATH") SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILES...
python
{ "resource": "" }
q238931
generate
train
def generate(env): findIt('bcc32', env) """Add Builders and construction variables for bcc to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in ['.c', '.cpp']: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix...
python
{ "resource": "" }
q238932
require
train
def require(builder_name): """Find an advertised autobuilder and return it This function searches through all installed distributions to find if any advertise an entry point with group 'iotile.autobuild' and name equal to builder_name. The first one that is found is returned. This function raises...
python
{ "resource": "" }
q238933
autobuild_onlycopy
train
def autobuild_onlycopy(): """Autobuild a project that does not require building firmware, pcb or documentation """ try: # Build only release information family = utilities.get_family('module_settings.json') autobuild_release(family) Alias('release', os.path.join('build', 'ou...
python
{ "resource": "" }
q238934
autobuild_docproject
train
def autobuild_docproject(): """Autobuild a project that only contains documentation""" try: #Build only release information family = utilities.get_family('module_settings.json') autobuild_release(family) autobuild_documentation(family.tile) except unit_test.IOTileException a...
python
{ "resource": "" }
q238935
autobuild_arm_program
train
def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True): """ Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those. """ try: #Build for all targets family = utilities.get_family('module_settings.json'...
python
{ "resource": "" }
q238936
autobuild_doxygen
train
def autobuild_doxygen(tile): """Generate documentation for firmware in this module using doxygen""" iotile = IOTile('.') doxydir = os.path.join('build', 'doc') doxyfile = os.path.join(doxydir, 'doxygen.txt') outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id) env = Environment(EN...
python
{ "resource": "" }
q238937
autobuild_documentation
train
def autobuild_documentation(tile): """Generate documentation for this module using a combination of sphinx and breathe""" docdir = os.path.join('#doc') docfile = os.path.join(docdir, 'conf.py') outdir = os.path.join('build', 'output', 'doc', tile.unique_id) outfile = os.path.join(outdir, '%s.timest...
python
{ "resource": "" }
q238938
autobuild_bootstrap_file
train
def autobuild_bootstrap_file(file_name, image_list): """Combine multiple firmware images into a single bootstrap hex file. The files listed in image_list must be products of either this tile or any dependency tile and should correspond exactly with the base name listed on the products section of the mo...
python
{ "resource": "" }
q238939
Scope.add_identifier
train
def add_identifier(self, name, obj): """Add a known identifier resolution. Args: name (str): The name of the identifier obj (object): The object that is should resolve to """ name = str(name) self._known_identifiers[name] = obj
python
{ "resource": "" }
q238940
Scope.resolve_identifier
train
def resolve_identifier(self, name, expected_type=None): """Resolve an identifier to an object. There is a single namespace for identifiers so the user also should pass an expected type that will be checked against what the identifier actually resolves to so that there are no surprises. ...
python
{ "resource": "" }
q238941
SignedListReport.FromReadings
train
def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0): """Generate an instance of the report format from a list of readings and a uuid. The signed list report is creat...
python
{ "resource": "" }
q238942
SignedListReport.decode
train
def decode(self): """Decode this report into a list of readings """ fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \ origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20]) assert fmt == 1 length = (len_high << 8) ...
python
{ "resource": "" }
q238943
DeviceModel._add_property
train
def _add_property(self, name, default_value): """Add a device property with a given default value. Args: name (str): The name of the property to add default_value (int, bool): The value of the property """ name = str(name) self._properties[name] = defaul...
python
{ "resource": "" }
q238944
DeviceModel.set
train
def set(self, name, value): """Set a device model property. Args: name (str): The name of the property to set value (int, bool): The value of the property to set """ name = str(name) if name not in self._properties: raise ArgumentError("Unkno...
python
{ "resource": "" }
q238945
DeviceModel.get
train
def get(self, name): """Get a device model property. Args: name (str): The name of the property to get """ name = str(name) if name not in self._properties: raise ArgumentError("Unknown property in DeviceModel", name=name) return self._propertie...
python
{ "resource": "" }
q238946
_convert_to_bytes
train
def _convert_to_bytes(type_name, value): """Convert a typed value to a binary array""" int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'} type_name = type_name.lower() if type_name not in int_types and type_name not in ['string', 'binary']: ...
python
{ "resource": "" }
q238947
ConfigEntry.dump
train
def dump(self): """Serialize this object.""" return { 'target': str(self.target), 'data': base64.b64encode(self.data).decode('utf-8'), 'var_id': self.var_id, 'valid': self.valid }
python
{ "resource": "" }
q238948
ConfigEntry.generate_rpcs
train
def generate_rpcs(self, address): """Generate the RPCs needed to stream this config variable to a tile. Args: address (int): The address of the tile that we should stream to. Returns: list of tuples: A list of argument tuples for each RPC. These tuples can ...
python
{ "resource": "" }
q238949
ConfigEntry.Restore
train
def Restore(cls, state): """Unserialize this object.""" target = SlotIdentifier.FromString(state.get('target')) data = base64.b64decode(state.get('data')) var_id = state.get('var_id') valid = state.get('valid') return ConfigEntry(target, var_id, data, valid)
python
{ "resource": "" }
q238950
ConfigDatabase.compact
train
def compact(self): """Remove all invalid config entries.""" saved_length = 0 to_remove = [] for i, entry in enumerate(self.entries): if not entry.valid: to_remove.append(i) saved_length += entry.data_space() for i in reversed(to_remov...
python
{ "resource": "" }
q238951
ConfigDatabase.start_entry
train
def start_entry(self, target, var_id): """Begin a new config database entry. If there is a current entry in progress, it is aborted but the data was already committed to persistent storage so that space is wasted. Args: target (SlotIdentifer): The target slot for th...
python
{ "resource": "" }
q238952
ConfigDatabase.add_data
train
def add_data(self, data): """Add data to the currently in progress entry. Args: data (bytes): The data that we want to add. Returns: int: An error code """ if self.data_size - self.data_index < len(data): return Error.DESTINATION_BUFFER_TOO_...
python
{ "resource": "" }
q238953
ConfigDatabase.end_entry
train
def end_entry(self): """Finish a previously started config database entry. This commits the currently in progress entry. The expected flow is that start_entry() is called followed by 1 or more calls to add_data() followed by a single call to end_entry(). Returns: i...
python
{ "resource": "" }
q238954
ConfigDatabase.stream_matching
train
def stream_matching(self, address, name): """Return the RPCs needed to stream matching config variables to the given tile. This function will return a list of tuples suitable for passing to EmulatedDevice.deferred_rpc. Args: address (int): The address of the tile that we wi...
python
{ "resource": "" }
q238955
ConfigDatabase.add_direct
train
def add_direct(self, target, var_id, var_type, data): """Directly add a config variable. This method is meant to be called from emulation scenarios that want to directly set config database entries from python. Args: target (SlotIdentifer): The target slot for this config v...
python
{ "resource": "" }
q238956
ConfigDatabaseMixin.start_config_var_entry
train
def start_config_var_entry(self, var_id, encoded_selector): """Start a new config variable entry.""" selector = SlotIdentifier.FromEncoded(encoded_selector) err = self.config_database.start_entry(selector, var_id) return [err]
python
{ "resource": "" }
q238957
ConfigDatabaseMixin.get_config_var_entry
train
def get_config_var_entry(self, index): """Get the metadata from the selected config variable entry.""" if index == 0 or index > len(self.config_database.entries): return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0] entry = self.config_database.entries[index - 1] if not...
python
{ "resource": "" }
q238958
ConfigDatabaseMixin.get_config_var_data
train
def get_config_var_data(self, index, offset): """Get a chunk of data for a config variable.""" if index == 0 or index > len(self.config_database.entries): return [Error.INVALID_ARRAY_KEY, b''] entry = self.config_database.entries[index - 1] if not entry.valid: r...
python
{ "resource": "" }
q238959
ConfigDatabaseMixin.invalidate_config_var_entry
train
def invalidate_config_var_entry(self, index): """Mark a config variable as invalid.""" if index == 0 or index > len(self.config_database.entries): return [Error.INVALID_ARRAY_KEY, b''] entry = self.config_database.entries[index - 1] if not entry.valid: return [C...
python
{ "resource": "" }
q238960
ConfigDatabaseMixin.get_config_database_info
train
def get_config_database_info(self): """Get memory usage and space statistics on the config database.""" max_size = self.config_database.data_size max_entries = self.config_database.max_entries() used_size = self.config_database.data_index used_entries = len(self.config_database....
python
{ "resource": "" }
q238961
VirtualTile.FindByName
train
def FindByName(cls, name): """Find an installed VirtualTile by name. This function searches for installed virtual tiles using the pkg_resources entry_point `iotile.virtual_tile`. If name is a path ending in .py, it is assumed to point to a module on disk and loaded directly rat...
python
{ "resource": "" }
q238962
VirtualTile.LoadFromFile
train
def LoadFromFile(cls, script_path): """Import a virtual tile from a file rather than an installed module script_path must point to a python file ending in .py that contains exactly one VirtualTile class definition. That class is loaded and executed as if it were installed. To ...
python
{ "resource": "" }
q238963
PyPIReleaseProvider.stage
train
def stage(self): """Stage python packages for release, verifying everything we can about them.""" if 'PYPI_USER' not in os.environ or 'PYPI_PASS' not in os.environ: raise BuildError("You must set the PYPI_USER and PYPI_PASS environment variables") try: import twine ...
python
{ "resource": "" }
q238964
IOTileReportParser.add_data
train
def add_data(self, data): """Add data to our stream, emitting reports as each new one is seen Args: data (bytearray): A chunk of new data to add """ if self.state == self.ErrorState: return self.raw_data += bytearray(data) still_processing = Tr...
python
{ "resource": "" }
q238965
IOTileReportParser.process_data
train
def process_data(self): """Attempt to extract a report from the current data stream contents Returns: bool: True if further processing is required and process_data should be called again. """ further_processing = False if self.state == self.WaitingF...
python
{ "resource": "" }
q238966
IOTileReportParser.calculate_report_size
train
def calculate_report_size(self, current_type, report_header): """Determine the size of a report given its type and header""" fmt = self.known_formats[current_type] return fmt.ReportLength(report_header)
python
{ "resource": "" }
q238967
IOTileReportParser.parse_report
train
def parse_report(self, current_type, report_data): """Parse a report into an IOTileReport subclass""" fmt = self.known_formats[current_type] return fmt(report_data)
python
{ "resource": "" }
q238968
IOTileReportParser._handle_report
train
def _handle_report(self, report): """Try to emit a report and possibly keep a copy of it""" keep_report = True if self.report_callback is not None: keep_report = self.report_callback(report, self.context) if keep_report: self.reports.append(report)
python
{ "resource": "" }
q238969
_POInitBuilder
train
def _POInitBuilder(env, **kw): """ Create builder object for `POInit` builder. """ import SCons.Action from SCons.Tool.GettextCommon import _init_po_files, _POFileBuilder action = SCons.Action.Action(_init_po_files, None) return _POFileBuilder(env, action=action, target_alias='$POCREATE_ALIAS')
python
{ "resource": "" }
q238970
generate
train
def generate(env,**kw): """ Generate the `msginit` tool """ import SCons.Util from SCons.Tool.GettextCommon import _detect_msginit try: env['MSGINIT'] = _detect_msginit(env) except: env['MSGINIT'] = 'msginit' msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \ + ...
python
{ "resource": "" }
q238971
open_bled112
train
def open_bled112(port, logger): """Open a BLED112 adapter either by name or the first available.""" if port is not None and port != '<auto>': logger.info("Using BLED112 adapter at %s", port) return serial.Serial(port, _BAUD_RATE, timeout=0.01, rtscts=True, exclusive=True) return _find_avai...
python
{ "resource": "" }
q238972
NativeBLEDeviceAdapter._find_ble_controllers
train
def _find_ble_controllers(self): """Get a list of the available and powered BLE controllers""" controllers = self.bable.list_controllers() return [ctrl for ctrl in controllers if ctrl.powered and ctrl.low_energy]
python
{ "resource": "" }
q238973
NativeBLEDeviceAdapter.stop_scan
train
def stop_scan(self): """Stop to scan.""" try: self.bable.stop_scan(sync=True) except bable_interface.BaBLEException: # If we errored our it is because we were not currently scanning pass self.scanning = False
python
{ "resource": "" }
q238974
NativeBLEDeviceAdapter._open_rpc_interface
train
def _open_rpc_interface(self, connection_id, callback): """Enable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adap...
python
{ "resource": "" }
q238975
NativeBLEDeviceAdapter._open_streaming_interface
train
def _open_streaming_interface(self, connection_id, callback): """Enable streaming interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(c...
python
{ "resource": "" }
q238976
NativeBLEDeviceAdapter._open_tracing_interface
train
def _open_tracing_interface(self, connection_id, callback): """Enable the tracing interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(c...
python
{ "resource": "" }
q238977
NativeBLEDeviceAdapter._close_rpc_interface
train
def _close_rpc_interface(self, connection_id, callback): """Disable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, ad...
python
{ "resource": "" }
q238978
NativeBLEDeviceAdapter._on_report
train
def _on_report(self, report, connection_id): """Callback function called when a report has been processed. Args: report (IOTileReport): The report object connection_id (int): The connection id related to this report Returns: - True to indicate that IOTileRep...
python
{ "resource": "" }
q238979
NativeBLEDeviceAdapter._on_report_error
train
def _on_report_error(self, code, message, connection_id): """Callback function called if an error occured while parsing a report""" self._logger.critical( "Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s", code, message )
python
{ "resource": "" }
q238980
NativeBLEDeviceAdapter._register_notification_callback
train
def _register_notification_callback(self, connection_handle, attribute_handle, callback, once=False): """Register a callback as a notification callback. It will be called if a notification with the matching connection_handle and attribute_handle is received. Args: connection_handle ...
python
{ "resource": "" }
q238981
NativeBLEDeviceAdapter.periodic_callback
train
def periodic_callback(self): """Periodic cleanup tasks to maintain this adapter, should be called every second. """ if self.stopped: return # Check if we should start scanning again if not self.scanning and len(self.connections.get_connections()) == 0: self._log...
python
{ "resource": "" }
q238982
format_snippet
train
def format_snippet(sensor_graph): """Format this sensor graph as iotile command snippets. This includes commands to reset and clear previously stored sensor graphs. Args: sensor_graph (SensorGraph): the sensor graph that we want to format """ output = [] # Clear any old sensor gr...
python
{ "resource": "" }
q238983
BLED112Adapter.find_bled112_devices
train
def find_bled112_devices(cls): """Look for BLED112 dongles on this computer and start an instance on each one""" found_devs = [] ports = serial.tools.list_ports.comports() for port in ports: if not hasattr(port, 'pid') or not hasattr(port, 'vid'): continue ...
python
{ "resource": "" }
q238984
BLED112Adapter.get_scan_stats
train
def get_scan_stats(self): """Return the scan event statistics for this adapter Returns: int : total scan events int : total v1 scan count int : total v1 scan response count int : total v2 scan count dict : device-specific scan counts ...
python
{ "resource": "" }
q238985
BLED112Adapter.reset_scan_stats
train
def reset_scan_stats(self): """Clears the scan event statistics and updates the last reset time""" self._scan_event_count = 0 self._v1_scan_count = 0 self._v1_scan_response_count = 0 self._v2_scan_count = 0 self._device_scan_counts = {} self._last_reset_time = tim...
python
{ "resource": "" }
q238986
BLED112Adapter.start_scan
train
def start_scan(self, active): """Start the scanning task""" self._command_task.sync_command(['_start_scan', active]) self.scanning = True
python
{ "resource": "" }
q238987
BLED112Adapter._open_tracing_interface
train
def _open_tracing_interface(self, conn_id, callback): """Enable the debug tracing interface for this IOTile device Args: conn_id (int): the unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id...
python
{ "resource": "" }
q238988
BLED112Adapter._process_scan_event
train
def _process_scan_event(self, response): """Parse the BLE advertisement packet. If it's an IOTile device, parse and add to the scanned devices. Then, parse advertisement and determine if it matches V1 or V2. There are two supported type of advertisements: v1: There is both an ...
python
{ "resource": "" }
q238989
BLED112Adapter._parse_v2_advertisement
train
def _parse_v2_advertisement(self, rssi, sender, data): """ Parse the IOTile Specific advertisement packet""" if len(data) != 31: return # We have already verified that the device is an IOTile device # by checking its service data uuid in _process_scan_event so # her...
python
{ "resource": "" }
q238990
BLED112Adapter.probe_services
train
def probe_services(self, handle, conn_id, callback): """Given a connected device, probe for its GATT services and characteristics Args: handle (int): a handle to the connection on the BLED112 dongle conn_id (int): a unique identifier for this connection on the DeviceManager ...
python
{ "resource": "" }
q238991
BLED112Adapter.probe_characteristics
train
def probe_characteristics(self, conn_id, handle, services): """Probe a device for all characteristics defined in its GATT table This routine must be called after probe_services and passed the services dictionary produced by that method. Args: handle (int): a handle to the c...
python
{ "resource": "" }
q238992
BLED112Adapter._on_disconnect
train
def _on_disconnect(self, result): """Callback called when disconnection command finishes Args: result (dict): result returned from diconnection command """ success, _, context = self._parse_return(result) callback = context['callback'] connection_id = conte...
python
{ "resource": "" }
q238993
BLED112Adapter._parse_return
train
def _parse_return(cls, result): """Extract the result, return value and context from a result object """ return_value = None success = result['result'] context = result['context'] if 'return_value' in result: return_value = result['return_value'] re...
python
{ "resource": "" }
q238994
BLED112Adapter._get_connection
train
def _get_connection(self, handle, expect_state=None): """Get a connection object, logging an error if its in an unexpected state """ conndata = self._connections.get(handle) if conndata and expect_state is not None and conndata['state'] != expect_state: self._logger.error("...
python
{ "resource": "" }
q238995
BLED112Adapter._on_connection_finished
train
def _on_connection_finished(self, result): """Callback when the connection attempt to a BLE device has finished This function if called when a new connection is successfully completed Args: event (BGAPIPacket): Connection event """ success, retval, context = self._...
python
{ "resource": "" }
q238996
BLED112Adapter._on_connection_failed
train
def _on_connection_failed(self, conn_id, handle, clean, reason): """Callback called from another thread when a connection attempt has failed. """ with self.count_lock: self.connecting_count -= 1 self._logger.info("_on_connection_failed conn_id=%d, reason=%s", conn_id, str(r...
python
{ "resource": "" }
q238997
BLED112Adapter._probe_services_finished
train
def _probe_services_finished(self, result): """Callback called after a BLE device has had its GATT table completely probed Args: result (dict): Parameters determined by the probe and context passed to the call to probe_device() """ #If we were disconnected b...
python
{ "resource": "" }
q238998
BLED112Adapter._probe_characteristics_finished
train
def _probe_characteristics_finished(self, result): """Callback when BLE adapter has finished probing services and characteristics for a device Args: result (dict): Result from the probe_characteristics command """ handle = result['context']['handle'] conn_id = resul...
python
{ "resource": "" }
q238999
BLED112Adapter.periodic_callback
train
def periodic_callback(self): """Periodic cleanup tasks to maintain this adapter, should be called every second """ if self.stopped: return # Check if we should start scanning again if not self.scanning and len(self._connections) == 0 and self.connecting_count == 0: ...
python
{ "resource": "" }