id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
23,200
iotile/coretools
iotileemulate/iotile/emulate/internal/emulation_loop.py
EmulationLoop._clean_shutdown
async def _clean_shutdown(self): """Cleanly shutdown the emulation loop.""" # Cleanly stop any other outstanding tasks not associated with tiles remaining_tasks = [] for task in self._tasks.get(None, []): self._logger.debug("Cancelling task at shutdown %s", task) task.cancel() remaining_tasks.append(task) asyncio.gather(*remaining_tasks, return_exceptions=True) if len(remaining_tasks) > 0: del self._tasks[None] # Shutdown tasks associated with each tile remaining_tasks = [] for address in sorted(self._tasks, reverse=True): if address is None: continue self._logger.debug("Shutting down tasks for tile at %d", address) for task in self._tasks.get(address, []): task.cancel() remaining_tasks.append(task) asyncio.gather(*remaining_tasks, return_exceptions=True) await self._rpc_queue.stop() self._loop.stop()
python
async def _clean_shutdown(self): # Cleanly stop any other outstanding tasks not associated with tiles remaining_tasks = [] for task in self._tasks.get(None, []): self._logger.debug("Cancelling task at shutdown %s", task) task.cancel() remaining_tasks.append(task) asyncio.gather(*remaining_tasks, return_exceptions=True) if len(remaining_tasks) > 0: del self._tasks[None] # Shutdown tasks associated with each tile remaining_tasks = [] for address in sorted(self._tasks, reverse=True): if address is None: continue self._logger.debug("Shutting down tasks for tile at %d", address) for task in self._tasks.get(address, []): task.cancel() remaining_tasks.append(task) asyncio.gather(*remaining_tasks, return_exceptions=True) await self._rpc_queue.stop() self._loop.stop()
[ "async", "def", "_clean_shutdown", "(", "self", ")", ":", "# Cleanly stop any other outstanding tasks not associated with tiles", "remaining_tasks", "=", "[", "]", "for", "task", "in", "self", ".", "_tasks", ".", "get", "(", "None", ",", "[", "]", ")", ":", "sel...
Cleanly shutdown the emulation loop.
[ "Cleanly", "shutdown", "the", "emulation", "loop", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L451-L483
23,201
iotile/coretools
iotileemulate/iotile/emulate/internal/emulation_loop.py
EmulationLoop._add_task
def _add_task(self, tile_address, coroutine): """Add a task from within the event loop. All tasks are associated with a tile so that they can be cleanly stopped when that tile is reset. """ self.verify_calling_thread(True, "_add_task is not thread safe") if tile_address not in self._tasks: self._tasks[tile_address] = [] task = self._loop.create_task(coroutine) self._tasks[tile_address].append(task)
python
def _add_task(self, tile_address, coroutine): self.verify_calling_thread(True, "_add_task is not thread safe") if tile_address not in self._tasks: self._tasks[tile_address] = [] task = self._loop.create_task(coroutine) self._tasks[tile_address].append(task)
[ "def", "_add_task", "(", "self", ",", "tile_address", ",", "coroutine", ")", ":", "self", ".", "verify_calling_thread", "(", "True", ",", "\"_add_task is not thread safe\"", ")", "if", "tile_address", "not", "in", "self", ".", "_tasks", ":", "self", ".", "_tas...
Add a task from within the event loop. All tasks are associated with a tile so that they can be cleanly stopped when that tile is reset.
[ "Add", "a", "task", "from", "within", "the", "event", "loop", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/emulation_loop.py#L485-L498
23,202
iotile/coretools
iotilecore/iotile/core/utilities/schema_verify/dict_verify.py
DictionaryVerifier.key_rule
def key_rule(self, regex, verifier): """Add a rule with a pattern that should apply to all keys. Any key not explicitly listed in an add_required or add_optional rule must match ONE OF the rules given in a call to key_rule(). So these rules are all OR'ed together. In this case you should pass a raw string specifying a regex that is used to determine if the rule is used to check a given key. Args: regex (str): The regular expression used to match the rule or None if this should apply to all verifier (Verifier): The verification rule """ if regex is not None: regex = re.compile(regex) self._additional_key_rules.append((regex, verifier))
python
def key_rule(self, regex, verifier): if regex is not None: regex = re.compile(regex) self._additional_key_rules.append((regex, verifier))
[ "def", "key_rule", "(", "self", ",", "regex", ",", "verifier", ")", ":", "if", "regex", "is", "not", "None", ":", "regex", "=", "re", ".", "compile", "(", "regex", ")", "self", ".", "_additional_key_rules", ".", "append", "(", "(", "regex", ",", "ver...
Add a rule with a pattern that should apply to all keys. Any key not explicitly listed in an add_required or add_optional rule must match ONE OF the rules given in a call to key_rule(). So these rules are all OR'ed together. In this case you should pass a raw string specifying a regex that is used to determine if the rule is used to check a given key. Args: regex (str): The regular expression used to match the rule or None if this should apply to all verifier (Verifier): The verification rule
[ "Add", "a", "rule", "with", "a", "pattern", "that", "should", "apply", "to", "all", "keys", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/dict_verify.py#L43-L63
23,203
iotile/coretools
iotilecore/iotile/core/hw/transport/virtualadapter.py
VirtualAdapterAsyncChannel.stream
def stream(self, report, callback=None): """Queue data for streaming Args: report (IOTileReport): A report object to stream to a client callback (callable): An optional callback that will be called with a bool value of True when this report actually gets streamed. If the client disconnects and the report is dropped instead, callback will be called with False """ conn_id = self._find_connection(self.conn_string) if isinstance(report, BroadcastReport): self.adapter.notify_event_nowait(self.conn_string, 'broadcast', report) elif conn_id is not None: self.adapter.notify_event_nowait(self.conn_string, 'report', report) if callback is not None: callback(isinstance(report, BroadcastReport) or (conn_id is not None))
python
def stream(self, report, callback=None): conn_id = self._find_connection(self.conn_string) if isinstance(report, BroadcastReport): self.adapter.notify_event_nowait(self.conn_string, 'broadcast', report) elif conn_id is not None: self.adapter.notify_event_nowait(self.conn_string, 'report', report) if callback is not None: callback(isinstance(report, BroadcastReport) or (conn_id is not None))
[ "def", "stream", "(", "self", ",", "report", ",", "callback", "=", "None", ")", ":", "conn_id", "=", "self", ".", "_find_connection", "(", "self", ".", "conn_string", ")", "if", "isinstance", "(", "report", ",", "BroadcastReport", ")", ":", "self", ".", ...
Queue data for streaming Args: report (IOTileReport): A report object to stream to a client callback (callable): An optional callback that will be called with a bool value of True when this report actually gets streamed. If the client disconnects and the report is dropped instead, callback will be called with False
[ "Queue", "data", "for", "streaming" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/virtualadapter.py#L23-L42
23,204
iotile/coretools
iotilecore/iotile/core/hw/transport/virtualadapter.py
VirtualAdapterAsyncChannel.trace
def trace(self, data, callback=None): """Queue data for tracing Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): An optional callback that will be called with a bool value of True when this data actually gets traced. If the client disconnects and the data is dropped instead, callback will be called with False. """ conn_id = self._find_connection(self.conn_string) if conn_id is not None: self.adapter.notify_event_nowait(self.conn_string, 'trace', data) if callback is not None: callback(conn_id is not None)
python
def trace(self, data, callback=None): conn_id = self._find_connection(self.conn_string) if conn_id is not None: self.adapter.notify_event_nowait(self.conn_string, 'trace', data) if callback is not None: callback(conn_id is not None)
[ "def", "trace", "(", "self", ",", "data", ",", "callback", "=", "None", ")", ":", "conn_id", "=", "self", ".", "_find_connection", "(", "self", ".", "conn_string", ")", "if", "conn_id", "is", "not", "None", ":", "self", ".", "adapter", ".", "notify_eve...
Queue data for tracing Args: data (bytearray, string): Unstructured data to trace to any connected client. callback (callable): An optional callback that will be called with a bool value of True when this data actually gets traced. If the client disconnects and the data is dropped instead, callback will be called with False.
[ "Queue", "data", "for", "tracing" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/virtualadapter.py#L44-L62
23,205
iotile/coretools
iotilecore/iotile/core/hw/transport/virtualadapter.py
VirtualDeviceAdapter._load_device
def _load_device(self, name, config): """Load a device either from a script or from an installed module""" if config is None: config_dict = {} elif isinstance(config, dict): config_dict = config elif config[0] == '#': # Allow passing base64 encoded json directly in the port string to ease testing. import base64 config_str = str(base64.b64decode(config[1:]), 'utf-8') config_dict = json.loads(config_str) else: try: with open(config, "r") as conf: data = json.load(conf) except IOError as exc: raise ArgumentError("Could not open config file", error=str(exc), path=config) if 'device' not in data: raise ArgumentError("Invalid configuration file passed to VirtualDeviceAdapter", device_name=name, config_path=config, missing_key='device') config_dict = data['device'] reg = ComponentRegistry() if name.endswith('.py'): _name, device_factory = reg.load_extension(name, class_filter=VirtualIOTileDevice, unique=True) return device_factory(config_dict) seen_names = [] for device_name, device_factory in reg.load_extensions('iotile.virtual_device', class_filter=VirtualIOTileDevice, product_name="virtual_device"): if device_name == name: return device_factory(config_dict) seen_names.append(device_name) raise ArgumentError("Could not find virtual_device by name", name=name, known_names=seen_names)
python
def _load_device(self, name, config): if config is None: config_dict = {} elif isinstance(config, dict): config_dict = config elif config[0] == '#': # Allow passing base64 encoded json directly in the port string to ease testing. import base64 config_str = str(base64.b64decode(config[1:]), 'utf-8') config_dict = json.loads(config_str) else: try: with open(config, "r") as conf: data = json.load(conf) except IOError as exc: raise ArgumentError("Could not open config file", error=str(exc), path=config) if 'device' not in data: raise ArgumentError("Invalid configuration file passed to VirtualDeviceAdapter", device_name=name, config_path=config, missing_key='device') config_dict = data['device'] reg = ComponentRegistry() if name.endswith('.py'): _name, device_factory = reg.load_extension(name, class_filter=VirtualIOTileDevice, unique=True) return device_factory(config_dict) seen_names = [] for device_name, device_factory in reg.load_extensions('iotile.virtual_device', class_filter=VirtualIOTileDevice, product_name="virtual_device"): if device_name == name: return device_factory(config_dict) seen_names.append(device_name) raise ArgumentError("Could not find virtual_device by name", name=name, known_names=seen_names)
[ "def", "_load_device", "(", "self", ",", "name", ",", "config", ")", ":", "if", "config", "is", "None", ":", "config_dict", "=", "{", "}", "elif", "isinstance", "(", "config", ",", "dict", ")", ":", "config_dict", "=", "config", "elif", "config", "[", ...
Load a device either from a script or from an installed module
[ "Load", "a", "device", "either", "from", "a", "script", "or", "from", "an", "installed", "module" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/virtualadapter.py#L172-L212
23,206
iotile/coretools
iotilecore/iotile/core/hw/transport/virtualadapter.py
VirtualDeviceAdapter.disconnect
async def disconnect(self, conn_id): """Asynchronously disconnect from a connected device Args: conn_id (int): A unique identifier that will refer to this connection callback (callback): A callback that will be called as callback(conn_id, adapter_id, success, failure_reason) """ self._ensure_connection(conn_id, True) dev = self._get_property(conn_id, 'device') dev.connected = False self._teardown_connection(conn_id)
python
async def disconnect(self, conn_id): self._ensure_connection(conn_id, True) dev = self._get_property(conn_id, 'device') dev.connected = False self._teardown_connection(conn_id)
[ "async", "def", "disconnect", "(", "self", ",", "conn_id", ")", ":", "self", ".", "_ensure_connection", "(", "conn_id", ",", "True", ")", "dev", "=", "self", ".", "_get_property", "(", "conn_id", ",", "'device'", ")", "dev", ".", "connected", "=", "False...
Asynchronously disconnect from a connected device Args: conn_id (int): A unique identifier that will refer to this connection callback (callback): A callback that will be called as callback(conn_id, adapter_id, success, failure_reason)
[ "Asynchronously", "disconnect", "from", "a", "connected", "device" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/virtualadapter.py#L247-L261
23,207
iotile/coretools
iotilecore/iotile/core/hw/transport/virtualadapter.py
VirtualDeviceAdapter._send_scan_event
async def _send_scan_event(self, device): """Send a scan event from a device.""" conn_string = str(device.iotile_id) info = { 'connection_string': conn_string, 'uuid': device.iotile_id, 'signal_strength': 100, 'validity_period': self.ExpirationTime } await self.notify_event(conn_string, 'device_seen', info)
python
async def _send_scan_event(self, device): conn_string = str(device.iotile_id) info = { 'connection_string': conn_string, 'uuid': device.iotile_id, 'signal_strength': 100, 'validity_period': self.ExpirationTime } await self.notify_event(conn_string, 'device_seen', info)
[ "async", "def", "_send_scan_event", "(", "self", ",", "device", ")", ":", "conn_string", "=", "str", "(", "device", ".", "iotile_id", ")", "info", "=", "{", "'connection_string'", ":", "conn_string", ",", "'uuid'", ":", "device", ".", "iotile_id", ",", "'s...
Send a scan event from a device.
[ "Send", "a", "scan", "event", "from", "a", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/virtualadapter.py#L369-L380
23,208
iotile/coretools
iotileemulate/iotile/emulate/constants/__init__.py
rpc_name
def rpc_name(rpc_id): """Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of the RPC that we wish to look up. Returns: str: The nice name of the RPC. """ name = _RPC_NAME_MAP.get(rpc_id) if name is None: name = 'RPC 0x%04X' % rpc_id return name
python
def rpc_name(rpc_id): name = _RPC_NAME_MAP.get(rpc_id) if name is None: name = 'RPC 0x%04X' % rpc_id return name
[ "def", "rpc_name", "(", "rpc_id", ")", ":", "name", "=", "_RPC_NAME_MAP", ".", "get", "(", "rpc_id", ")", "if", "name", "is", "None", ":", "name", "=", "'RPC 0x%04X'", "%", "rpc_id", "return", "name" ]
Map an RPC id to a string name. This function looks the RPC up in a map of all globally declared RPCs, and returns a nice name string. if the RPC is not found in the global name map, returns a generic name string such as 'rpc 0x%04X'. Args: rpc_id (int): The id of the RPC that we wish to look up. Returns: str: The nice name of the RPC.
[ "Map", "an", "RPC", "id", "to", "a", "string", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/constants/__init__.py#L18-L36
23,209
iotile/coretools
iotileemulate/iotile/emulate/constants/__init__.py
stream_name
def stream_name(stream_id): """Map a stream id to a human readable name. The mapping process is as follows: If the stream id is globally known, its global name is used as <name> otherwise a string representation of the stream is used as <name>. In both cases the hex representation of the stream id is appended as a number: <name> (0x<stream id in hex>) Args: stream_id (int): An integer stream id. Returns: str: The nice name of the stream. """ name = _STREAM_NAME_MAP.get(stream_id) if name is None: name = str(DataStream.FromEncoded(stream_id)) return "{} (0x{:04X})".format(name, stream_id)
python
def stream_name(stream_id): name = _STREAM_NAME_MAP.get(stream_id) if name is None: name = str(DataStream.FromEncoded(stream_id)) return "{} (0x{:04X})".format(name, stream_id)
[ "def", "stream_name", "(", "stream_id", ")", ":", "name", "=", "_STREAM_NAME_MAP", ".", "get", "(", "stream_id", ")", "if", "name", "is", "None", ":", "name", "=", "str", "(", "DataStream", ".", "FromEncoded", "(", "stream_id", ")", ")", "return", "\"{} ...
Map a stream id to a human readable name. The mapping process is as follows: If the stream id is globally known, its global name is used as <name> otherwise a string representation of the stream is used as <name>. In both cases the hex representation of the stream id is appended as a number: <name> (0x<stream id in hex>) Args: stream_id (int): An integer stream id. Returns: str: The nice name of the stream.
[ "Map", "a", "stream", "id", "to", "a", "human", "readable", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/constants/__init__.py#L39-L63
23,210
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py
SConsValues.set_option
def set_option(self, name, value): """ Sets an option from an SConscript file. """ if not name in self.settable: raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name) if name == 'num_jobs': try: value = int(value) if value < 1: raise ValueError except ValueError: raise SCons.Errors.UserError("A positive integer is required: %s"%repr(value)) elif name == 'max_drift': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'duplicate': try: value = str(value) except ValueError: raise SCons.Errors.UserError("A string is required: %s"%repr(value)) if not value in SCons.Node.FS.Valid_Duplicates: raise SCons.Errors.UserError("Not a valid duplication style: %s" % value) # Set the duplicate style right away so it can affect linking # of SConscript files. SCons.Node.FS.set_duplicate(value) elif name == 'diskcheck': try: value = diskcheck_convert(value) except ValueError as v: raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v) if 'diskcheck' not in self.__dict__: # No --diskcheck= option was specified on the command line. # Set this right away so it can affect the rest of the # file/Node lookups while processing the SConscript files. SCons.Node.FS.set_diskcheck(value) elif name == 'stack_size': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'md5_chunksize': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'warn': if SCons.Util.is_String(value): value = [value] value = self.__SConscript_settings__.get(name, []) + value SCons.Warnings.process_warn_strings(value) self.__SConscript_settings__[name] = value
python
def set_option(self, name, value): if not name in self.settable: raise SCons.Errors.UserError("This option is not settable from a SConscript file: %s"%name) if name == 'num_jobs': try: value = int(value) if value < 1: raise ValueError except ValueError: raise SCons.Errors.UserError("A positive integer is required: %s"%repr(value)) elif name == 'max_drift': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'duplicate': try: value = str(value) except ValueError: raise SCons.Errors.UserError("A string is required: %s"%repr(value)) if not value in SCons.Node.FS.Valid_Duplicates: raise SCons.Errors.UserError("Not a valid duplication style: %s" % value) # Set the duplicate style right away so it can affect linking # of SConscript files. SCons.Node.FS.set_duplicate(value) elif name == 'diskcheck': try: value = diskcheck_convert(value) except ValueError as v: raise SCons.Errors.UserError("Not a valid diskcheck value: %s"%v) if 'diskcheck' not in self.__dict__: # No --diskcheck= option was specified on the command line. # Set this right away so it can affect the rest of the # file/Node lookups while processing the SConscript files. SCons.Node.FS.set_diskcheck(value) elif name == 'stack_size': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'md5_chunksize': try: value = int(value) except ValueError: raise SCons.Errors.UserError("An integer is required: %s"%repr(value)) elif name == 'warn': if SCons.Util.is_String(value): value = [value] value = self.__SConscript_settings__.get(name, []) + value SCons.Warnings.process_warn_strings(value) self.__SConscript_settings__[name] = value
[ "def", "set_option", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "name", "in", "self", ".", "settable", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"This option is not settable from a SConscript file: %s\"", "%", "name", "...
Sets an option from an SConscript file.
[ "Sets", "an", "option", "from", "an", "SConscript", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py#L145-L200
23,211
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py
SConsOptionGroup.format_help
def format_help(self, formatter): """ Format an option group's help text, outdenting the title so it's flush with the "SCons Options" title we print at the top. """ formatter.dedent() result = formatter.format_heading(self.title) formatter.indent() result = result + optparse.OptionContainer.format_help(self, formatter) return result
python
def format_help(self, formatter): formatter.dedent() result = formatter.format_heading(self.title) formatter.indent() result = result + optparse.OptionContainer.format_help(self, formatter) return result
[ "def", "format_help", "(", "self", ",", "formatter", ")", ":", "formatter", ".", "dedent", "(", ")", "result", "=", "formatter", ".", "format_heading", "(", "self", ".", "title", ")", "formatter", ".", "indent", "(", ")", "result", "=", "result", "+", ...
Format an option group's help text, outdenting the title so it's flush with the "SCons Options" title we print at the top.
[ "Format", "an", "option", "group", "s", "help", "text", "outdenting", "the", "title", "so", "it", "s", "flush", "with", "the", "SCons", "Options", "title", "we", "print", "at", "the", "top", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py#L270-L279
23,212
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py
SConsOptionParser._process_long_opt
def _process_long_opt(self, rargs, values): """ SCons-specific processing of long options. This is copied directly from the normal optparse._process_long_opt() method, except that, if configured to do so, we catch the exception thrown when an unknown option is encountered and just stick it back on the "leftover" arguments for later (re-)processing. """ arg = rargs.pop(0) # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: (opt, next_arg) = arg.split("=", 1) rargs.insert(0, next_arg) had_explicit_value = True else: opt = arg had_explicit_value = False try: opt = self._match_long_opt(opt) except optparse.BadOptionError: if self.preserve_unknown_options: # SCons-specific: if requested, add unknown options to # the "leftover arguments" list for later processing. self.largs.append(arg) if had_explicit_value: # The unknown option will be re-processed later, # so undo the insertion of the explicit value. rargs.pop(0) return raise option = self._long_opt[opt] if option.takes_value(): nargs = option.nargs if nargs == '?': if had_explicit_value: value = rargs.pop(0) else: value = option.const elif len(rargs) < nargs: if nargs == 1: if not option.choices: self.error(_("%s option requires an argument") % opt) else: msg = _("%s option requires an argument " % opt) msg += _("(choose from %s)" % ', '.join(option.choices)) self.error(msg) else: self.error(_("%s option requires %d arguments") % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] elif had_explicit_value: self.error(_("%s option does not take a value") % opt) else: value = None option.process(opt, value, values, self)
python
def _process_long_opt(self, rargs, values): arg = rargs.pop(0) # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: (opt, next_arg) = arg.split("=", 1) rargs.insert(0, next_arg) had_explicit_value = True else: opt = arg had_explicit_value = False try: opt = self._match_long_opt(opt) except optparse.BadOptionError: if self.preserve_unknown_options: # SCons-specific: if requested, add unknown options to # the "leftover arguments" list for later processing. self.largs.append(arg) if had_explicit_value: # The unknown option will be re-processed later, # so undo the insertion of the explicit value. rargs.pop(0) return raise option = self._long_opt[opt] if option.takes_value(): nargs = option.nargs if nargs == '?': if had_explicit_value: value = rargs.pop(0) else: value = option.const elif len(rargs) < nargs: if nargs == 1: if not option.choices: self.error(_("%s option requires an argument") % opt) else: msg = _("%s option requires an argument " % opt) msg += _("(choose from %s)" % ', '.join(option.choices)) self.error(msg) else: self.error(_("%s option requires %d arguments") % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] elif had_explicit_value: self.error(_("%s option does not take a value") % opt) else: value = None option.process(opt, value, values, self)
[ "def", "_process_long_opt", "(", "self", ",", "rargs", ",", "values", ")", ":", "arg", "=", "rargs", ".", "pop", "(", "0", ")", "# Value explicitly attached to arg? Pretend it's the next", "# argument.", "if", "\"=\"", "in", "arg", ":", "(", "opt", ",", "next...
SCons-specific processing of long options. This is copied directly from the normal optparse._process_long_opt() method, except that, if configured to do so, we catch the exception thrown when an unknown option is encountered and just stick it back on the "leftover" arguments for later (re-)processing.
[ "SCons", "-", "specific", "processing", "of", "long", "options", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py#L290-L358
23,213
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py
SConsOptionParser.add_local_option
def add_local_option(self, *args, **kw): """ Adds a local option to the parser. This is initiated by a SetOption() call to add a user-defined command-line option. We add the option to a separate option group for the local options, creating the group if necessary. """ try: group = self.local_option_group except AttributeError: group = SConsOptionGroup(self, 'Local Options') group = self.add_option_group(group) self.local_option_group = group result = group.add_option(*args, **kw) if result: # The option was added successfully. We now have to add the # default value to our object that holds the default values # (so that an attempt to fetch the option's attribute will # yield the default value when not overridden) and then # we re-parse the leftover command-line options, so that # any value overridden on the command line is immediately # available if the user turns around and does a GetOption() # right away. setattr(self.values.__defaults__, result.dest, result.default) self.reparse_local_options() return result
python
def add_local_option(self, *args, **kw): try: group = self.local_option_group except AttributeError: group = SConsOptionGroup(self, 'Local Options') group = self.add_option_group(group) self.local_option_group = group result = group.add_option(*args, **kw) if result: # The option was added successfully. We now have to add the # default value to our object that holds the default values # (so that an attempt to fetch the option's attribute will # yield the default value when not overridden) and then # we re-parse the leftover command-line options, so that # any value overridden on the command line is immediately # available if the user turns around and does a GetOption() # right away. setattr(self.values.__defaults__, result.dest, result.default) self.reparse_local_options() return result
[ "def", "add_local_option", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "try", ":", "group", "=", "self", ".", "local_option_group", "except", "AttributeError", ":", "group", "=", "SConsOptionGroup", "(", "self", ",", "'Local Options'", ")...
Adds a local option to the parser. This is initiated by a SetOption() call to add a user-defined command-line option. We add the option to a separate option group for the local options, creating the group if necessary.
[ "Adds", "a", "local", "option", "to", "the", "parser", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py#L425-L454
23,214
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py
SConsIndentedHelpFormatter.format_heading
def format_heading(self, heading): """ This translates any heading of "options" or "Options" into "SCons Options." Unfortunately, we have to do this here, because those titles are hard-coded in the optparse calls. """ if heading == 'Options': heading = "SCons Options" return optparse.IndentedHelpFormatter.format_heading(self, heading)
python
def format_heading(self, heading): if heading == 'Options': heading = "SCons Options" return optparse.IndentedHelpFormatter.format_heading(self, heading)
[ "def", "format_heading", "(", "self", ",", "heading", ")", ":", "if", "heading", "==", "'Options'", ":", "heading", "=", "\"SCons Options\"", "return", "optparse", ".", "IndentedHelpFormatter", ".", "format_heading", "(", "self", ",", "heading", ")" ]
This translates any heading of "options" or "Options" into "SCons Options." Unfortunately, we have to do this here, because those titles are hard-coded in the optparse calls.
[ "This", "translates", "any", "heading", "of", "options", "or", "Options", "into", "SCons", "Options", ".", "Unfortunately", "we", "have", "to", "do", "this", "here", "because", "those", "titles", "are", "hard", "-", "coded", "in", "the", "optparse", "calls",...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConsOptions.py#L460-L468
23,215
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.to_dict
def to_dict(self): """Convert this object into a dictionary. Returns: dict: A dict with the same information as this object. """ out_dict = {} out_dict['commands'] = self.commands out_dict['configs'] = self.configs out_dict['short_name'] = self.name out_dict['versions'] = { 'module': self.module_version, 'api': self.api_version } return out_dict
python
def to_dict(self): out_dict = {} out_dict['commands'] = self.commands out_dict['configs'] = self.configs out_dict['short_name'] = self.name out_dict['versions'] = { 'module': self.module_version, 'api': self.api_version } return out_dict
[ "def", "to_dict", "(", "self", ")", ":", "out_dict", "=", "{", "}", "out_dict", "[", "'commands'", "]", "=", "self", ".", "commands", "out_dict", "[", "'configs'", "]", "=", "self", ".", "configs", "out_dict", "[", "'short_name'", "]", "=", "self", "."...
Convert this object into a dictionary. Returns: dict: A dict with the same information as this object.
[ "Convert", "this", "object", "into", "a", "dictionary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L46-L63
23,216
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.set_api_version
def set_api_version(self, major, minor): """Set the API version this module was designed for. Each module must declare the mib12 API version it was compiled with as a 2 byte major.minor number. This information is used by the pic12_executive to decide whether the application is compatible. """ if not self._is_byte(major) or not self._is_byte(minor): raise ArgumentError("Invalid API version number with component that does not fit in 1 byte", major=major, minor=minor) self.api_version = (major, minor)
python
def set_api_version(self, major, minor): if not self._is_byte(major) or not self._is_byte(minor): raise ArgumentError("Invalid API version number with component that does not fit in 1 byte", major=major, minor=minor) self.api_version = (major, minor)
[ "def", "set_api_version", "(", "self", ",", "major", ",", "minor", ")", ":", "if", "not", "self", ".", "_is_byte", "(", "major", ")", "or", "not", "self", ".", "_is_byte", "(", "minor", ")", ":", "raise", "ArgumentError", "(", "\"Invalid API version number...
Set the API version this module was designed for. Each module must declare the mib12 API version it was compiled with as a 2 byte major.minor number. This information is used by the pic12_executive to decide whether the application is compatible.
[ "Set", "the", "API", "version", "this", "module", "was", "designed", "for", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L69-L81
23,217
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.set_module_version
def set_module_version(self, major, minor, patch): """Set the module version for this module. Each module must declare a semantic version number in the form: major.minor.patch where each component is a 1 byte number between 0 and 255. """ if not (self._is_byte(major) and self._is_byte(minor) and self._is_byte(patch)): raise ArgumentError("Invalid module version number with component that does not fit in 1 byte", major=major, minor=minor, patch=patch) self.module_version = (major, minor, patch)
python
def set_module_version(self, major, minor, patch): if not (self._is_byte(major) and self._is_byte(minor) and self._is_byte(patch)): raise ArgumentError("Invalid module version number with component that does not fit in 1 byte", major=major, minor=minor, patch=patch) self.module_version = (major, minor, patch)
[ "def", "set_module_version", "(", "self", ",", "major", ",", "minor", ",", "patch", ")", ":", "if", "not", "(", "self", ".", "_is_byte", "(", "major", ")", "and", "self", ".", "_is_byte", "(", "minor", ")", "and", "self", ".", "_is_byte", "(", "patch...
Set the module version for this module. Each module must declare a semantic version number in the form: major.minor.patch where each component is a 1 byte number between 0 and 255.
[ "Set", "the", "module", "version", "for", "this", "module", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L83-L96
23,218
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.set_name
def set_name(self, name): """Set the module name to a 6 byte string If the string is too short it is appended with space characters. """ if len(name) > 6: raise ArgumentError("Name must be at most 6 characters long", name=name) if len(name) < 6: name += ' '*(6 - len(name)) self.name = name
python
def set_name(self, name): if len(name) > 6: raise ArgumentError("Name must be at most 6 characters long", name=name) if len(name) < 6: name += ' '*(6 - len(name)) self.name = name
[ "def", "set_name", "(", "self", ",", "name", ")", ":", "if", "len", "(", "name", ")", ">", "6", ":", "raise", "ArgumentError", "(", "\"Name must be at most 6 characters long\"", ",", "name", "=", "name", ")", "if", "len", "(", "name", ")", "<", "6", ":...
Set the module name to a 6 byte string If the string is too short it is appended with space characters.
[ "Set", "the", "module", "name", "to", "a", "6", "byte", "string" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L98-L110
23,219
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.add_command
def add_command(self, cmd_id, handler): """Add a command to the TBBlock. The cmd_id must be a non-negative 2 byte number. handler should be the command handler """ if cmd_id < 0 or cmd_id >= 2**16: raise ArgumentError("Command ID in mib block is not a non-negative 2-byte number", cmd_id=cmd_id, handler=handler) if cmd_id in self.commands: raise ArgumentError("Attempted to add the same command ID twice.", cmd_id=cmd_id, existing_handler=self.commands[cmd_id], new_handler=handler) self.commands[cmd_id] = handler
python
def add_command(self, cmd_id, handler): if cmd_id < 0 or cmd_id >= 2**16: raise ArgumentError("Command ID in mib block is not a non-negative 2-byte number", cmd_id=cmd_id, handler=handler) if cmd_id in self.commands: raise ArgumentError("Attempted to add the same command ID twice.", cmd_id=cmd_id, existing_handler=self.commands[cmd_id], new_handler=handler) self.commands[cmd_id] = handler
[ "def", "add_command", "(", "self", ",", "cmd_id", ",", "handler", ")", ":", "if", "cmd_id", "<", "0", "or", "cmd_id", ">=", "2", "**", "16", ":", "raise", "ArgumentError", "(", "\"Command ID in mib block is not a non-negative 2-byte number\"", ",", "cmd_id", "="...
Add a command to the TBBlock. The cmd_id must be a non-negative 2 byte number. handler should be the command handler
[ "Add", "a", "command", "to", "the", "TBBlock", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L112-L128
23,220
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.add_config
def add_config(self, config_id, config_data): """Add a configuration variable to the MIB block""" if config_id < 0 or config_id >= 2**16: raise ArgumentError("Config ID in mib block is not a non-negative 2-byte number", config_data=config_id, data=config_data) if config_id in self.configs: raise ArgumentError("Attempted to add the same command ID twice.", config_data=config_id, old_data=self.configs[config_id], new_data=config_data) self.configs[config_id] = config_data
python
def add_config(self, config_id, config_data): if config_id < 0 or config_id >= 2**16: raise ArgumentError("Config ID in mib block is not a non-negative 2-byte number", config_data=config_id, data=config_data) if config_id in self.configs: raise ArgumentError("Attempted to add the same command ID twice.", config_data=config_id, old_data=self.configs[config_id], new_data=config_data) self.configs[config_id] = config_data
[ "def", "add_config", "(", "self", ",", "config_id", ",", "config_data", ")", ":", "if", "config_id", "<", "0", "or", "config_id", ">=", "2", "**", "16", ":", "raise", "ArgumentError", "(", "\"Config ID in mib block is not a non-negative 2-byte number\"", ",", "con...
Add a configuration variable to the MIB block
[ "Add", "a", "configuration", "variable", "to", "the", "MIB", "block" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L130-L141
23,221
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock._parse_hwtype
def _parse_hwtype(self): """Convert the numerical hardware id to a chip name.""" self.chip_name = KNOWN_HARDWARE_TYPES.get(self.hw_type, "Unknown Chip (type=%d)" % self.hw_type)
python
def _parse_hwtype(self): self.chip_name = KNOWN_HARDWARE_TYPES.get(self.hw_type, "Unknown Chip (type=%d)" % self.hw_type)
[ "def", "_parse_hwtype", "(", "self", ")", ":", "self", ".", "chip_name", "=", "KNOWN_HARDWARE_TYPES", ".", "get", "(", "self", ".", "hw_type", ",", "\"Unknown Chip (type=%d)\"", "%", "self", ".", "hw_type", ")" ]
Convert the numerical hardware id to a chip name.
[ "Convert", "the", "numerical", "hardware", "id", "to", "a", "chip", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L143-L146
23,222
iotile/coretools
iotilebuild/iotile/build/tilebus/block.py
TBBlock.render_template
def render_template(self, template_name, out_path=None): """Render a template based on this TileBus Block. The template has access to all of the attributes of this block as a dictionary (the result of calling self.to_dict()). You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package out_path (str): An optional path of where to save the output file, otherwise it is just returned as a string. Returns: string: The rendered template data. """ return render_template(template_name, self.to_dict(), out_path=out_path)
python
def render_template(self, template_name, out_path=None): return render_template(template_name, self.to_dict(), out_path=out_path)
[ "def", "render_template", "(", "self", ",", "template_name", ",", "out_path", "=", "None", ")", ":", "return", "render_template", "(", "template_name", ",", "self", ".", "to_dict", "(", ")", ",", "out_path", "=", "out_path", ")" ]
Render a template based on this TileBus Block. The template has access to all of the attributes of this block as a dictionary (the result of calling self.to_dict()). You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package out_path (str): An optional path of where to save the output file, otherwise it is just returned as a string. Returns: string: The rendered template data.
[ "Render", "a", "template", "based", "on", "this", "TileBus", "Block", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/tilebus/block.py#L148-L166
23,223
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py
Tag
def Tag(env, target, source, *more_tags, **kw_tags): """ Tag a file with the given arguments, just sets the accordingly named attribute on the file object. TODO: FIXME """ if not target: target=source first_tag=None else: first_tag=source if first_tag: kw_tags[first_tag[0]] = '' if len(kw_tags) == 0 and len(more_tags) == 0: raise UserError("No tags given.") # XXX: sanity checks for x in more_tags: kw_tags[x] = '' if not SCons.Util.is_List(target): target=[target] else: # hmm, sometimes the target list, is a list of a list # make sure it is flattened prior to processing. # TODO: perhaps some bug ?!? target=env.Flatten(target) for t in target: for (k,v) in kw_tags.items(): # all file tags have to start with PACKAGING_, so we can later # differentiate between "normal" object attributes and the # packaging attributes. As the user should not be bothered with # that, the prefix will be added here if missing. if k[:10] != 'PACKAGING_': k='PACKAGING_'+k t.Tag(k, v)
python
def Tag(env, target, source, *more_tags, **kw_tags): if not target: target=source first_tag=None else: first_tag=source if first_tag: kw_tags[first_tag[0]] = '' if len(kw_tags) == 0 and len(more_tags) == 0: raise UserError("No tags given.") # XXX: sanity checks for x in more_tags: kw_tags[x] = '' if not SCons.Util.is_List(target): target=[target] else: # hmm, sometimes the target list, is a list of a list # make sure it is flattened prior to processing. # TODO: perhaps some bug ?!? target=env.Flatten(target) for t in target: for (k,v) in kw_tags.items(): # all file tags have to start with PACKAGING_, so we can later # differentiate between "normal" object attributes and the # packaging attributes. As the user should not be bothered with # that, the prefix will be added here if missing. if k[:10] != 'PACKAGING_': k='PACKAGING_'+k t.Tag(k, v)
[ "def", "Tag", "(", "env", ",", "target", ",", "source", ",", "*", "more_tags", ",", "*", "*", "kw_tags", ")", ":", "if", "not", "target", ":", "target", "=", "source", "first_tag", "=", "None", "else", ":", "first_tag", "=", "source", "if", "first_ta...
Tag a file with the given arguments, just sets the accordingly named attribute on the file object. TODO: FIXME
[ "Tag", "a", "file", "with", "the", "given", "arguments", "just", "sets", "the", "accordingly", "named", "attribute", "on", "the", "file", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py#L44-L82
23,224
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py
copy_attr
def copy_attr(f1, f2): """ copies the special packaging file attributes from f1 to f2. """ copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_' if f1._tags: pattrs = [tag for tag in f1._tags if copyit(tag)] for attr in pattrs: f2.Tag(attr, f1.GetTag(attr))
python
def copy_attr(f1, f2): copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_' if f1._tags: pattrs = [tag for tag in f1._tags if copyit(tag)] for attr in pattrs: f2.Tag(attr, f1.GetTag(attr))
[ "def", "copy_attr", "(", "f1", ",", "f2", ")", ":", "copyit", "=", "lambda", "x", ":", "not", "hasattr", "(", "f2", ",", "x", ")", "and", "x", "[", ":", "10", "]", "==", "'PACKAGING_'", "if", "f1", ".", "_tags", ":", "pattrs", "=", "[", "tag", ...
copies the special packaging file attributes from f1 to f2.
[ "copies", "the", "special", "packaging", "file", "attributes", "from", "f1", "to", "f2", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py#L231-L238
23,225
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py
putintopackageroot
def putintopackageroot(target, source, env, pkgroot, honor_install_location=1): """ Uses the CopyAs builder to copy all source files to the directory given in pkgroot. If honor_install_location is set and the copied source file has an PACKAGING_INSTALL_LOCATION attribute, the PACKAGING_INSTALL_LOCATION is used as the new name of the source file under pkgroot. The source file will not be copied if it is already under the the pkgroot directory. All attributes of the source file will be copied to the new file. """ # make sure the packageroot is a Dir object. if SCons.Util.is_String(pkgroot): pkgroot=env.Dir(pkgroot) if not SCons.Util.is_List(source): source=[source] new_source = [] for file in source: if SCons.Util.is_String(file): file = env.File(file) if file.is_under(pkgroot): new_source.append(file) else: if file.GetTag('PACKAGING_INSTALL_LOCATION') and\ honor_install_location: new_name=make_path_relative(file.GetTag('PACKAGING_INSTALL_LOCATION')) else: new_name=make_path_relative(file.get_path()) new_file=pkgroot.File(new_name) new_file=env.CopyAs(new_file, file)[0] copy_attr(file, new_file) new_source.append(new_file) return (target, new_source)
python
def putintopackageroot(target, source, env, pkgroot, honor_install_location=1): # make sure the packageroot is a Dir object. if SCons.Util.is_String(pkgroot): pkgroot=env.Dir(pkgroot) if not SCons.Util.is_List(source): source=[source] new_source = [] for file in source: if SCons.Util.is_String(file): file = env.File(file) if file.is_under(pkgroot): new_source.append(file) else: if file.GetTag('PACKAGING_INSTALL_LOCATION') and\ honor_install_location: new_name=make_path_relative(file.GetTag('PACKAGING_INSTALL_LOCATION')) else: new_name=make_path_relative(file.get_path()) new_file=pkgroot.File(new_name) new_file=env.CopyAs(new_file, file)[0] copy_attr(file, new_file) new_source.append(new_file) return (target, new_source)
[ "def", "putintopackageroot", "(", "target", ",", "source", ",", "env", ",", "pkgroot", ",", "honor_install_location", "=", "1", ")", ":", "# make sure the packageroot is a Dir object.", "if", "SCons", ".", "Util", ".", "is_String", "(", "pkgroot", ")", ":", "pkg...
Uses the CopyAs builder to copy all source files to the directory given in pkgroot. If honor_install_location is set and the copied source file has an PACKAGING_INSTALL_LOCATION attribute, the PACKAGING_INSTALL_LOCATION is used as the new name of the source file under pkgroot. The source file will not be copied if it is already under the the pkgroot directory. All attributes of the source file will be copied to the new file.
[ "Uses", "the", "CopyAs", "builder", "to", "copy", "all", "source", "files", "to", "the", "directory", "given", "in", "pkgroot", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py#L240-L275
23,226
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py
stripinstallbuilder
def stripinstallbuilder(target, source, env): """ Strips the install builder action from the source list and stores the final installation location as the "PACKAGING_INSTALL_LOCATION" of the source of the source file. This effectively removes the final installed files from the source list while remembering the installation location. It also warns about files which have no install builder attached. """ def has_no_install_location(file): return not (file.has_builder() and\ hasattr(file.builder, 'name') and\ (file.builder.name=="InstallBuilder" or\ file.builder.name=="InstallAsBuilder")) if len([src for src in source if has_no_install_location(src)]): warn(Warning, "there are files to package which have no\ InstallBuilder attached, this might lead to irreproducible packages") n_source=[] for s in source: if has_no_install_location(s): n_source.append(s) else: for ss in s.sources: n_source.append(ss) copy_attr(s, ss) ss.Tag('PACKAGING_INSTALL_LOCATION', s.get_path()) return (target, n_source)
python
def stripinstallbuilder(target, source, env): def has_no_install_location(file): return not (file.has_builder() and\ hasattr(file.builder, 'name') and\ (file.builder.name=="InstallBuilder" or\ file.builder.name=="InstallAsBuilder")) if len([src for src in source if has_no_install_location(src)]): warn(Warning, "there are files to package which have no\ InstallBuilder attached, this might lead to irreproducible packages") n_source=[] for s in source: if has_no_install_location(s): n_source.append(s) else: for ss in s.sources: n_source.append(ss) copy_attr(s, ss) ss.Tag('PACKAGING_INSTALL_LOCATION', s.get_path()) return (target, n_source)
[ "def", "stripinstallbuilder", "(", "target", ",", "source", ",", "env", ")", ":", "def", "has_no_install_location", "(", "file", ")", ":", "return", "not", "(", "file", ".", "has_builder", "(", ")", "and", "hasattr", "(", "file", ".", "builder", ",", "'n...
Strips the install builder action from the source list and stores the final installation location as the "PACKAGING_INSTALL_LOCATION" of the source of the source file. This effectively removes the final installed files from the source list while remembering the installation location. It also warns about files which have no install builder attached.
[ "Strips", "the", "install", "builder", "action", "from", "the", "source", "list", "and", "stores", "the", "final", "installation", "location", "as", "the", "PACKAGING_INSTALL_LOCATION", "of", "the", "source", "of", "the", "source", "file", ".", "This", "effectiv...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/__init__.py#L277-L305
23,227
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
BufferedStreamWalker.restore
def restore(self, state): """Restore a previous state of this stream walker. Raises: ArgumentError: If the state refers to a different selector or the offset is invalid. """ selector = DataStreamSelector.FromString(state.get(u'selector')) if selector != self.selector: raise ArgumentError("Attempted to restore a BufferedStreamWalker with a different selector", selector=self.selector, serialized_data=state) self.seek(state.get(u'offset'), target="offset")
python
def restore(self, state): selector = DataStreamSelector.FromString(state.get(u'selector')) if selector != self.selector: raise ArgumentError("Attempted to restore a BufferedStreamWalker with a different selector", selector=self.selector, serialized_data=state) self.seek(state.get(u'offset'), target="offset")
[ "def", "restore", "(", "self", ",", "state", ")", ":", "selector", "=", "DataStreamSelector", ".", "FromString", "(", "state", ".", "get", "(", "u'selector'", ")", ")", "if", "selector", "!=", "self", ".", "selector", ":", "raise", "ArgumentError", "(", ...
Restore a previous state of this stream walker. Raises: ArgumentError: If the state refers to a different selector or the offset is invalid.
[ "Restore", "a", "previous", "state", "of", "this", "stream", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L85-L98
23,228
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
BufferedStreamWalker.pop
def pop(self): """Pop a reading off of this stream and return it.""" if self._count == 0: raise StreamEmptyError("Pop called on buffered stream walker without any data", selector=self.selector) while True: curr = self.engine.get(self.storage_type, self.offset) self.offset += 1 stream = DataStream.FromEncoded(curr.stream) if self.matches(stream): self._count -= 1 return curr
python
def pop(self): if self._count == 0: raise StreamEmptyError("Pop called on buffered stream walker without any data", selector=self.selector) while True: curr = self.engine.get(self.storage_type, self.offset) self.offset += 1 stream = DataStream.FromEncoded(curr.stream) if self.matches(stream): self._count -= 1 return curr
[ "def", "pop", "(", "self", ")", ":", "if", "self", ".", "_count", "==", "0", ":", "raise", "StreamEmptyError", "(", "\"Pop called on buffered stream walker without any data\"", ",", "selector", "=", "self", ".", "selector", ")", "while", "True", ":", "curr", "...
Pop a reading off of this stream and return it.
[ "Pop", "a", "reading", "off", "of", "this", "stream", "and", "return", "it", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L105-L118
23,229
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
BufferedStreamWalker.seek
def seek(self, value, target="offset"): """Seek this stream to a specific offset or reading id. There are two modes of use. You can seek to a specific reading id, which means the walker will be positioned exactly at the reading pointed to by the reading ID. If the reading id cannot be found an exception will be raised. The reading id can be found but corresponds to a reading that is not selected by this walker, the walker will be moved to point at the first reading after that reading and False will be returned. If target=="offset", the walker will be positioned at the specified offset in the sensor log. It will also update the count of available readings based on that new location so that the count remains correct. The offset does not need to correspond to a reading selected by this walker. If offset does not point to a selected reading, the effective behavior will be as if the walker pointed to the next selected reading after `offset`. Args: value (int): The identifier to seek, either an offset or a reading id. target (str): The type of thing to seek. Can be offset or id. If id is given, then a reading with the given ID will be searched for. If offset is given then the walker will be positioned at the given offset. Returns: bool: True if an exact match was found, False otherwise. An exact match means that the offset or reading ID existed and corresponded to a reading selected by this walker. An inexact match means that the offset or reading ID existed but corresponded to reading that was not selected by this walker. If the offset or reading ID could not be found an Exception is thrown instead. Raises: ArgumentError: target is an invalid string, must be offset or id. UnresolvedIdentifierError: the desired offset or reading id could not be found. """ if target not in (u'offset', u'id'): raise ArgumentError("You must specify target as either offset or id", target=target) if target == u'offset': self._verify_offset(value) self.offset = value else: self.offset = self._find_id(value) self._count = self.engine.count_matching(self.selector, offset=self.offset) curr = self.engine.get(self.storage_type, self.offset) return self.matches(DataStream.FromEncoded(curr.stream))
python
def seek(self, value, target="offset"): if target not in (u'offset', u'id'): raise ArgumentError("You must specify target as either offset or id", target=target) if target == u'offset': self._verify_offset(value) self.offset = value else: self.offset = self._find_id(value) self._count = self.engine.count_matching(self.selector, offset=self.offset) curr = self.engine.get(self.storage_type, self.offset) return self.matches(DataStream.FromEncoded(curr.stream))
[ "def", "seek", "(", "self", ",", "value", ",", "target", "=", "\"offset\"", ")", ":", "if", "target", "not", "in", "(", "u'offset'", ",", "u'id'", ")", ":", "raise", "ArgumentError", "(", "\"You must specify target as either offset or id\"", ",", "target", "="...
Seek this stream to a specific offset or reading id. There are two modes of use. You can seek to a specific reading id, which means the walker will be positioned exactly at the reading pointed to by the reading ID. If the reading id cannot be found an exception will be raised. The reading id can be found but corresponds to a reading that is not selected by this walker, the walker will be moved to point at the first reading after that reading and False will be returned. If target=="offset", the walker will be positioned at the specified offset in the sensor log. It will also update the count of available readings based on that new location so that the count remains correct. The offset does not need to correspond to a reading selected by this walker. If offset does not point to a selected reading, the effective behavior will be as if the walker pointed to the next selected reading after `offset`. Args: value (int): The identifier to seek, either an offset or a reading id. target (str): The type of thing to seek. Can be offset or id. If id is given, then a reading with the given ID will be searched for. If offset is given then the walker will be positioned at the given offset. Returns: bool: True if an exact match was found, False otherwise. An exact match means that the offset or reading ID existed and corresponded to a reading selected by this walker. An inexact match means that the offset or reading ID existed but corresponded to reading that was not selected by this walker. If the offset or reading ID could not be found an Exception is thrown instead. Raises: ArgumentError: target is an invalid string, must be offset or id. UnresolvedIdentifierError: the desired offset or reading id could not be found.
[ "Seek", "this", "stream", "to", "a", "specific", "offset", "or", "reading", "id", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L120-L179
23,230
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
BufferedStreamWalker.skip_all
def skip_all(self): """Skip all readings in this walker.""" storage, streaming = self.engine.count() if self.selector.output: self.offset = streaming else: self.offset = storage self._count = 0
python
def skip_all(self): storage, streaming = self.engine.count() if self.selector.output: self.offset = streaming else: self.offset = storage self._count = 0
[ "def", "skip_all", "(", "self", ")", ":", "storage", ",", "streaming", "=", "self", ".", "engine", ".", "count", "(", ")", "if", "self", ".", "selector", ".", "output", ":", "self", ".", "offset", "=", "streaming", "else", ":", "self", ".", "offset",...
Skip all readings in this walker.
[ "Skip", "all", "readings", "in", "this", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L228-L238
23,231
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
BufferedStreamWalker.notify_rollover
def notify_rollover(self, stream): """Notify that a reading in the given stream was overwritten. Args: stream (DataStream): The stream that had overwritten data. """ self.offset -= 1 if not self.matches(stream): return if self._count == 0: raise InternalError("BufferedStreamWalker out of sync with storage engine, count was wrong.") self._count -= 1
python
def notify_rollover(self, stream): self.offset -= 1 if not self.matches(stream): return if self._count == 0: raise InternalError("BufferedStreamWalker out of sync with storage engine, count was wrong.") self._count -= 1
[ "def", "notify_rollover", "(", "self", ",", "stream", ")", ":", "self", ".", "offset", "-=", "1", "if", "not", "self", ".", "matches", "(", "stream", ")", ":", "return", "if", "self", ".", "_count", "==", "0", ":", "raise", "InternalError", "(", "\"B...
Notify that a reading in the given stream was overwritten. Args: stream (DataStream): The stream that had overwritten data.
[ "Notify", "that", "a", "reading", "in", "the", "given", "stream", "was", "overwritten", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L252-L267
23,232
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
VirtualStreamWalker.dump
def dump(self): """Serialize the state of this stream walker. Returns: dict: The serialized state. """ reading = self.reading if reading is not None: reading = reading.asdict() return { u'selector': str(self.selector), u'reading': reading }
python
def dump(self): reading = self.reading if reading is not None: reading = reading.asdict() return { u'selector': str(self.selector), u'reading': reading }
[ "def", "dump", "(", "self", ")", ":", "reading", "=", "self", ".", "reading", "if", "reading", "is", "not", "None", ":", "reading", "=", "reading", ".", "asdict", "(", ")", "return", "{", "u'selector'", ":", "str", "(", "self", ".", "selector", ")", ...
Serialize the state of this stream walker. Returns: dict: The serialized state.
[ "Serialize", "the", "state", "of", "this", "stream", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L286-L300
23,233
iotile/coretools
iotilesensorgraph/iotile/sg/walker.py
CounterStreamWalker.peek
def peek(self): """Peek at the oldest reading in this virtual stream.""" if self.reading is None: raise StreamEmptyError("peek called on virtual stream walker without any data", selector=self.selector) return self.reading
python
def peek(self): if self.reading is None: raise StreamEmptyError("peek called on virtual stream walker without any data", selector=self.selector) return self.reading
[ "def", "peek", "(", "self", ")", ":", "if", "self", ".", "reading", "is", "None", ":", "raise", "StreamEmptyError", "(", "\"peek called on virtual stream walker without any data\"", ",", "selector", "=", "self", ".", "selector", ")", "return", "self", ".", "read...
Peek at the oldest reading in this virtual stream.
[ "Peek", "at", "the", "oldest", "reading", "in", "this", "virtual", "stream", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L481-L487
23,234
iotile/coretools
iotilecore/iotile/core/utilities/linebuffer_ui.py
LinebufferUI.run
def run(self, refresh_interval=0.05): """Set up the loop, check that the tool is installed""" try: from asciimatics.screen import Screen except ImportError: raise ExternalError("You must have asciimatics installed to use LinebufferUI", suggestion="pip install iotilecore[ui]") Screen.wrapper(self._run_loop, arguments=[refresh_interval])
python
def run(self, refresh_interval=0.05): try: from asciimatics.screen import Screen except ImportError: raise ExternalError("You must have asciimatics installed to use LinebufferUI", suggestion="pip install iotilecore[ui]") Screen.wrapper(self._run_loop, arguments=[refresh_interval])
[ "def", "run", "(", "self", ",", "refresh_interval", "=", "0.05", ")", ":", "try", ":", "from", "asciimatics", ".", "screen", "import", "Screen", "except", "ImportError", ":", "raise", "ExternalError", "(", "\"You must have asciimatics installed to use LinebufferUI\"",...
Set up the loop, check that the tool is installed
[ "Set", "up", "the", "loop", "check", "that", "the", "tool", "is", "installed" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/linebuffer_ui.py#L62-L70
23,235
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vc.py
find_vc_pdir
def find_vc_pdir(msvc_version): """Try to find the product directory for the given version. Note ---- If for some reason the requested version could not be found, an exception which inherits from VisualCException will be raised.""" root = 'Software\\' try: hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version] except KeyError: debug("Unknown version of MSVC: %s" % msvc_version) raise UnsupportedVersion("Unknown version %s" % msvc_version) for hkroot, key in hkeys: try: comps = None if not key: comps = find_vc_pdir_vswhere(msvc_version) if not comps: debug('find_vc_dir(): no VC found via vswhere for version {}'.format(repr(key))) raise SCons.Util.WinError else: if common.is_win64(): try: # ordinally at win64, try Wow6432Node first. comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot) except SCons.Util.WinError as e: # at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node pass if not comps: # not Win64, or Microsoft Visual Studio for Python 2.7 comps = common.read_reg(root + key, hkroot) except SCons.Util.WinError as e: debug('find_vc_dir(): no VC registry key {}'.format(repr(key))) else: debug('find_vc_dir(): found VC in registry: {}'.format(comps)) if os.path.exists(comps): return comps else: debug('find_vc_dir(): reg says dir is {}, but it does not exist. (ignoring)'.format(comps)) raise MissingConfiguration("registry dir {} not found on the filesystem".format(comps)) return None
python
def find_vc_pdir(msvc_version): root = 'Software\\' try: hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version] except KeyError: debug("Unknown version of MSVC: %s" % msvc_version) raise UnsupportedVersion("Unknown version %s" % msvc_version) for hkroot, key in hkeys: try: comps = None if not key: comps = find_vc_pdir_vswhere(msvc_version) if not comps: debug('find_vc_dir(): no VC found via vswhere for version {}'.format(repr(key))) raise SCons.Util.WinError else: if common.is_win64(): try: # ordinally at win64, try Wow6432Node first. comps = common.read_reg(root + 'Wow6432Node\\' + key, hkroot) except SCons.Util.WinError as e: # at Microsoft Visual Studio for Python 2.7, value is not in Wow6432Node pass if not comps: # not Win64, or Microsoft Visual Studio for Python 2.7 comps = common.read_reg(root + key, hkroot) except SCons.Util.WinError as e: debug('find_vc_dir(): no VC registry key {}'.format(repr(key))) else: debug('find_vc_dir(): found VC in registry: {}'.format(comps)) if os.path.exists(comps): return comps else: debug('find_vc_dir(): reg says dir is {}, but it does not exist. (ignoring)'.format(comps)) raise MissingConfiguration("registry dir {} not found on the filesystem".format(comps)) return None
[ "def", "find_vc_pdir", "(", "msvc_version", ")", ":", "root", "=", "'Software\\\\'", "try", ":", "hkeys", "=", "_VCVER_TO_PRODUCT_DIR", "[", "msvc_version", "]", "except", "KeyError", ":", "debug", "(", "\"Unknown version of MSVC: %s\"", "%", "msvc_version", ")", ...
Try to find the product directory for the given version. Note ---- If for some reason the requested version could not be found, an exception which inherits from VisualCException will be raised.
[ "Try", "to", "find", "the", "product", "directory", "for", "the", "given", "version", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vc.py#L257-L300
23,236
iotile/coretools
iotilesensorgraph/iotile/sg/compiler.py
compile_sgf
def compile_sgf(in_path, optimize=True, model=None): """Compile and optionally optimize an SGF file. Args: in_path (str): The input path to the sgf file to compile. optimize (bool): Whether to optimize the compiled result, defaults to True if not passed. model (DeviceModel): Optional device model if we are compiling for a nonstandard device. Normally you should leave this blank. Returns: SensorGraph: The compiled sensorgraph object """ if model is None: model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(in_path) parser.compile(model) if optimize: opt = SensorGraphOptimizer() opt.optimize(parser.sensor_graph, model=model) return parser.sensor_graph
python
def compile_sgf(in_path, optimize=True, model=None): if model is None: model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(in_path) parser.compile(model) if optimize: opt = SensorGraphOptimizer() opt.optimize(parser.sensor_graph, model=model) return parser.sensor_graph
[ "def", "compile_sgf", "(", "in_path", ",", "optimize", "=", "True", ",", "model", "=", "None", ")", ":", "if", "model", "is", "None", ":", "model", "=", "DeviceModel", "(", ")", "parser", "=", "SensorGraphFileParser", "(", ")", "parser", ".", "parse_file...
Compile and optionally optimize an SGF file. Args: in_path (str): The input path to the sgf file to compile. optimize (bool): Whether to optimize the compiled result, defaults to True if not passed. model (DeviceModel): Optional device model if we are compiling for a nonstandard device. Normally you should leave this blank. Returns: SensorGraph: The compiled sensorgraph object
[ "Compile", "and", "optionally", "optimize", "an", "SGF", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/compiler.py#L8-L34
23,237
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/g77.py
generate
def generate(env): """Add Builders and construction variables for g77 to an Environment.""" add_all_to_env(env) add_f77_to_env(env) fcomp = env.Detect(compilers) or 'g77' if env['PLATFORM'] in ['cygwin', 'win32']: env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS') else: env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -fPIC') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -fPIC') env['FORTRAN'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['F77'] = fcomp env['SHF77'] = '$F77' env['INCFORTRANPREFIX'] = "-I" env['INCFORTRANSUFFIX'] = "" env['INCF77PREFIX'] = "-I" env['INCF77SUFFIX'] = ""
python
def generate(env): add_all_to_env(env) add_f77_to_env(env) fcomp = env.Detect(compilers) or 'g77' if env['PLATFORM'] in ['cygwin', 'win32']: env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS') else: env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -fPIC') env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -fPIC') env['FORTRAN'] = fcomp env['SHFORTRAN'] = '$FORTRAN' env['F77'] = fcomp env['SHF77'] = '$F77' env['INCFORTRANPREFIX'] = "-I" env['INCFORTRANSUFFIX'] = "" env['INCF77PREFIX'] = "-I" env['INCF77SUFFIX'] = ""
[ "def", "generate", "(", "env", ")", ":", "add_all_to_env", "(", "env", ")", "add_f77_to_env", "(", "env", ")", "fcomp", "=", "env", ".", "Detect", "(", "compilers", ")", "or", "'g77'", "if", "env", "[", "'PLATFORM'", "]", "in", "[", "'cygwin'", ",", ...
Add Builders and construction variables for g77 to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "g77", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/g77.py#L41-L64
23,238
iotile/coretools
iotilesensorgraph/iotile/sg/parser/language.py
get_language
def get_language(): """Create or retrieve the parse tree for defining a sensor graph.""" global sensor_graph, statement if sensor_graph is not None: return sensor_graph _create_primitives() _create_simple_statements() _create_block_bnf() sensor_graph = ZeroOrMore(statement) + StringEnd() sensor_graph.ignore(comment) return sensor_graph
python
def get_language(): global sensor_graph, statement if sensor_graph is not None: return sensor_graph _create_primitives() _create_simple_statements() _create_block_bnf() sensor_graph = ZeroOrMore(statement) + StringEnd() sensor_graph.ignore(comment) return sensor_graph
[ "def", "get_language", "(", ")", ":", "global", "sensor_graph", ",", "statement", "if", "sensor_graph", "is", "not", "None", ":", "return", "sensor_graph", "_create_primitives", "(", ")", "_create_simple_statements", "(", ")", "_create_block_bnf", "(", ")", "senso...
Create or retrieve the parse tree for defining a sensor graph.
[ "Create", "or", "retrieve", "the", "parse", "tree", "for", "defining", "a", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/language.py#L142-L157
23,239
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgfmt.py
_create_mo_file_builder
def _create_mo_file_builder(env, **kw): """ Create builder object for `MOFiles` builder """ import SCons.Action # FIXME: What factory use for source? Ours or their? kw['action'] = SCons.Action.Action('$MSGFMTCOM','$MSGFMTCOMSTR') kw['suffix'] = '$MOSUFFIX' kw['src_suffix'] = '$POSUFFIX' kw['src_builder'] = '_POUpdateBuilder' kw['single_source'] = True return _MOFileBuilder(**kw)
python
def _create_mo_file_builder(env, **kw): import SCons.Action # FIXME: What factory use for source? Ours or their? kw['action'] = SCons.Action.Action('$MSGFMTCOM','$MSGFMTCOMSTR') kw['suffix'] = '$MOSUFFIX' kw['src_suffix'] = '$POSUFFIX' kw['src_builder'] = '_POUpdateBuilder' kw['single_source'] = True return _MOFileBuilder(**kw)
[ "def", "_create_mo_file_builder", "(", "env", ",", "*", "*", "kw", ")", ":", "import", "SCons", ".", "Action", "# FIXME: What factory use for source? Ours or their?", "kw", "[", "'action'", "]", "=", "SCons", ".", "Action", ".", "Action", "(", "'$MSGFMTCOM'", ",...
Create builder object for `MOFiles` builder
[ "Create", "builder", "object", "for", "MOFiles", "builder" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgfmt.py#L63-L72
23,240
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgfmt.py
generate
def generate(env,**kw): """ Generate `msgfmt` tool """ import SCons.Util from SCons.Tool.GettextCommon import _detect_msgfmt try: env['MSGFMT'] = _detect_msgfmt(env) except: env['MSGFMT'] = 'msgfmt' env.SetDefault( MSGFMTFLAGS = [ SCons.Util.CLVar('-c') ], MSGFMTCOM = '$MSGFMT $MSGFMTFLAGS -o $TARGET $SOURCE', MSGFMTCOMSTR = '', MOSUFFIX = ['.mo'], POSUFFIX = ['.po'] ) env.Append( BUILDERS = { 'MOFiles' : _create_mo_file_builder(env) } )
python
def generate(env,**kw): import SCons.Util from SCons.Tool.GettextCommon import _detect_msgfmt try: env['MSGFMT'] = _detect_msgfmt(env) except: env['MSGFMT'] = 'msgfmt' env.SetDefault( MSGFMTFLAGS = [ SCons.Util.CLVar('-c') ], MSGFMTCOM = '$MSGFMT $MSGFMTFLAGS -o $TARGET $SOURCE', MSGFMTCOMSTR = '', MOSUFFIX = ['.mo'], POSUFFIX = ['.po'] ) env.Append( BUILDERS = { 'MOFiles' : _create_mo_file_builder(env) } )
[ "def", "generate", "(", "env", ",", "*", "*", "kw", ")", ":", "import", "SCons", ".", "Util", "from", "SCons", ".", "Tool", ".", "GettextCommon", "import", "_detect_msgfmt", "try", ":", "env", "[", "'MSGFMT'", "]", "=", "_detect_msgfmt", "(", "env", ")...
Generate `msgfmt` tool
[ "Generate", "msgfmt", "tool" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msgfmt.py#L76-L91
23,241
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/RC.py
RCScan
def RCScan(): """Return a prototype Scanner instance for scanning RC source files""" res_re= r'^(?:\s*#\s*(?:include)|' \ '.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' \ '\s*.*?)' \ '\s*(<|"| )([^>"\s]+)(?:[>"\s])*$' resScanner = SCons.Scanner.ClassicCPP("ResourceScanner", "$RCSUFFIXES", "CPPPATH", res_re, recursive=no_tlb) return resScanner
python
def RCScan(): res_re= r'^(?:\s*#\s*(?:include)|' \ '.*?\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)' \ '\s*.*?)' \ '\s*(<|"| )([^>"\s]+)(?:[>"\s])*$' resScanner = SCons.Scanner.ClassicCPP("ResourceScanner", "$RCSUFFIXES", "CPPPATH", res_re, recursive=no_tlb) return resScanner
[ "def", "RCScan", "(", ")", ":", "res_re", "=", "r'^(?:\\s*#\\s*(?:include)|'", "'.*?\\s+(?:ICON|BITMAP|CURSOR|HTML|FONT|MESSAGETABLE|TYPELIB|REGISTRY|D3DFX)'", "'\\s*.*?)'", "'\\s*(<|\"| )([^>\"\\s]+)(?:[>\"\\s])*$'", "resScanner", "=", "SCons", ".", "Scanner", ".", "ClassicCPP", ...
Return a prototype Scanner instance for scanning RC source files
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "RC", "source", "files" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/RC.py#L47-L60
23,242
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py
_read_linguas_from_files
def _read_linguas_from_files(env, linguas_files=None): """ Parse `LINGUAS` file and return list of extracted languages """ import SCons.Util import SCons.Environment global _re_comment global _re_lang if not SCons.Util.is_List(linguas_files) \ and not SCons.Util.is_String(linguas_files) \ and not isinstance(linguas_files, SCons.Node.FS.Base) \ and linguas_files: # If, linguas_files==True or such, then read 'LINGUAS' file. linguas_files = ['LINGUAS'] if linguas_files is None: return [] fnodes = env.arg2nodes(linguas_files) linguas = [] for fnode in fnodes: contents = _re_comment.sub("", fnode.get_text_contents()) ls = [l for l in _re_lang.findall(contents) if l] linguas.extend(ls) return linguas
python
def _read_linguas_from_files(env, linguas_files=None): import SCons.Util import SCons.Environment global _re_comment global _re_lang if not SCons.Util.is_List(linguas_files) \ and not SCons.Util.is_String(linguas_files) \ and not isinstance(linguas_files, SCons.Node.FS.Base) \ and linguas_files: # If, linguas_files==True or such, then read 'LINGUAS' file. linguas_files = ['LINGUAS'] if linguas_files is None: return [] fnodes = env.arg2nodes(linguas_files) linguas = [] for fnode in fnodes: contents = _re_comment.sub("", fnode.get_text_contents()) ls = [l for l in _re_lang.findall(contents) if l] linguas.extend(ls) return linguas
[ "def", "_read_linguas_from_files", "(", "env", ",", "linguas_files", "=", "None", ")", ":", "import", "SCons", ".", "Util", "import", "SCons", ".", "Environment", "global", "_re_comment", "global", "_re_lang", "if", "not", "SCons", ".", "Util", ".", "is_List",...
Parse `LINGUAS` file and return list of extracted languages
[ "Parse", "LINGUAS", "file", "and", "return", "list", "of", "extracted", "languages" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py#L131-L151
23,243
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py
_init_po_files
def _init_po_files(target, source, env): """ Action function for `POInit` builder. """ nop = lambda target, source, env: 0 if 'POAUTOINIT' in env: autoinit = env['POAUTOINIT'] else: autoinit = False # Well, if everything outside works well, this loop should do single # iteration. Otherwise we are rebuilding all the targets even, if just # one has changed (but is this our fault?). for tgt in target: if not tgt.exists(): if autoinit: action = SCons.Action.Action('$MSGINITCOM', '$MSGINITCOMSTR') else: msg = 'File ' + repr(str(tgt)) + ' does not exist. ' \ + 'If you are a translator, you can create it through: \n' \ + '$MSGINITCOM' action = SCons.Action.Action(nop, msg) status = action([tgt], source, env) if status: return status return 0
python
def _init_po_files(target, source, env): nop = lambda target, source, env: 0 if 'POAUTOINIT' in env: autoinit = env['POAUTOINIT'] else: autoinit = False # Well, if everything outside works well, this loop should do single # iteration. Otherwise we are rebuilding all the targets even, if just # one has changed (but is this our fault?). for tgt in target: if not tgt.exists(): if autoinit: action = SCons.Action.Action('$MSGINITCOM', '$MSGINITCOMSTR') else: msg = 'File ' + repr(str(tgt)) + ' does not exist. ' \ + 'If you are a translator, you can create it through: \n' \ + '$MSGINITCOM' action = SCons.Action.Action(nop, msg) status = action([tgt], source, env) if status: return status return 0
[ "def", "_init_po_files", "(", "target", ",", "source", ",", "env", ")", ":", "nop", "=", "lambda", "target", ",", "source", ",", "env", ":", "0", "if", "'POAUTOINIT'", "in", "env", ":", "autoinit", "=", "env", "[", "'POAUTOINIT'", "]", "else", ":", "...
Action function for `POInit` builder.
[ "Action", "function", "for", "POInit", "builder", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py#L362-L383
23,244
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py
_POTargetFactory._create_node
def _create_node(self, name, factory, directory=None, create=1): """ Create node, and set it up to factory settings. """ import SCons.Util node = factory(name, directory, create) node.set_noclean(self.noclean) node.set_precious(self.precious) if self.nodefault: self.env.Ignore('.', node) if self.alias: self.env.AlwaysBuild(self.env.Alias(self.alias, node)) return node
python
def _create_node(self, name, factory, directory=None, create=1): import SCons.Util node = factory(name, directory, create) node.set_noclean(self.noclean) node.set_precious(self.precious) if self.nodefault: self.env.Ignore('.', node) if self.alias: self.env.AlwaysBuild(self.env.Alias(self.alias, node)) return node
[ "def", "_create_node", "(", "self", ",", "name", ",", "factory", ",", "directory", "=", "None", ",", "create", "=", "1", ")", ":", "import", "SCons", ".", "Util", "node", "=", "factory", "(", "name", ",", "directory", ",", "create", ")", "node", ".",...
Create node, and set it up to factory settings.
[ "Create", "node", "and", "set", "it", "up", "to", "factory", "settings", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py#L102-L112
23,245
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py
_POTargetFactory.Entry
def Entry(self, name, directory=None, create=1): """ Create `SCons.Node.FS.Entry` """ return self._create_node(name, self.env.fs.Entry, directory, create)
python
def Entry(self, name, directory=None, create=1): return self._create_node(name, self.env.fs.Entry, directory, create)
[ "def", "Entry", "(", "self", ",", "name", ",", "directory", "=", "None", ",", "create", "=", "1", ")", ":", "return", "self", ".", "_create_node", "(", "name", ",", "self", ".", "env", ".", "fs", ".", "Entry", ",", "directory", ",", "create", ")" ]
Create `SCons.Node.FS.Entry`
[ "Create", "SCons", ".", "Node", ".", "FS", ".", "Entry" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py#L114-L116
23,246
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py
_POTargetFactory.File
def File(self, name, directory=None, create=1): """ Create `SCons.Node.FS.File` """ return self._create_node(name, self.env.fs.File, directory, create)
python
def File(self, name, directory=None, create=1): return self._create_node(name, self.env.fs.File, directory, create)
[ "def", "File", "(", "self", ",", "name", ",", "directory", "=", "None", ",", "create", "=", "1", ")", ":", "return", "self", ".", "_create_node", "(", "name", ",", "self", ".", "env", ".", "fs", ".", "File", ",", "directory", ",", "create", ")" ]
Create `SCons.Node.FS.File`
[ "Create", "SCons", ".", "Node", ".", "FS", ".", "File" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/GettextCommon.py#L118-L120
23,247
iotile/coretools
iotilesensorgraph/iotile/sg/parser/stream_allocator.py
StreamAllocator.allocate_stream
def allocate_stream(self, stream_type, stream_id=None, previous=None, attach=False): """Allocate a new stream of the given type. The stream is allocated with an incremental ID starting at StreamAllocator.StartingID. The returned data stream can always be used to to attach a NodeInput to this stream, however the attach_stream() function should always be called first since this stream's output may need to be split and a logically equivalent stream used instead to satisfy a device specific constraint on the maximum number of outputs attached to a given stream. You can call allocate_stream on the same stream multiple times without issue. Subsequent calls to allocate_stream are noops. Args: stream_type (int): A stream type specified in the DataStream class like DataStream.ConstantType stream_id (int): The ID we would like to use for this stream, if this is not specified, an ID is automatically allocated. previous (DataStream): If this stream was automatically derived from another stream, this parameter should be a link to the old stream. attach (bool): Call attach_stream immediately before returning. Convenience routine for streams that should immediately be attached to something. Returns: DataStream: The allocated data stream. """ if stream_type not in DataStream.TypeToString: raise ArgumentError("Unknown stream type in allocate_stream", stream_type=stream_type) if stream_id is not None and stream_id >= StreamAllocator.StartingID: raise ArgumentError("Attempted to explicitly allocate a stream id in the internally managed id range", stream_id=stream_id, started_id=StreamAllocator.StartingID) # If the stream id is not explicitly given, we need to manage and track it # from our autoallocate range if stream_id is None: if stream_type not in self._next_id: self._next_id[stream_type] = StreamAllocator.StartingID stream_id = self._next_id[stream_type] self._next_id[stream_type] += 1 # Keep track of how many downstream nodes are attached to this stream so # that we know when we need to split it into two. stream = DataStream(stream_type, stream_id) if stream not in self._allocated_streams: self._allocated_streams[stream] = (stream, 0, previous) if attach: stream = self.attach_stream(stream) return stream
python
def allocate_stream(self, stream_type, stream_id=None, previous=None, attach=False): if stream_type not in DataStream.TypeToString: raise ArgumentError("Unknown stream type in allocate_stream", stream_type=stream_type) if stream_id is not None and stream_id >= StreamAllocator.StartingID: raise ArgumentError("Attempted to explicitly allocate a stream id in the internally managed id range", stream_id=stream_id, started_id=StreamAllocator.StartingID) # If the stream id is not explicitly given, we need to manage and track it # from our autoallocate range if stream_id is None: if stream_type not in self._next_id: self._next_id[stream_type] = StreamAllocator.StartingID stream_id = self._next_id[stream_type] self._next_id[stream_type] += 1 # Keep track of how many downstream nodes are attached to this stream so # that we know when we need to split it into two. stream = DataStream(stream_type, stream_id) if stream not in self._allocated_streams: self._allocated_streams[stream] = (stream, 0, previous) if attach: stream = self.attach_stream(stream) return stream
[ "def", "allocate_stream", "(", "self", ",", "stream_type", ",", "stream_id", "=", "None", ",", "previous", "=", "None", ",", "attach", "=", "False", ")", ":", "if", "stream_type", "not", "in", "DataStream", ".", "TypeToString", ":", "raise", "ArgumentError",...
Allocate a new stream of the given type. The stream is allocated with an incremental ID starting at StreamAllocator.StartingID. The returned data stream can always be used to to attach a NodeInput to this stream, however the attach_stream() function should always be called first since this stream's output may need to be split and a logically equivalent stream used instead to satisfy a device specific constraint on the maximum number of outputs attached to a given stream. You can call allocate_stream on the same stream multiple times without issue. Subsequent calls to allocate_stream are noops. Args: stream_type (int): A stream type specified in the DataStream class like DataStream.ConstantType stream_id (int): The ID we would like to use for this stream, if this is not specified, an ID is automatically allocated. previous (DataStream): If this stream was automatically derived from another stream, this parameter should be a link to the old stream. attach (bool): Call attach_stream immediately before returning. Convenience routine for streams that should immediately be attached to something. Returns: DataStream: The allocated data stream.
[ "Allocate", "a", "new", "stream", "of", "the", "given", "type", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/stream_allocator.py#L30-L84
23,248
iotile/coretools
iotilesensorgraph/iotile/sg/parser/stream_allocator.py
StreamAllocator.attach_stream
def attach_stream(self, stream): """Notify that we would like to attach a node input to this stream. The return value from this function is the DataStream that should be attached to since this function may internally allocate a new SGNode that copies the stream if there is no space in the output list to hold another input. This function should be called once for every node input before allocated a new sensor graph node that attaches to a stream that is managed by the StreamAllocator. Args: stream (DataStream): The stream (originally returned from allocate_stream) that we want to attach to. Returns: Datastream: A data stream, possible the same as stream, that should be attached to a node input. """ curr_stream, count, prev = self._allocated_streams[stream] # Check if we need to split this stream and allocate a new one if count == (self.model.get(u'max_node_outputs') - 1): new_stream = self.allocate_stream(curr_stream.stream_type, previous=curr_stream) copy_desc = u"({} always) => {} using copy_all_a".format(curr_stream, new_stream) self.sensor_graph.add_node(copy_desc) self._allocated_streams[stream] = (new_stream, 1, curr_stream) # If we are splitting a constant stream, make sure we also duplicate the initialization value # FIXME: If there is no default value for the stream, that is probably a warning since all constant # streams should be initialized with a value. if curr_stream.stream_type == DataStream.ConstantType and curr_stream in self.sensor_graph.constant_database: self.sensor_graph.add_constant(new_stream, self.sensor_graph.constant_database[curr_stream]) return new_stream self._allocated_streams[stream] = (curr_stream, count + 1, prev) return curr_stream
python
def attach_stream(self, stream): curr_stream, count, prev = self._allocated_streams[stream] # Check if we need to split this stream and allocate a new one if count == (self.model.get(u'max_node_outputs') - 1): new_stream = self.allocate_stream(curr_stream.stream_type, previous=curr_stream) copy_desc = u"({} always) => {} using copy_all_a".format(curr_stream, new_stream) self.sensor_graph.add_node(copy_desc) self._allocated_streams[stream] = (new_stream, 1, curr_stream) # If we are splitting a constant stream, make sure we also duplicate the initialization value # FIXME: If there is no default value for the stream, that is probably a warning since all constant # streams should be initialized with a value. if curr_stream.stream_type == DataStream.ConstantType and curr_stream in self.sensor_graph.constant_database: self.sensor_graph.add_constant(new_stream, self.sensor_graph.constant_database[curr_stream]) return new_stream self._allocated_streams[stream] = (curr_stream, count + 1, prev) return curr_stream
[ "def", "attach_stream", "(", "self", ",", "stream", ")", ":", "curr_stream", ",", "count", ",", "prev", "=", "self", ".", "_allocated_streams", "[", "stream", "]", "# Check if we need to split this stream and allocate a new one", "if", "count", "==", "(", "self", ...
Notify that we would like to attach a node input to this stream. The return value from this function is the DataStream that should be attached to since this function may internally allocate a new SGNode that copies the stream if there is no space in the output list to hold another input. This function should be called once for every node input before allocated a new sensor graph node that attaches to a stream that is managed by the StreamAllocator. Args: stream (DataStream): The stream (originally returned from allocate_stream) that we want to attach to. Returns: Datastream: A data stream, possible the same as stream, that should be attached to a node input.
[ "Notify", "that", "we", "would", "like", "to", "attach", "a", "node", "input", "to", "this", "stream", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/stream_allocator.py#L86-L124
23,249
iotile/coretools
iotilecore/iotile/core/dev/iotileobj.py
IOTile._find_v1_settings
def _find_v1_settings(self, settings): """Parse a v1 module_settings.json file. V1 is the older file format that requires a modules dictionary with a module_name and modules key that could in theory hold information on multiple modules in a single directory. """ if 'module_name' in settings: modname = settings['module_name'] if 'modules' not in settings or len(settings['modules']) == 0: raise DataError("No modules defined in module_settings.json file") elif len(settings['modules']) > 1: raise DataError("Multiple modules defined in module_settings.json file", modules=[x for x in settings['modules']]) else: modname = list(settings['modules'])[0] if modname not in settings['modules']: raise DataError("Module name does not correspond with an entry in the modules directory", name=modname, modules=[x for x in settings['modules']]) release_info = self._load_release_info(settings) modsettings = settings['modules'][modname] architectures = settings.get('architectures', {}) target_defs = settings.get('module_targets', {}) targets = target_defs.get(modname, []) return TileInfo(modname, modsettings, architectures, targets, release_info)
python
def _find_v1_settings(self, settings): if 'module_name' in settings: modname = settings['module_name'] if 'modules' not in settings or len(settings['modules']) == 0: raise DataError("No modules defined in module_settings.json file") elif len(settings['modules']) > 1: raise DataError("Multiple modules defined in module_settings.json file", modules=[x for x in settings['modules']]) else: modname = list(settings['modules'])[0] if modname not in settings['modules']: raise DataError("Module name does not correspond with an entry in the modules directory", name=modname, modules=[x for x in settings['modules']]) release_info = self._load_release_info(settings) modsettings = settings['modules'][modname] architectures = settings.get('architectures', {}) target_defs = settings.get('module_targets', {}) targets = target_defs.get(modname, []) return TileInfo(modname, modsettings, architectures, targets, release_info)
[ "def", "_find_v1_settings", "(", "self", ",", "settings", ")", ":", "if", "'module_name'", "in", "settings", ":", "modname", "=", "settings", "[", "'module_name'", "]", "if", "'modules'", "not", "in", "settings", "or", "len", "(", "settings", "[", "'modules'...
Parse a v1 module_settings.json file. V1 is the older file format that requires a modules dictionary with a module_name and modules key that could in theory hold information on multiple modules in a single directory.
[ "Parse", "a", "v1", "module_settings", ".", "json", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/iotileobj.py#L129-L158
23,250
iotile/coretools
iotilecore/iotile/core/dev/iotileobj.py
IOTile._ensure_product_string
def _ensure_product_string(cls, product): """Ensure that all product locations are strings. Older components specify paths as lists of path components. Join those paths into a normal path string. """ if isinstance(product, str): return product if isinstance(product, list): return os.path.join(*product) raise DataError("Unknown object (not str or list) specified as a component product", product=product)
python
def _ensure_product_string(cls, product): if isinstance(product, str): return product if isinstance(product, list): return os.path.join(*product) raise DataError("Unknown object (not str or list) specified as a component product", product=product)
[ "def", "_ensure_product_string", "(", "cls", ",", "product", ")", ":", "if", "isinstance", "(", "product", ",", "str", ")", ":", "return", "product", "if", "isinstance", "(", "product", ",", "list", ")", ":", "return", "os", ".", "path", ".", "join", "...
Ensure that all product locations are strings. Older components specify paths as lists of path components. Join those paths into a normal path string.
[ "Ensure", "that", "all", "product", "locations", "are", "strings", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/iotileobj.py#L345-L358
23,251
iotile/coretools
iotilecore/iotile/core/dev/iotileobj.py
IOTile.find_products
def find_products(self, product_type): """Search for products of a given type. Search through the products declared by this IOTile component and return only those matching the given type. If the product is described by the path to a file, a complete normalized path will be returned. The path could be different depending on whether this IOTile component is in development or release mode. The behavior of this function when filter_products has been called is slightly different based on whether product_type is in LIST_PRODUCTS or not. If product type is in LIST_PRODUCTS, then all matching products are returned if product_type itself was passed. So to get all tilebus_definitions you would call ``filter_products('tilebus_definitions')`` By contrast, other products are filtered product-by-product. So there is no way to filter and get **all libraries**. Instead you pass the specific product names of the libraries that you want to ``filter_products`` and those specific libraries are returned. Passing the literal string ``library`` to ``filter_products`` will not return only the libraries, it will return nothing since no library is named ``library``. Args: product_type (str): The type of product that we wish to return. Returns: list of str: The list of all products of the given type. If no such products are found, an empty list will be returned. If filter_products() has been called and the filter does not include this product type, an empty list will be returned. """ if self.filter_prods and product_type in self.LIST_PRODUCTS and product_type not in self.desired_prods: return [] if product_type in self.LIST_PRODUCTS: found_products = self.products.get(product_type, []) else: found_products = [x[0] for x in self.products.items() if x[1] == product_type and (not self.filter_prods or x[0] in self.desired_prods)] found_products = [self._ensure_product_string(x) for x in found_products] declaration = self.PATH_PRODUCTS.get(product_type) if declaration is not None: found_products = [self._process_product_path(x, declaration) for x in found_products] return found_products
python
def find_products(self, product_type): if self.filter_prods and product_type in self.LIST_PRODUCTS and product_type not in self.desired_prods: return [] if product_type in self.LIST_PRODUCTS: found_products = self.products.get(product_type, []) else: found_products = [x[0] for x in self.products.items() if x[1] == product_type and (not self.filter_prods or x[0] in self.desired_prods)] found_products = [self._ensure_product_string(x) for x in found_products] declaration = self.PATH_PRODUCTS.get(product_type) if declaration is not None: found_products = [self._process_product_path(x, declaration) for x in found_products] return found_products
[ "def", "find_products", "(", "self", ",", "product_type", ")", ":", "if", "self", ".", "filter_prods", "and", "product_type", "in", "self", ".", "LIST_PRODUCTS", "and", "product_type", "not", "in", "self", ".", "desired_prods", ":", "return", "[", "]", "if",...
Search for products of a given type. Search through the products declared by this IOTile component and return only those matching the given type. If the product is described by the path to a file, a complete normalized path will be returned. The path could be different depending on whether this IOTile component is in development or release mode. The behavior of this function when filter_products has been called is slightly different based on whether product_type is in LIST_PRODUCTS or not. If product type is in LIST_PRODUCTS, then all matching products are returned if product_type itself was passed. So to get all tilebus_definitions you would call ``filter_products('tilebus_definitions')`` By contrast, other products are filtered product-by-product. So there is no way to filter and get **all libraries**. Instead you pass the specific product names of the libraries that you want to ``filter_products`` and those specific libraries are returned. Passing the literal string ``library`` to ``filter_products`` will not return only the libraries, it will return nothing since no library is named ``library``. Args: product_type (str): The type of product that we wish to return. Returns: list of str: The list of all products of the given type. If no such products are found, an empty list will be returned. If filter_products() has been called and the filter does not include this product type, an empty list will be returned.
[ "Search", "for", "products", "of", "a", "given", "type", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/iotileobj.py#L374-L424
23,252
iotile/coretools
iotilecore/iotile/core/dev/iotileobj.py
IOTile.library_directories
def library_directories(self): """Return a list of directories containing any static libraries built by this IOTile.""" libs = self.find_products('library') if len(libs) > 0: return [os.path.join(self.output_folder)] return []
python
def library_directories(self): libs = self.find_products('library') if len(libs) > 0: return [os.path.join(self.output_folder)] return []
[ "def", "library_directories", "(", "self", ")", ":", "libs", "=", "self", ".", "find_products", "(", "'library'", ")", "if", "len", "(", "libs", ")", ">", "0", ":", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "output_folder", ")"...
Return a list of directories containing any static libraries built by this IOTile.
[ "Return", "a", "list", "of", "directories", "containing", "any", "static", "libraries", "built", "by", "this", "IOTile", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/iotileobj.py#L426-L434
23,253
iotile/coretools
iotilecore/iotile/core/dev/iotileobj.py
IOTile.filter_products
def filter_products(self, desired_prods): """When asked for a product, filter only those on this list.""" self.filter_prods = True self.desired_prods = set(desired_prods)
python
def filter_products(self, desired_prods): self.filter_prods = True self.desired_prods = set(desired_prods)
[ "def", "filter_products", "(", "self", ",", "desired_prods", ")", ":", "self", ".", "filter_prods", "=", "True", "self", ".", "desired_prods", "=", "set", "(", "desired_prods", ")" ]
When asked for a product, filter only those on this list.
[ "When", "asked", "for", "a", "product", "filter", "only", "those", "on", "this", "list", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/iotileobj.py#L436-L440
23,254
iotile/coretools
iotilesensorgraph/iotile/sg/output_formats/ascii.py
format_ascii
def format_ascii(sensor_graph): """Format this sensor graph as a loadable ascii file format. This includes commands to reset and clear previously stored sensor graphs. NB. This format does not include any required configuration variables that were specified in this sensor graph, so you should also output tha information separately in, e.g. the config format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string """ cmdfile = CommandFile("Sensor Graph", "1.0") # Clear any old sensor graph cmdfile.add("set_online", False) cmdfile.add("clear") cmdfile.add("reset") # Load in the nodes for node in sensor_graph.dump_nodes(): cmdfile.add('add_node', node) # Load in the streamers for streamer in sensor_graph.streamers: other = 0xFF if streamer.with_other is not None: other = streamer.with_other args = [streamer.selector, streamer.dest, streamer.automatic, streamer.format, streamer.report_type, other] cmdfile.add('add_streamer', *args) # Load all the constants for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()): cmdfile.add("push_reading", stream, value) # Persist the sensor graph cmdfile.add("persist") cmdfile.add("set_online", True) return cmdfile.dump()
python
def format_ascii(sensor_graph): cmdfile = CommandFile("Sensor Graph", "1.0") # Clear any old sensor graph cmdfile.add("set_online", False) cmdfile.add("clear") cmdfile.add("reset") # Load in the nodes for node in sensor_graph.dump_nodes(): cmdfile.add('add_node', node) # Load in the streamers for streamer in sensor_graph.streamers: other = 0xFF if streamer.with_other is not None: other = streamer.with_other args = [streamer.selector, streamer.dest, streamer.automatic, streamer.format, streamer.report_type, other] cmdfile.add('add_streamer', *args) # Load all the constants for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()): cmdfile.add("push_reading", stream, value) # Persist the sensor graph cmdfile.add("persist") cmdfile.add("set_online", True) return cmdfile.dump()
[ "def", "format_ascii", "(", "sensor_graph", ")", ":", "cmdfile", "=", "CommandFile", "(", "\"Sensor Graph\"", ",", "\"1.0\"", ")", "# Clear any old sensor graph", "cmdfile", ".", "add", "(", "\"set_online\"", ",", "False", ")", "cmdfile", ".", "add", "(", "\"cle...
Format this sensor graph as a loadable ascii file format. This includes commands to reset and clear previously stored sensor graphs. NB. This format does not include any required configuration variables that were specified in this sensor graph, so you should also output tha information separately in, e.g. the config format. Args: sensor_graph (SensorGraph): the sensor graph that we want to format Returns: str: The ascii output lines concatenated as a single string
[ "Format", "this", "sensor", "graph", "as", "a", "loadable", "ascii", "file", "format", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/output_formats/ascii.py#L11-L57
23,255
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.clear
def clear(self): """Clear all nodes from this sensor_graph. This function is equivalent to just creating a new SensorGraph() object from scratch. It does not clear any data from the SensorLog, however. """ self.roots = [] self.nodes = [] self.streamers = [] self.constant_database = {} self.metadata_database = {} self.config_database = {}
python
def clear(self): self.roots = [] self.nodes = [] self.streamers = [] self.constant_database = {} self.metadata_database = {} self.config_database = {}
[ "def", "clear", "(", "self", ")", ":", "self", ".", "roots", "=", "[", "]", "self", ".", "nodes", "=", "[", "]", "self", ".", "streamers", "=", "[", "]", "self", ".", "constant_database", "=", "{", "}", "self", ".", "metadata_database", "=", "{", ...
Clear all nodes from this sensor_graph. This function is equivalent to just creating a new SensorGraph() object from scratch. It does not clear any data from the SensorLog, however.
[ "Clear", "all", "nodes", "from", "this", "sensor_graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L55-L68
23,256
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_node
def add_node(self, node_descriptor): """Add a node to the sensor graph based on the description given. The node_descriptor must follow the sensor graph DSL and describe a node whose input nodes already exist. Args: node_descriptor (str): A description of the node to be added including its inputs, triggering conditions, processing function and output stream. """ if self._max_nodes is not None and len(self.nodes) >= self._max_nodes: raise ResourceUsageError("Maximum number of nodes exceeded", max_nodes=self._max_nodes) node, inputs, processor = parse_node_descriptor(node_descriptor, self.model) in_root = False for i, input_data in enumerate(inputs): selector, trigger = input_data walker = self.sensor_log.create_walker(selector) # Constant walkers begin life initialized to 0 so they always read correctly if walker.selector.inexhaustible: walker.reading = IOTileReading(0xFFFFFFFF, walker.selector.as_stream(), 0) node.connect_input(i, walker, trigger) if selector.input and not in_root: self.roots.append(node) in_root = True # Make sure we only add to root list once else: found = False for other in self.nodes: if selector.matches(other.stream): other.connect_output(node) found = True if not found and selector.buffered: raise NodeConnectionError("Node has input that refers to another node that has not been created yet", node_descriptor=node_descriptor, input_selector=str(selector), input_index=i) # Also make sure we add this node's output to any other existing node's inputs # this is important for constant nodes that may be written from multiple places # FIXME: Make sure when we emit nodes, they are topologically sorted for other_node in self.nodes: for selector, trigger in other_node.inputs: if selector.matches(node.stream): node.connect_output(other_node) # Find and load the processing function for this node func = self.find_processing_function(processor) if func is None: raise ProcessingFunctionError("Could not find processing function in installed packages", func_name=processor) node.set_func(processor, func) self.nodes.append(node)
python
def add_node(self, node_descriptor): if self._max_nodes is not None and len(self.nodes) >= self._max_nodes: raise ResourceUsageError("Maximum number of nodes exceeded", max_nodes=self._max_nodes) node, inputs, processor = parse_node_descriptor(node_descriptor, self.model) in_root = False for i, input_data in enumerate(inputs): selector, trigger = input_data walker = self.sensor_log.create_walker(selector) # Constant walkers begin life initialized to 0 so they always read correctly if walker.selector.inexhaustible: walker.reading = IOTileReading(0xFFFFFFFF, walker.selector.as_stream(), 0) node.connect_input(i, walker, trigger) if selector.input and not in_root: self.roots.append(node) in_root = True # Make sure we only add to root list once else: found = False for other in self.nodes: if selector.matches(other.stream): other.connect_output(node) found = True if not found and selector.buffered: raise NodeConnectionError("Node has input that refers to another node that has not been created yet", node_descriptor=node_descriptor, input_selector=str(selector), input_index=i) # Also make sure we add this node's output to any other existing node's inputs # this is important for constant nodes that may be written from multiple places # FIXME: Make sure when we emit nodes, they are topologically sorted for other_node in self.nodes: for selector, trigger in other_node.inputs: if selector.matches(node.stream): node.connect_output(other_node) # Find and load the processing function for this node func = self.find_processing_function(processor) if func is None: raise ProcessingFunctionError("Could not find processing function in installed packages", func_name=processor) node.set_func(processor, func) self.nodes.append(node)
[ "def", "add_node", "(", "self", ",", "node_descriptor", ")", ":", "if", "self", ".", "_max_nodes", "is", "not", "None", "and", "len", "(", "self", ".", "nodes", ")", ">=", "self", ".", "_max_nodes", ":", "raise", "ResourceUsageError", "(", "\"Maximum numbe...
Add a node to the sensor graph based on the description given. The node_descriptor must follow the sensor graph DSL and describe a node whose input nodes already exist. Args: node_descriptor (str): A description of the node to be added including its inputs, triggering conditions, processing function and output stream.
[ "Add", "a", "node", "to", "the", "sensor", "graph", "based", "on", "the", "description", "given", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L70-L127
23,257
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_config
def add_config(self, slot, config_id, config_type, value): """Add a config variable assignment to this sensor graph. Args: slot (SlotIdentifier): The slot identifier that this config variable is assigned to. config_id (int): The 16-bit id of this config_id config_type (str): The type of the config variable, currently supported are fixed width integer types, strings and binary blobs. value (str|int|bytes): The value to assign to the config variable. """ if slot not in self.config_database: self.config_database[slot] = {} self.config_database[slot][config_id] = (config_type, value)
python
def add_config(self, slot, config_id, config_type, value): if slot not in self.config_database: self.config_database[slot] = {} self.config_database[slot][config_id] = (config_type, value)
[ "def", "add_config", "(", "self", ",", "slot", ",", "config_id", ",", "config_type", ",", "value", ")", ":", "if", "slot", "not", "in", "self", ".", "config_database", ":", "self", ".", "config_database", "[", "slot", "]", "=", "{", "}", "self", ".", ...
Add a config variable assignment to this sensor graph. Args: slot (SlotIdentifier): The slot identifier that this config variable is assigned to. config_id (int): The 16-bit id of this config_id config_type (str): The type of the config variable, currently supported are fixed width integer types, strings and binary blobs. value (str|int|bytes): The value to assign to the config variable.
[ "Add", "a", "config", "variable", "assignment", "to", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L129-L145
23,258
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_streamer
def add_streamer(self, streamer): """Add a streamer to this sensor graph. Args: streamer (DataStreamer): The streamer we want to add """ if self._max_streamers is not None and len(self.streamers) >= self._max_streamers: raise ResourceUsageError("Maximum number of streamers exceeded", max_streamers=self._max_streamers) streamer.link_to_storage(self.sensor_log) streamer.index = len(self.streamers) self.streamers.append(streamer)
python
def add_streamer(self, streamer): if self._max_streamers is not None and len(self.streamers) >= self._max_streamers: raise ResourceUsageError("Maximum number of streamers exceeded", max_streamers=self._max_streamers) streamer.link_to_storage(self.sensor_log) streamer.index = len(self.streamers) self.streamers.append(streamer)
[ "def", "add_streamer", "(", "self", ",", "streamer", ")", ":", "if", "self", ".", "_max_streamers", "is", "not", "None", "and", "len", "(", "self", ".", "streamers", ")", ">=", "self", ".", "_max_streamers", ":", "raise", "ResourceUsageError", "(", "\"Maxi...
Add a streamer to this sensor graph. Args: streamer (DataStreamer): The streamer we want to add
[ "Add", "a", "streamer", "to", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L147-L160
23,259
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_constant
def add_constant(self, stream, value): """Store a constant value for use in this sensor graph. Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers. Args: stream (DataStream): The constant stream to assign the value to value (int): The value to assign. """ if stream in self.constant_database: raise ArgumentError("Attempted to set the same constant twice", stream=stream, old_value=self.constant_database[stream], new_value=value) self.constant_database[stream] = value
python
def add_constant(self, stream, value): if stream in self.constant_database: raise ArgumentError("Attempted to set the same constant twice", stream=stream, old_value=self.constant_database[stream], new_value=value) self.constant_database[stream] = value
[ "def", "add_constant", "(", "self", ",", "stream", ",", "value", ")", ":", "if", "stream", "in", "self", ".", "constant_database", ":", "raise", "ArgumentError", "(", "\"Attempted to set the same constant twice\"", ",", "stream", "=", "stream", ",", "old_value", ...
Store a constant value for use in this sensor graph. Constant assignments occur after all sensor graph nodes have been allocated since they must be propogated to all appropriate virtual stream walkers. Args: stream (DataStream): The constant stream to assign the value to value (int): The value to assign.
[ "Store", "a", "constant", "value", "for", "use", "in", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L162-L177
23,260
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.add_metadata
def add_metadata(self, name, value): """Attach a piece of metadata to this sensorgraph. Metadata is not used during the simulation of a sensorgraph but allows it to convey additional context that may be used during code generation. For example, associating an `app_tag` with a sensorgraph allows the snippet code generator to set that app_tag on a device when programming the sensorgraph. Arg: name (str): The name of the metadata that we wish to associate with this sensorgraph. value (object): The value we wish to store. """ if name in self.metadata_database: raise ArgumentError("Attempted to set the same metadata value twice", name=name, old_value=self.metadata_database[name], new_value=value) self.metadata_database[name] = value
python
def add_metadata(self, name, value): if name in self.metadata_database: raise ArgumentError("Attempted to set the same metadata value twice", name=name, old_value=self.metadata_database[name], new_value=value) self.metadata_database[name] = value
[ "def", "add_metadata", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "in", "self", ".", "metadata_database", ":", "raise", "ArgumentError", "(", "\"Attempted to set the same metadata value twice\"", ",", "name", "=", "name", ",", "old_value", "...
Attach a piece of metadata to this sensorgraph. Metadata is not used during the simulation of a sensorgraph but allows it to convey additional context that may be used during code generation. For example, associating an `app_tag` with a sensorgraph allows the snippet code generator to set that app_tag on a device when programming the sensorgraph. Arg: name (str): The name of the metadata that we wish to associate with this sensorgraph. value (object): The value we wish to store.
[ "Attach", "a", "piece", "of", "metadata", "to", "this", "sensorgraph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L179-L197
23,261
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.initialize_remaining_constants
def initialize_remaining_constants(self, value=0): """Ensure that all constant streams referenced in the sensor graph have a value. Constant streams that are automatically created by the compiler are initialized as part of the compilation process but it's possible that the user references other constant streams but never assigns them an explicit initial value. This function will initialize them all to a default value (0 if not passed) and return the streams that were so initialized. Args: value (int): Optional value to use to initialize all uninitialized constants. Defaults to 0 if not passed. Returns: list(DataStream): A list of all of the constant streams that were not previously initialized and were initialized to the given value in this function. """ remaining = [] for node, _inputs, _outputs in self.iterate_bfs(): streams = node.input_streams() + [node.stream] for stream in streams: if stream.stream_type is not DataStream.ConstantType: continue if stream not in self.constant_database: self.add_constant(stream, value) remaining.append(stream) return remaining
python
def initialize_remaining_constants(self, value=0): remaining = [] for node, _inputs, _outputs in self.iterate_bfs(): streams = node.input_streams() + [node.stream] for stream in streams: if stream.stream_type is not DataStream.ConstantType: continue if stream not in self.constant_database: self.add_constant(stream, value) remaining.append(stream) return remaining
[ "def", "initialize_remaining_constants", "(", "self", ",", "value", "=", "0", ")", ":", "remaining", "=", "[", "]", "for", "node", ",", "_inputs", ",", "_outputs", "in", "self", ".", "iterate_bfs", "(", ")", ":", "streams", "=", "node", ".", "input_strea...
Ensure that all constant streams referenced in the sensor graph have a value. Constant streams that are automatically created by the compiler are initialized as part of the compilation process but it's possible that the user references other constant streams but never assigns them an explicit initial value. This function will initialize them all to a default value (0 if not passed) and return the streams that were so initialized. Args: value (int): Optional value to use to initialize all uninitialized constants. Defaults to 0 if not passed. Returns: list(DataStream): A list of all of the constant streams that were not previously initialized and were initialized to the given value in this function.
[ "Ensure", "that", "all", "constant", "streams", "referenced", "in", "the", "sensor", "graph", "have", "a", "value", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L199-L230
23,262
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.load_constants
def load_constants(self): """Load all constants into their respective streams. All previous calls to add_constant stored a constant value that should be associated with virtual stream walkers. This function actually calls push_stream in order to push all of the constant values to their walkers. """ for stream, value in self.constant_database.items(): self.sensor_log.push(stream, IOTileReading(0, stream.encode(), value))
python
def load_constants(self): for stream, value in self.constant_database.items(): self.sensor_log.push(stream, IOTileReading(0, stream.encode(), value))
[ "def", "load_constants", "(", "self", ")", ":", "for", "stream", ",", "value", "in", "self", ".", "constant_database", ".", "items", "(", ")", ":", "self", ".", "sensor_log", ".", "push", "(", "stream", ",", "IOTileReading", "(", "0", ",", "stream", "....
Load all constants into their respective streams. All previous calls to add_constant stored a constant value that should be associated with virtual stream walkers. This function actually calls push_stream in order to push all of the constant values to their walkers.
[ "Load", "all", "constants", "into", "their", "respective", "streams", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L232-L242
23,263
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.get_config
def get_config(self, slot, config_id): """Get a config variable assignment previously set on this sensor graph. Args: slot (SlotIdentifier): The slot that we are setting this config variable on. config_id (int): The 16-bit config variable identifier. Returns: (str, str|int): Returns a tuple with the type of the config variable and the value that is being set. Raises: ArgumentError: If the config variable is not currently set on the specified slot. """ if slot not in self.config_database: raise ArgumentError("No config variables have been set on specified slot", slot=slot) if config_id not in self.config_database[slot]: raise ArgumentError("Config variable has not been set on specified slot", slot=slot, config_id=config_id) return self.config_database[slot][config_id]
python
def get_config(self, slot, config_id): if slot not in self.config_database: raise ArgumentError("No config variables have been set on specified slot", slot=slot) if config_id not in self.config_database[slot]: raise ArgumentError("Config variable has not been set on specified slot", slot=slot, config_id=config_id) return self.config_database[slot][config_id]
[ "def", "get_config", "(", "self", ",", "slot", ",", "config_id", ")", ":", "if", "slot", "not", "in", "self", ".", "config_database", ":", "raise", "ArgumentError", "(", "\"No config variables have been set on specified slot\"", ",", "slot", "=", "slot", ")", "i...
Get a config variable assignment previously set on this sensor graph. Args: slot (SlotIdentifier): The slot that we are setting this config variable on. config_id (int): The 16-bit config variable identifier. Returns: (str, str|int): Returns a tuple with the type of the config variable and the value that is being set. Raises: ArgumentError: If the config variable is not currently set on the specified slot.
[ "Get", "a", "config", "variable", "assignment", "previously", "set", "on", "this", "sensor", "graph", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L244-L267
23,264
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.is_output
def is_output(self, stream): """Check if a stream is a sensor graph output. Return: bool """ for streamer in self.streamers: if streamer.selector.matches(stream): return True return False
python
def is_output(self, stream): for streamer in self.streamers: if streamer.selector.matches(stream): return True return False
[ "def", "is_output", "(", "self", ",", "stream", ")", ":", "for", "streamer", "in", "self", ".", "streamers", ":", "if", "streamer", ".", "selector", ".", "matches", "(", "stream", ")", ":", "return", "True", "return", "False" ]
Check if a stream is a sensor graph output. Return: bool
[ "Check", "if", "a", "stream", "is", "a", "sensor", "graph", "output", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L269-L280
23,265
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.get_tick
def get_tick(self, name): """Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph compiler and used for fast operations and finally there are several field configurable ticks that can be used for setting up configurable timers. This is done by setting a config variable on the controller with the desired tick interval, which is then interpreted by this function. The appropriate config_id to use is listed in `known_constants.py` Returns: int: 0 if the tick is disabled, otherwise the number of seconds between each tick """ name_map = { 'fast': config_fast_tick_secs, 'user1': config_tick1_secs, 'user2': config_tick2_secs } config = name_map.get(name) if config is None: raise ArgumentError("Unknown tick requested", name=name) slot = SlotIdentifier.FromString('controller') try: var = self.get_config(slot, config) return var[1] except ArgumentError: return 0
python
def get_tick(self, name): name_map = { 'fast': config_fast_tick_secs, 'user1': config_tick1_secs, 'user2': config_tick2_secs } config = name_map.get(name) if config is None: raise ArgumentError("Unknown tick requested", name=name) slot = SlotIdentifier.FromString('controller') try: var = self.get_config(slot, config) return var[1] except ArgumentError: return 0
[ "def", "get_tick", "(", "self", ",", "name", ")", ":", "name_map", "=", "{", "'fast'", ":", "config_fast_tick_secs", ",", "'user1'", ":", "config_tick1_secs", ",", "'user2'", ":", "config_tick2_secs", "}", "config", "=", "name_map", ".", "get", "(", "name", ...
Check the config variables to see if there is a configurable tick. Sensor Graph has a built-in 10 second tick that is sent every 10 seconds to allow for triggering timed events. There is a second 'user' tick that is generated internally by the sensorgraph compiler and used for fast operations and finally there are several field configurable ticks that can be used for setting up configurable timers. This is done by setting a config variable on the controller with the desired tick interval, which is then interpreted by this function. The appropriate config_id to use is listed in `known_constants.py` Returns: int: 0 if the tick is disabled, otherwise the number of seconds between each tick
[ "Check", "the", "config", "variables", "to", "see", "if", "there", "is", "a", "configurable", "tick", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L282-L318
23,266
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.mark_streamer
def mark_streamer(self, index): """Manually mark a streamer that should trigger. The next time check_streamers is called, the given streamer will be manually marked that it should trigger, which will cause it to trigger unless it has no data. Args: index (int): The index of the streamer that we should mark as manually triggered. Raises: ArgumentError: If the streamer index is invalid. """ self._logger.debug("Marking streamer %d manually", index) if index >= len(self.streamers): raise ArgumentError("Invalid streamer index", index=index, num_streamers=len(self.streamers)) self._manually_triggered_streamers.add(index)
python
def mark_streamer(self, index): self._logger.debug("Marking streamer %d manually", index) if index >= len(self.streamers): raise ArgumentError("Invalid streamer index", index=index, num_streamers=len(self.streamers)) self._manually_triggered_streamers.add(index)
[ "def", "mark_streamer", "(", "self", ",", "index", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Marking streamer %d manually\"", ",", "index", ")", "if", "index", ">=", "len", "(", "self", ".", "streamers", ")", ":", "raise", "ArgumentError", "(...
Manually mark a streamer that should trigger. The next time check_streamers is called, the given streamer will be manually marked that it should trigger, which will cause it to trigger unless it has no data. Args: index (int): The index of the streamer that we should mark as manually triggered. Raises: ArgumentError: If the streamer index is invalid.
[ "Manually", "mark", "a", "streamer", "that", "should", "trigger", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L358-L377
23,267
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.check_streamers
def check_streamers(self, blacklist=None): """Check if any streamers are ready to produce a report. You can limit what streamers are checked by passing a set-like object into blacklist. This method is the primary way to see when you should poll a given streamer for its next report. Note, this function is not idempotent. If a streamer is marked as manual and it is triggered from a node rule inside the sensor_graph, that trigger will only last as long as the next call to check_streamers() so you need to explicitly build a report on all ready streamers before calling check_streamers again. Args: blacklist (set): Optional set of streamer indices that should not be checked right now. Returns: list of DataStreamer: A list of the ready streamers. """ ready = [] selected = set() for i, streamer in enumerate(self.streamers): if blacklist is not None and i in blacklist: continue if i in selected: continue marked = False if i in self._manually_triggered_streamers: marked = True self._manually_triggered_streamers.remove(i) if streamer.triggered(marked): self._logger.debug("Streamer %d triggered, manual=%s", i, marked) ready.append(streamer) selected.add(i) # Handle streamers triggered with another for j, streamer2 in enumerate(self.streamers[i:]): if streamer2.with_other == i and j not in selected and streamer2.triggered(True): self._logger.debug("Streamer %d triggered due to with-other on %d", j, i) ready.append(streamer2) selected.add(j) return ready
python
def check_streamers(self, blacklist=None): ready = [] selected = set() for i, streamer in enumerate(self.streamers): if blacklist is not None and i in blacklist: continue if i in selected: continue marked = False if i in self._manually_triggered_streamers: marked = True self._manually_triggered_streamers.remove(i) if streamer.triggered(marked): self._logger.debug("Streamer %d triggered, manual=%s", i, marked) ready.append(streamer) selected.add(i) # Handle streamers triggered with another for j, streamer2 in enumerate(self.streamers[i:]): if streamer2.with_other == i and j not in selected and streamer2.triggered(True): self._logger.debug("Streamer %d triggered due to with-other on %d", j, i) ready.append(streamer2) selected.add(j) return ready
[ "def", "check_streamers", "(", "self", ",", "blacklist", "=", "None", ")", ":", "ready", "=", "[", "]", "selected", "=", "set", "(", ")", "for", "i", ",", "streamer", "in", "enumerate", "(", "self", ".", "streamers", ")", ":", "if", "blacklist", "is"...
Check if any streamers are ready to produce a report. You can limit what streamers are checked by passing a set-like object into blacklist. This method is the primary way to see when you should poll a given streamer for its next report. Note, this function is not idempotent. If a streamer is marked as manual and it is triggered from a node rule inside the sensor_graph, that trigger will only last as long as the next call to check_streamers() so you need to explicitly build a report on all ready streamers before calling check_streamers again. Args: blacklist (set): Optional set of streamer indices that should not be checked right now. Returns: list of DataStreamer: A list of the ready streamers.
[ "Check", "if", "any", "streamers", "are", "ready", "to", "produce", "a", "report", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L379-L429
23,268
iotile/coretools
iotilesensorgraph/iotile/sg/graph.py
SensorGraph.sort_nodes
def sort_nodes(self): """Topologically sort all of our nodes. Topologically sorting our nodes makes nodes that are inputs to other nodes come first in the list of nodes. This is important to do before programming a sensorgraph into an embedded device whose engine assumes a topologically sorted graph. The sorting is done in place on self.nodes """ node_map = {id(node): i for i, node in enumerate(self.nodes)} node_deps = {} for node, inputs, _outputs in self.iterate_bfs(): node_index = node_map[id(node)] deps = {node_map[id(x)] for x in inputs} node_deps[node_index] = deps # Now that we have our dependency tree properly built, topologically # sort the nodes and reorder them. node_order = toposort_flatten(node_deps) self.nodes = [self.nodes[x] for x in node_order] #Check root nodes all topographically sorted to the beginning for root in self.roots: if root not in self.nodes[0:len(self.roots)]: raise NodeConnectionError("Inputs not sorted in the beginning", node=str(root), node_position=self.nodes.index(root))
python
def sort_nodes(self): node_map = {id(node): i for i, node in enumerate(self.nodes)} node_deps = {} for node, inputs, _outputs in self.iterate_bfs(): node_index = node_map[id(node)] deps = {node_map[id(x)] for x in inputs} node_deps[node_index] = deps # Now that we have our dependency tree properly built, topologically # sort the nodes and reorder them. node_order = toposort_flatten(node_deps) self.nodes = [self.nodes[x] for x in node_order] #Check root nodes all topographically sorted to the beginning for root in self.roots: if root not in self.nodes[0:len(self.roots)]: raise NodeConnectionError("Inputs not sorted in the beginning", node=str(root), node_position=self.nodes.index(root))
[ "def", "sort_nodes", "(", "self", ")", ":", "node_map", "=", "{", "id", "(", "node", ")", ":", "i", "for", "i", ",", "node", "in", "enumerate", "(", "self", ".", "nodes", ")", "}", "node_deps", "=", "{", "}", "for", "node", ",", "inputs", ",", ...
Topologically sort all of our nodes. Topologically sorting our nodes makes nodes that are inputs to other nodes come first in the list of nodes. This is important to do before programming a sensorgraph into an embedded device whose engine assumes a topologically sorted graph. The sorting is done in place on self.nodes
[ "Topologically", "sort", "all", "of", "our", "nodes", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L461-L489
23,269
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ipkg.py
generate
def generate(env): """Add Builders and construction variables for ipkg to an Environment.""" try: bld = env['BUILDERS']['Ipkg'] except KeyError: bld = SCons.Builder.Builder(action='$IPKGCOM', suffix='$IPKGSUFFIX', source_scanner=None, target_scanner=None) env['BUILDERS']['Ipkg'] = bld env['IPKG'] = 'ipkg-build' env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}' if env.WhereIs('id'): env['IPKGUSER'] = os.popen('id -un').read().strip() env['IPKGGROUP'] = os.popen('id -gn').read().strip() env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP') env['IPKGSUFFIX'] = '.ipk'
python
def generate(env): try: bld = env['BUILDERS']['Ipkg'] except KeyError: bld = SCons.Builder.Builder(action='$IPKGCOM', suffix='$IPKGSUFFIX', source_scanner=None, target_scanner=None) env['BUILDERS']['Ipkg'] = bld env['IPKG'] = 'ipkg-build' env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}' if env.WhereIs('id'): env['IPKGUSER'] = os.popen('id -un').read().strip() env['IPKGGROUP'] = os.popen('id -gn').read().strip() env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP') env['IPKGSUFFIX'] = '.ipk'
[ "def", "generate", "(", "env", ")", ":", "try", ":", "bld", "=", "env", "[", "'BUILDERS'", "]", "[", "'Ipkg'", "]", "except", "KeyError", ":", "bld", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "'$IPKGCOM'", ",", "suffix", "=", ...
Add Builders and construction variables for ipkg to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "ipkg", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ipkg.py#L42-L61
23,270
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
InputTrigger.triggered
def triggered(self, walker): """Check if this input is triggered on the given stream walker. Args: walker (StreamWalker): The walker to check Returns: bool: Whether this trigger is triggered or not """ if self.use_count: comp_value = walker.count() else: if walker.count() == 0: return False comp_value = walker.peek().value return self.comp_function(comp_value, self.reference)
python
def triggered(self, walker): if self.use_count: comp_value = walker.count() else: if walker.count() == 0: return False comp_value = walker.peek().value return self.comp_function(comp_value, self.reference)
[ "def", "triggered", "(", "self", ",", "walker", ")", ":", "if", "self", ".", "use_count", ":", "comp_value", "=", "walker", ".", "count", "(", ")", "else", ":", "if", "walker", ".", "count", "(", ")", "==", "0", ":", "return", "False", "comp_value", ...
Check if this input is triggered on the given stream walker. Args: walker (StreamWalker): The walker to check Returns: bool: Whether this trigger is triggered or not
[ "Check", "if", "this", "input", "is", "triggered", "on", "the", "given", "stream", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L75-L93
23,271
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.connect_input
def connect_input(self, index, walker, trigger=None): """Connect an input to a stream walker. If the input is already connected to something an exception is thrown. Otherwise the walker is used to read inputs for that input. A triggering condition can optionally be passed that will determine when this input will be considered as triggered. Args: index (int): The index of the input that we want to connect walker (StreamWalker): The stream walker to use for the input trigger (InputTrigger): The trigger to use for the input. If no trigger is specified, the input is considered to always be triggered (so TrueTrigger is used) """ if trigger is None: trigger = TrueTrigger() if index >= len(self.inputs): raise TooManyInputsError("Input index exceeded max number of inputs", index=index, max_inputs=len(self.inputs), stream=self.stream) self.inputs[index] = (walker, trigger)
python
def connect_input(self, index, walker, trigger=None): if trigger is None: trigger = TrueTrigger() if index >= len(self.inputs): raise TooManyInputsError("Input index exceeded max number of inputs", index=index, max_inputs=len(self.inputs), stream=self.stream) self.inputs[index] = (walker, trigger)
[ "def", "connect_input", "(", "self", ",", "index", ",", "walker", ",", "trigger", "=", "None", ")", ":", "if", "trigger", "is", "None", ":", "trigger", "=", "TrueTrigger", "(", ")", "if", "index", ">=", "len", "(", "self", ".", "inputs", ")", ":", ...
Connect an input to a stream walker. If the input is already connected to something an exception is thrown. Otherwise the walker is used to read inputs for that input. A triggering condition can optionally be passed that will determine when this input will be considered as triggered. Args: index (int): The index of the input that we want to connect walker (StreamWalker): The stream walker to use for the input trigger (InputTrigger): The trigger to use for the input. If no trigger is specified, the input is considered to always be triggered (so TrueTrigger is used)
[ "Connect", "an", "input", "to", "a", "stream", "walker", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L177-L200
23,272
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.input_streams
def input_streams(self): """Return a list of DataStream objects for all singular input streams. This function only returns individual streams, not the streams that would be selected from a selector like 'all outputs' for example. Returns: list(DataStream): A list of all of the individual DataStreams that are inputs of the node. Input selectors that select multiple streams are not included """ streams = [] for walker, _trigger in self.inputs: if walker.selector is None or not walker.selector.singular: continue streams.append(walker.selector.as_stream()) return streams
python
def input_streams(self): streams = [] for walker, _trigger in self.inputs: if walker.selector is None or not walker.selector.singular: continue streams.append(walker.selector.as_stream()) return streams
[ "def", "input_streams", "(", "self", ")", ":", "streams", "=", "[", "]", "for", "walker", ",", "_trigger", "in", "self", ".", "inputs", ":", "if", "walker", ".", "selector", "is", "None", "or", "not", "walker", ".", "selector", ".", "singular", ":", ...
Return a list of DataStream objects for all singular input streams. This function only returns individual streams, not the streams that would be selected from a selector like 'all outputs' for example. Returns: list(DataStream): A list of all of the individual DataStreams that are inputs of the node. Input selectors that select multiple streams are not included
[ "Return", "a", "list", "of", "DataStream", "objects", "for", "all", "singular", "input", "streams", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L202-L221
23,273
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.find_input
def find_input(self, stream): """Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None """ for i, input_x in enumerate(self.inputs): if input_x[0].matches(stream): return i
python
def find_input(self, stream): for i, input_x in enumerate(self.inputs): if input_x[0].matches(stream): return i
[ "def", "find_input", "(", "self", ",", "stream", ")", ":", "for", "i", ",", "input_x", "in", "enumerate", "(", "self", ".", "inputs", ")", ":", "if", "input_x", "[", "0", "]", ".", "matches", "(", "stream", ")", ":", "return", "i" ]
Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None
[ "Find", "the", "input", "that", "responds", "to", "this", "stream", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L223-L235
23,274
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.num_inputs
def num_inputs(self): """Return the number of connected inputs. Returns: int: The number of connected inputs """ num = 0 for walker, _ in self.inputs: if not isinstance(walker, InvalidStreamWalker): num += 1 return num
python
def num_inputs(self): num = 0 for walker, _ in self.inputs: if not isinstance(walker, InvalidStreamWalker): num += 1 return num
[ "def", "num_inputs", "(", "self", ")", ":", "num", "=", "0", "for", "walker", ",", "_", "in", "self", ".", "inputs", ":", "if", "not", "isinstance", "(", "walker", ",", "InvalidStreamWalker", ")", ":", "num", "+=", "1", "return", "num" ]
Return the number of connected inputs. Returns: int: The number of connected inputs
[ "Return", "the", "number", "of", "connected", "inputs", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L238-L251
23,275
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.connect_output
def connect_output(self, node): """Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output """ if len(self.outputs) == self.max_outputs: raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
python
def connect_output(self, node): if len(self.outputs) == self.max_outputs: raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
[ "def", "connect_output", "(", "self", ",", "node", ")", ":", "if", "len", "(", "self", ".", "outputs", ")", "==", "self", ".", "max_outputs", ":", "raise", "TooManyOutputsError", "(", "\"Attempted to connect too many nodes to the output of a node\"", ",", "max_outpu...
Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output
[ "Connect", "another", "node", "to", "our", "output", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L273-L286
23,276
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.triggered
def triggered(self): """Test if we should trigger our operation. We test the trigger condition on each of our inputs and then combine those triggers using our configured trigger combiner to get an overall result for whether this node is triggered. Returns: bool: True if we should trigger and False otherwise """ trigs = [x[1].triggered(x[0]) for x in self.inputs] if self.trigger_combiner == self.OrTriggerCombiner: return True in trigs return False not in trigs
python
def triggered(self): trigs = [x[1].triggered(x[0]) for x in self.inputs] if self.trigger_combiner == self.OrTriggerCombiner: return True in trigs return False not in trigs
[ "def", "triggered", "(", "self", ")", ":", "trigs", "=", "[", "x", "[", "1", "]", ".", "triggered", "(", "x", "[", "0", "]", ")", "for", "x", "in", "self", ".", "inputs", "]", "if", "self", ".", "trigger_combiner", "==", "self", ".", "OrTriggerCo...
Test if we should trigger our operation. We test the trigger condition on each of our inputs and then combine those triggers using our configured trigger combiner to get an overall result for whether this node is triggered. Returns: bool: True if we should trigger and False otherwise
[ "Test", "if", "we", "should", "trigger", "our", "operation", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L288-L304
23,277
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.set_func
def set_func(self, name, func): """Set the processing function to use for this node. Args: name (str): The name of the function to use. This is just stored for reference in case we need to serialize the node later. func (callable): A function that is called to process inputs for this node. It should have the following signature: callable(input1_walker, input2_walker, ...) It should return a list of IOTileReadings that are then pushed into the node's output stream """ self.func_name = name self.func = func
python
def set_func(self, name, func): self.func_name = name self.func = func
[ "def", "set_func", "(", "self", ",", "name", ",", "func", ")", ":", "self", ".", "func_name", "=", "name", "self", ".", "func", "=", "func" ]
Set the processing function to use for this node. Args: name (str): The name of the function to use. This is just stored for reference in case we need to serialize the node later. func (callable): A function that is called to process inputs for this node. It should have the following signature: callable(input1_walker, input2_walker, ...) It should return a list of IOTileReadings that are then pushed into the node's output stream
[ "Set", "the", "processing", "function", "to", "use", "for", "this", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L306-L321
23,278
iotile/coretools
iotilesensorgraph/iotile/sg/node.py
SGNode.process
def process(self, rpc_executor, mark_streamer=None): """Run this node's processing function. Args: rpc_executor (RPCExecutor): An object capable of executing RPCs in case we need to do that. mark_streamer (callable): Function that can be called to manually mark a streamer as triggered by index. Returns: list(IOTileReading): A list of IOTileReadings with the results of the processing function or an empty list if no results were produced """ if self.func is None: raise ProcessingFunctionError('No processing function set for node', stream=self.stream) results = self.func(*[x[0] for x in self.inputs], rpc_executor=rpc_executor, mark_streamer=mark_streamer) if results is None: results = [] return results
python
def process(self, rpc_executor, mark_streamer=None): if self.func is None: raise ProcessingFunctionError('No processing function set for node', stream=self.stream) results = self.func(*[x[0] for x in self.inputs], rpc_executor=rpc_executor, mark_streamer=mark_streamer) if results is None: results = [] return results
[ "def", "process", "(", "self", ",", "rpc_executor", ",", "mark_streamer", "=", "None", ")", ":", "if", "self", ".", "func", "is", "None", ":", "raise", "ProcessingFunctionError", "(", "'No processing function set for node'", ",", "stream", "=", "self", ".", "s...
Run this node's processing function. Args: rpc_executor (RPCExecutor): An object capable of executing RPCs in case we need to do that. mark_streamer (callable): Function that can be called to manually mark a streamer as triggered by index. Returns: list(IOTileReading): A list of IOTileReadings with the results of the processing function or an empty list if no results were produced
[ "Run", "this", "node", "s", "processing", "function", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node.py#L323-L345
23,279
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Fortran.py
FortranScan
def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = "(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = """(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case insensitive # \s+ : match one or more white space characters # (?!PROCEDURE) : but *don't* match if the next word matches # PROCEDURE (negative lookahead assertion), # case insensitive # (\w+) : match one or more alphanumeric characters # that make up the defined module name and # save it in a group def_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner
python
def FortranScan(path_variable="FORTRANPATH"): # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = "(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = """(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case insensitive # \s+ : match one or more white space characters # (?!PROCEDURE) : but *don't* match if the next word matches # PROCEDURE (negative lookahead assertion), # case insensitive # (\w+) : match one or more alphanumeric characters # that make up the defined module name and # save it in a group def_regex = """(?i)^\s*MODULE\s+(?!PROCEDURE)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner
[ "def", "FortranScan", "(", "path_variable", "=", "\"FORTRANPATH\"", ")", ":", "# The USE statement regex matches the following:", "#", "# USE module_name", "# USE :: module_name", "# USE, INTRINSIC :: module_name", "# USE, NON_INTRINSIC :: module_name", "#", "# Limitations"...
Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "source", "files", "for", "Fortran", "USE", "&", "INCLUDE", "statements" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Fortran.py#L126-L310
23,280
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cvf.py
generate
def generate(env): """Add Builders and construction variables for compaq visual fortran to an Environment.""" fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['OBJSUFFIX'] = '.obj' env['FORTRANMODDIR'] = '${TARGET.dir}' env['FORTRANMODDIRPREFIX'] = '/module:' env['FORTRANMODDIRSUFFIX'] = ''
python
def generate(env): fortran.generate(env) env['FORTRAN'] = 'f90' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:${TARGET.windows}' env['OBJSUFFIX'] = '.obj' env['FORTRANMODDIR'] = '${TARGET.dir}' env['FORTRANMODDIRPREFIX'] = '/module:' env['FORTRANMODDIRSUFFIX'] = ''
[ "def", "generate", "(", "env", ")", ":", "fortran", ".", "generate", "(", "env", ")", "env", "[", "'FORTRAN'", "]", "=", "'f90'", "env", "[", "'FORTRANCOM'", "]", "=", "'$FORTRAN $FORTRANFLAGS $_FORTRANMODFLAG $_FORTRANINCFLAGS /compile_only ${SOURCES.windows} /object:$...
Add Builders and construction variables for compaq visual fortran to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "compaq", "visual", "fortran", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cvf.py#L36-L49
23,281
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py
Value.read
def read(self): """Return the value. If necessary, the value is built.""" self.build() if not hasattr(self, 'built_value'): self.built_value = self.value return self.built_value
python
def read(self): self.build() if not hasattr(self, 'built_value'): self.built_value = self.value return self.built_value
[ "def", "read", "(", "self", ")", ":", "self", ".", "build", "(", ")", "if", "not", "hasattr", "(", "self", ",", "'built_value'", ")", ":", "self", ".", "built_value", "=", "self", ".", "value", "return", "self", ".", "built_value" ]
Return the value. If necessary, the value is built.
[ "Return", "the", "value", ".", "If", "necessary", "the", "value", "is", "built", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py#L120-L125
23,282
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py
Value.get_csig
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() self.get_ninfo().csig = contents return contents
python
def get_csig(self, calc=None): try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() self.get_ninfo().csig = contents return contents
[ "def", "get_csig", "(", "self", ",", "calc", "=", "None", ")", ":", "try", ":", "return", "self", ".", "ninfo", ".", "csig", "except", "AttributeError", ":", "pass", "contents", "=", "self", ".", "get_contents", "(", ")", "self", ".", "get_ninfo", "(",...
Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.
[ "Because", "we", "re", "a", "Python", "value", "node", "and", "don", "t", "have", "a", "real", "timestamp", "we", "get", "to", "ignore", "the", "calculator", "and", "just", "use", "the", "value", "contents", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Python.py#L155-L165
23,283
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_complex
def mark_complex(self, name, serializer, deserializer): """Mark a property as complex with serializer and deserializer functions. Args: name (str): The name of the complex property. serializer (callable): The function to call to serialize the property's value to something that can be saved in a json. deserializer (callable): The function to call to unserialize the property from a dict loaded by a json back to the original value. """ self._complex_properties[name] = (serializer, deserializer)
python
def mark_complex(self, name, serializer, deserializer): self._complex_properties[name] = (serializer, deserializer)
[ "def", "mark_complex", "(", "self", ",", "name", ",", "serializer", ",", "deserializer", ")", ":", "self", ".", "_complex_properties", "[", "name", "]", "=", "(", "serializer", ",", "deserializer", ")" ]
Mark a property as complex with serializer and deserializer functions. Args: name (str): The name of the complex property. serializer (callable): The function to call to serialize the property's value to something that can be saved in a json. deserializer (callable): The function to call to unserialize the property from a dict loaded by a json back to the original value.
[ "Mark", "a", "property", "as", "complex", "with", "serializer", "and", "deserializer", "functions", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L63-L74
23,284
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_typed_list
def mark_typed_list(self, name, type_object): """Mark a property as containing serializable objects of a given type. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a list of objects. This method requires that all members of the given list be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this list. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_list(obj): if obj is None: return None if not isinstance(obj, list): raise DataError("Property %s marked as list was not a list: %s" % (name, repr(obj))) return [x.dump() for x in obj] def _restore_list(obj): if obj is None: return obj return [type_object.Restore(x) for x in obj] self.mark_complex(name, _dump_list, _restore_list)
python
def mark_typed_list(self, name, type_object): if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_list(obj): if obj is None: return None if not isinstance(obj, list): raise DataError("Property %s marked as list was not a list: %s" % (name, repr(obj))) return [x.dump() for x in obj] def _restore_list(obj): if obj is None: return obj return [type_object.Restore(x) for x in obj] self.mark_complex(name, _dump_list, _restore_list)
[ "def", "mark_typed_list", "(", "self", ",", "name", ",", "type_object", ")", ":", "if", "not", "hasattr", "(", "type_object", ",", "'dump'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: dump()\"", "%", "type_object"...
Mark a property as containing serializable objects of a given type. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a list of objects. This method requires that all members of the given list be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this list.
[ "Mark", "a", "property", "as", "containing", "serializable", "objects", "of", "a", "given", "type", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L76-L111
23,285
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_typed_map
def mark_typed_map(self, name, type_object): """Mark a property as containing a map str to serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a dict of objects. This method requires that all members of the given dict be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this dict. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_map(obj): if obj is None: return None if not isinstance(obj, dict): raise DataError("Property %s marked as list was not a dict: %s" % (name, repr(obj))) return {key: val.dump() for key, val in obj.items()} def _restore_map(obj): if obj is None: return obj return {key: type_object.Restore(val) for key, val in obj.items()} self.mark_complex(name, _dump_map, _restore_map)
python
def mark_typed_map(self, name, type_object): if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_map(obj): if obj is None: return None if not isinstance(obj, dict): raise DataError("Property %s marked as list was not a dict: %s" % (name, repr(obj))) return {key: val.dump() for key, val in obj.items()} def _restore_map(obj): if obj is None: return obj return {key: type_object.Restore(val) for key, val in obj.items()} self.mark_complex(name, _dump_map, _restore_map)
[ "def", "mark_typed_map", "(", "self", ",", "name", ",", "type_object", ")", ":", "if", "not", "hasattr", "(", "type_object", ",", "'dump'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: dump()\"", "%", "type_object",...
Mark a property as containing a map str to serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a dict of objects. This method requires that all members of the given dict be of a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this dict.
[ "Mark", "a", "property", "as", "containing", "a", "map", "str", "to", "serializable", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L113-L148
23,286
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.mark_typed_object
def mark_typed_object(self, name, type_object): """Mark a property as containing a serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a complex object. This method requires that property ``name`` be a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this property. """ if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_obj(obj): if obj is None: return None return obj.dump() def _restore_obj(obj): if obj is None: return obj return type_object.Restore(obj) self.mark_complex(name, _dump_obj, _restore_obj)
python
def mark_typed_object(self, name, type_object): if not hasattr(type_object, 'dump'): raise ArgumentError("The passed type object %s is missing required method: dump()" % type_object) if not hasattr(type_object, 'Restore'): raise ArgumentError("The passed type object %s is missing required method: Restore()" % type_object) def _dump_obj(obj): if obj is None: return None return obj.dump() def _restore_obj(obj): if obj is None: return obj return type_object.Restore(obj) self.mark_complex(name, _dump_obj, _restore_obj)
[ "def", "mark_typed_object", "(", "self", ",", "name", ",", "type_object", ")", ":", "if", "not", "hasattr", "(", "type_object", ",", "'dump'", ")", ":", "raise", "ArgumentError", "(", "\"The passed type object %s is missing required method: dump()\"", "%", "type_objec...
Mark a property as containing a serializable object. This convenience method allows you to avoid having to call ``mark_complex()`` whenever you need to serialize a complex object. This method requires that property ``name`` be a single class that contains a dump() method and a Restore() class method where type_object.Restore(x.dump()) == x. Args: name (str): The name of the complex property. type_object: The class object that will be contained inside this property.
[ "Mark", "a", "property", "as", "containing", "a", "serializable", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L150-L182
23,287
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.dump_property
def dump_property(self, name): """Serialize a property of this class by name. Args: name (str): The name of the property to dump. Returns: object: The serialized value of the property. """ if not hasattr(self, name): raise ArgumentError("Unknown property %s" % name) value = getattr(self, name) if name in self._complex_properties: value = self._complex_properties[name][0](value) return value
python
def dump_property(self, name): if not hasattr(self, name): raise ArgumentError("Unknown property %s" % name) value = getattr(self, name) if name in self._complex_properties: value = self._complex_properties[name][0](value) return value
[ "def", "dump_property", "(", "self", ",", "name", ")", ":", "if", "not", "hasattr", "(", "self", ",", "name", ")", ":", "raise", "ArgumentError", "(", "\"Unknown property %s\"", "%", "name", ")", "value", "=", "getattr", "(", "self", ",", "name", ")", ...
Serialize a property of this class by name. Args: name (str): The name of the property to dump. Returns: object: The serialized value of the property.
[ "Serialize", "a", "property", "of", "this", "class", "by", "name", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L184-L201
23,288
iotile/coretools
iotileemulate/iotile/emulate/virtual/simple_state.py
SerializableState.get_properties
def get_properties(self): """Get a list of all of the public data properties of this class. Returns: list of str: A list of all of the public properties in this class. """ names = inspect.getmembers(self, predicate=lambda x: not inspect.ismethod(x)) return [x[0] for x in names if not x[0].startswith("_") and x[0] not in self._ignored_properties]
python
def get_properties(self): names = inspect.getmembers(self, predicate=lambda x: not inspect.ismethod(x)) return [x[0] for x in names if not x[0].startswith("_") and x[0] not in self._ignored_properties]
[ "def", "get_properties", "(", "self", ")", ":", "names", "=", "inspect", ".", "getmembers", "(", "self", ",", "predicate", "=", "lambda", "x", ":", "not", "inspect", ".", "ismethod", "(", "x", ")", ")", "return", "[", "x", "[", "0", "]", "for", "x"...
Get a list of all of the public data properties of this class. Returns: list of str: A list of all of the public properties in this class.
[ "Get", "a", "list", "of", "all", "of", "the", "public", "data", "properties", "of", "this", "class", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/simple_state.py#L203-L211
23,289
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py
get_default_version
def get_default_version(env): """Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version. """ if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): # get all versions, and remember them for speed later versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: debug('get_default_version: WARNING: no installed versions found, ' 'using first in SupportedVSList (%s)'%SupportedVSList[0].version) env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION']
python
def get_default_version(env): if 'MSVS' not in env or not SCons.Util.is_Dict(env['MSVS']): # get all versions, and remember them for speed later versions = [vs.version for vs in get_installed_visual_studios()] env['MSVS'] = {'VERSIONS' : versions} else: versions = env['MSVS'].get('VERSIONS', []) if 'MSVS_VERSION' not in env: if versions: env['MSVS_VERSION'] = versions[0] #use highest version by default else: debug('get_default_version: WARNING: no installed versions found, ' 'using first in SupportedVSList (%s)'%SupportedVSList[0].version) env['MSVS_VERSION'] = SupportedVSList[0].version env['MSVS']['VERSION'] = env['MSVS_VERSION'] return env['MSVS_VERSION']
[ "def", "get_default_version", "(", "env", ")", ":", "if", "'MSVS'", "not", "in", "env", "or", "not", "SCons", ".", "Util", ".", "is_Dict", "(", "env", "[", "'MSVS'", "]", ")", ":", "# get all versions, and remember them for speed later", "versions", "=", "[", ...
Returns the default version string to use for MSVS. If no version was requested by the user through the MSVS environment variable, query all the available visual studios through get_installed_visual_studios, and take the highest one. Return ------ version: str the default version.
[ "Returns", "the", "default", "version", "string", "to", "use", "for", "MSVS", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py#L477-L506
23,290
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py
get_default_arch
def get_default_arch(env): """Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str """ arch = env.get('MSVS_ARCH', 'x86') msvs = InstalledVSMap.get(env['MSVS_VERSION']) if not msvs: arch = 'x86' elif not arch in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch
python
def get_default_arch(env): arch = env.get('MSVS_ARCH', 'x86') msvs = InstalledVSMap.get(env['MSVS_VERSION']) if not msvs: arch = 'x86' elif not arch in msvs.get_supported_arch(): fmt = "Visual Studio version %s does not support architecture %s" raise SCons.Errors.UserError(fmt % (env['MSVS_VERSION'], arch)) return arch
[ "def", "get_default_arch", "(", "env", ")", ":", "arch", "=", "env", ".", "get", "(", "'MSVS_ARCH'", ",", "'x86'", ")", "msvs", "=", "InstalledVSMap", ".", "get", "(", "env", "[", "'MSVS_VERSION'", "]", ")", "if", "not", "msvs", ":", "arch", "=", "'x...
Return the default arch to use for MSVS if no version was requested by the user through the MSVS_ARCH environment variable, select x86 Return ------ arch: str
[ "Return", "the", "default", "arch", "to", "use", "for", "MSVS" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vs.py#L508-L528
23,291
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/structures.py
ControlStructure.format_rpc
def format_rpc(self, address, rpc_id, payload): """Create a formated word list that encodes this rpc.""" addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24)) send_length = len(payload) if len(payload) < 20: payload = payload + b'\0'*(20 - len(payload)) payload_words = struct.unpack("<5L", payload) return self.base_address + self.RPC_TLS_OFFSET + 8, ([addr_word, send_length, 0] + [x for x in payload_words])
python
def format_rpc(self, address, rpc_id, payload): addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24)) send_length = len(payload) if len(payload) < 20: payload = payload + b'\0'*(20 - len(payload)) payload_words = struct.unpack("<5L", payload) return self.base_address + self.RPC_TLS_OFFSET + 8, ([addr_word, send_length, 0] + [x for x in payload_words])
[ "def", "format_rpc", "(", "self", ",", "address", ",", "rpc_id", ",", "payload", ")", ":", "addr_word", "=", "(", "rpc_id", "|", "(", "address", "<<", "16", ")", "|", "(", "(", "1", "<<", "1", ")", "<<", "24", ")", ")", "send_length", "=", "len",...
Create a formated word list that encodes this rpc.
[ "Create", "a", "formated", "word", "list", "that", "encodes", "this", "rpc", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/structures.py#L62-L73
23,292
iotile/coretools
transport_plugins/jlink/iotile_transport_jlink/structures.py
ControlStructure.format_response
def format_response(self, response_data): """Format an RPC response.""" _addr, length = self.response_info() if len(response_data) != length: raise HardwareError("Invalid response read length, should be the same as what response_info() returns", expected=length, actual=len(response_data)) resp, flags, received_length, payload = struct.unpack("<HxBL4x20s", response_data) resp = resp & 0xFF if flags & (1 << 3): raise HardwareError("Could not grab external gate") if received_length > 20: raise HardwareError("Invalid received payload length > 20 bytes", received_length=received_length) payload = payload[:received_length] return { 'status': resp, 'payload': payload }
python
def format_response(self, response_data): _addr, length = self.response_info() if len(response_data) != length: raise HardwareError("Invalid response read length, should be the same as what response_info() returns", expected=length, actual=len(response_data)) resp, flags, received_length, payload = struct.unpack("<HxBL4x20s", response_data) resp = resp & 0xFF if flags & (1 << 3): raise HardwareError("Could not grab external gate") if received_length > 20: raise HardwareError("Invalid received payload length > 20 bytes", received_length=received_length) payload = payload[:received_length] return { 'status': resp, 'payload': payload }
[ "def", "format_response", "(", "self", ",", "response_data", ")", ":", "_addr", ",", "length", "=", "self", ".", "response_info", "(", ")", "if", "len", "(", "response_data", ")", "!=", "length", ":", "raise", "HardwareError", "(", "\"Invalid response read len...
Format an RPC response.
[ "Format", "an", "RPC", "response", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/structures.py#L75-L95
23,293
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py
ProgramScanner
def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps
python
def ProgramScanner(**kw): kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps
[ "def", "ProgramScanner", "(", "*", "*", "kw", ")", ":", "kw", "[", "'path_function'", "]", "=", "SCons", ".", "Scanner", ".", "FindPathDirs", "(", "'LIBPATH'", ")", "ps", "=", "SCons", ".", "Scanner", ".", "Base", "(", "scan", ",", "\"ProgramScanner\"", ...
Return a prototype Scanner instance for scanning executable files for static-lib dependencies
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "executable", "files", "for", "static", "-", "lib", "dependencies" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py#L34-L39
23,294
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py
_subst_libs
def _subst_libs(env, libs): """ Substitute environment variables and split into list. """ if SCons.Util.is_String(libs): libs = env.subst(libs) if SCons.Util.is_String(libs): libs = libs.split() elif SCons.Util.is_Sequence(libs): _libs = [] for l in libs: _libs += _subst_libs(env, l) libs = _libs else: # libs is an object (Node, for example) libs = [libs] return libs
python
def _subst_libs(env, libs): if SCons.Util.is_String(libs): libs = env.subst(libs) if SCons.Util.is_String(libs): libs = libs.split() elif SCons.Util.is_Sequence(libs): _libs = [] for l in libs: _libs += _subst_libs(env, l) libs = _libs else: # libs is an object (Node, for example) libs = [libs] return libs
[ "def", "_subst_libs", "(", "env", ",", "libs", ")", ":", "if", "SCons", ".", "Util", ".", "is_String", "(", "libs", ")", ":", "libs", "=", "env", ".", "subst", "(", "libs", ")", "if", "SCons", ".", "Util", ".", "is_String", "(", "libs", ")", ":",...
Substitute environment variables and split into list.
[ "Substitute", "environment", "variables", "and", "split", "into", "list", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py#L41-L57
23,295
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py
scan
def scan(node, env, libpath = ()): """ This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies. """ try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] libs = _subst_libs(env, libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result
python
def scan(node, env, libpath = ()): try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] libs = _subst_libs(env, libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result
[ "def", "scan", "(", "node", ",", "env", ",", "libpath", "=", "(", ")", ")", ":", "try", ":", "libs", "=", "env", "[", "'LIBS'", "]", "except", "KeyError", ":", "# There are no LIBS in this environment, so just return a null list:", "return", "[", "]", "libs", ...
This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies.
[ "This", "scanner", "scans", "program", "files", "for", "static", "-", "library", "dependencies", ".", "It", "will", "search", "the", "LIBPATH", "environment", "variable", "for", "libraries", "specified", "in", "the", "LIBS", "variable", "returning", "any", "file...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Prog.py#L59-L110
23,296
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeState.clear_to_reset
def clear_to_reset(self, config_vars): """Clear the RemoteBridge subsystem to its reset state.""" super(RemoteBridgeState, self).clear_to_reset(config_vars) self.status = BRIDGE_STATUS.IDLE self.error = 0
python
def clear_to_reset(self, config_vars): super(RemoteBridgeState, self).clear_to_reset(config_vars) self.status = BRIDGE_STATUS.IDLE self.error = 0
[ "def", "clear_to_reset", "(", "self", ",", "config_vars", ")", ":", "super", "(", "RemoteBridgeState", ",", "self", ")", ".", "clear_to_reset", "(", "config_vars", ")", "self", ".", "status", "=", "BRIDGE_STATUS", ".", "IDLE", "self", ".", "error", "=", "0...
Clear the RemoteBridge subsystem to its reset state.
[ "Clear", "the", "RemoteBridge", "subsystem", "to", "its", "reset", "state", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L42-L47
23,297
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.begin_script
def begin_script(self): """Indicate we are going to start loading a script.""" if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING): return [1] #FIXME: Return correct error here self.remote_bridge.status = BRIDGE_STATUS.WAITING self.remote_bridge.error = 0 self.remote_bridge.script_error = None self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
python
def begin_script(self): if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING): return [1] #FIXME: Return correct error here self.remote_bridge.status = BRIDGE_STATUS.WAITING self.remote_bridge.error = 0 self.remote_bridge.script_error = None self.remote_bridge.parsed_script = None self._device.script = bytearray() return [0]
[ "def", "begin_script", "(", "self", ")", ":", "if", "self", ".", "remote_bridge", ".", "status", "in", "(", "BRIDGE_STATUS", ".", "RECEIVED", ",", "BRIDGE_STATUS", ".", "VALIDATED", ",", "BRIDGE_STATUS", ".", "EXECUTING", ")", ":", "return", "[", "1", "]",...
Indicate we are going to start loading a script.
[ "Indicate", "we", "are", "going", "to", "start", "loading", "a", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L77-L90
23,298
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.end_script
def end_script(self): """Indicate that we have finished receiving a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] #FIXME: State change self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
python
def end_script(self): if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] #FIXME: State change self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
[ "def", "end_script", "(", "self", ")", ":", "if", "self", ".", "remote_bridge", ".", "status", "not", "in", "(", "BRIDGE_STATUS", ".", "RECEIVED", ",", "BRIDGE_STATUS", ".", "WAITING", ")", ":", "return", "[", "1", "]", "#FIXME: State change", "self", ".",...
Indicate that we have finished receiving a script.
[ "Indicate", "that", "we", "have", "finished", "receiving", "a", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L93-L100
23,299
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py
RemoteBridgeMixin.trigger_script
def trigger_script(self): """Actually process a script.""" if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,): return [1] #FIXME: State change # This is asynchronous in real life so just cache the error try: self.remote_bridge.parsed_script = UpdateScript.FromBinary(self._device.script) #FIXME: Actually run the script self.remote_bridge.status = BRIDGE_STATUS.IDLE except Exception as exc: self._logger.exception("Error parsing script streamed to device") self.remote_bridge.script_error = exc self.remote_bridge.error = 1 # FIXME: Error code return [0]
python
def trigger_script(self): if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,): return [1] #FIXME: State change # This is asynchronous in real life so just cache the error try: self.remote_bridge.parsed_script = UpdateScript.FromBinary(self._device.script) #FIXME: Actually run the script self.remote_bridge.status = BRIDGE_STATUS.IDLE except Exception as exc: self._logger.exception("Error parsing script streamed to device") self.remote_bridge.script_error = exc self.remote_bridge.error = 1 # FIXME: Error code return [0]
[ "def", "trigger_script", "(", "self", ")", ":", "if", "self", ".", "remote_bridge", ".", "status", "not", "in", "(", "BRIDGE_STATUS", ".", "RECEIVED", ",", ")", ":", "return", "[", "1", "]", "#FIXME: State change", "# This is asynchronous in real life so just cach...
Actually process a script.
[ "Actually", "process", "a", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L103-L120