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,500 | iotile/coretools | iotilesensorgraph/iotile/sg/slot.py | SlotIdentifier.FromEncoded | def FromEncoded(cls, bindata):
"""Create a slot identifier from an encoded binary descriptor.
These binary descriptors are used to communicate slot targeting
to an embedded device. They are exactly 8 bytes in length.
Args:
bindata (bytes): The 8-byte binary descriptor.
Returns:
SlotIdentifier
"""
if len(bindata) != 8:
raise ArgumentError("Invalid binary slot descriptor with invalid length", length=len(bindata), expected=8, data=bindata)
slot, match_op = struct.unpack("<B6xB", bindata)
match_name = cls.KNOWN_MATCH_CODES.get(match_op)
if match_name is None:
raise ArgumentError("Unknown match operation specified in binary slot descriptor", operation=match_op, known_match_ops=cls.KNOWN_MATCH_CODES)
if match_name == 'match_controller':
return SlotIdentifier(controller=True)
if match_name == 'match_slot':
return SlotIdentifier(slot=slot)
raise ArgumentError("Unsupported match operation in binary slot descriptor", match_op=match_name) | python | def FromEncoded(cls, bindata):
if len(bindata) != 8:
raise ArgumentError("Invalid binary slot descriptor with invalid length", length=len(bindata), expected=8, data=bindata)
slot, match_op = struct.unpack("<B6xB", bindata)
match_name = cls.KNOWN_MATCH_CODES.get(match_op)
if match_name is None:
raise ArgumentError("Unknown match operation specified in binary slot descriptor", operation=match_op, known_match_ops=cls.KNOWN_MATCH_CODES)
if match_name == 'match_controller':
return SlotIdentifier(controller=True)
if match_name == 'match_slot':
return SlotIdentifier(slot=slot)
raise ArgumentError("Unsupported match operation in binary slot descriptor", match_op=match_name) | [
"def",
"FromEncoded",
"(",
"cls",
",",
"bindata",
")",
":",
"if",
"len",
"(",
"bindata",
")",
"!=",
"8",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid binary slot descriptor with invalid length\"",
",",
"length",
"=",
"len",
"(",
"bindata",
")",
",",
"expecte... | Create a slot identifier from an encoded binary descriptor.
These binary descriptors are used to communicate slot targeting
to an embedded device. They are exactly 8 bytes in length.
Args:
bindata (bytes): The 8-byte binary descriptor.
Returns:
SlotIdentifier | [
"Create",
"a",
"slot",
"identifier",
"from",
"an",
"encoded",
"binary",
"descriptor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/slot.py#L112-L140 |
23,501 | iotile/coretools | iotilesensorgraph/iotile/sg/slot.py | SlotIdentifier.encode | def encode(self):
"""Encode this slot identifier into a binary descriptor.
Returns:
bytes: The 8-byte encoded slot identifier
"""
slot = 0
match_op = self.KNOWN_MATCH_NAMES['match_controller']
if not self.controller:
slot = self.slot
match_op = self.KNOWN_MATCH_NAMES['match_slot']
return struct.pack("<B6xB", slot, match_op) | python | def encode(self):
slot = 0
match_op = self.KNOWN_MATCH_NAMES['match_controller']
if not self.controller:
slot = self.slot
match_op = self.KNOWN_MATCH_NAMES['match_slot']
return struct.pack("<B6xB", slot, match_op) | [
"def",
"encode",
"(",
"self",
")",
":",
"slot",
"=",
"0",
"match_op",
"=",
"self",
".",
"KNOWN_MATCH_NAMES",
"[",
"'match_controller'",
"]",
"if",
"not",
"self",
".",
"controller",
":",
"slot",
"=",
"self",
".",
"slot",
"match_op",
"=",
"self",
".",
"K... | Encode this slot identifier into a binary descriptor.
Returns:
bytes: The 8-byte encoded slot identifier | [
"Encode",
"this",
"slot",
"identifier",
"into",
"a",
"binary",
"descriptor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/slot.py#L142-L156 |
23,502 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py | _scons_syntax_error | def _scons_syntax_error(e):
"""Handle syntax errors. Print out a message and show where the error
occurred.
"""
etype, value, tb = sys.exc_info()
lines = traceback.format_exception_only(etype, value)
for line in lines:
sys.stderr.write(line+'\n')
sys.exit(2) | python | def _scons_syntax_error(e):
etype, value, tb = sys.exc_info()
lines = traceback.format_exception_only(etype, value)
for line in lines:
sys.stderr.write(line+'\n')
sys.exit(2) | [
"def",
"_scons_syntax_error",
"(",
"e",
")",
":",
"etype",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"lines",
"=",
"traceback",
".",
"format_exception_only",
"(",
"etype",
",",
"value",
")",
"for",
"line",
"in",
"lines",
":",
"sys... | Handle syntax errors. Print out a message and show where the error
occurred. | [
"Handle",
"syntax",
"errors",
".",
"Print",
"out",
"a",
"message",
"and",
"show",
"where",
"the",
"error",
"occurred",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py#L548-L556 |
23,503 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py | find_deepest_user_frame | def find_deepest_user_frame(tb):
"""
Find the deepest stack frame that is not part of SCons.
Input is a "pre-processed" stack trace in the form
returned by traceback.extract_tb() or traceback.extract_stack()
"""
tb.reverse()
# find the deepest traceback frame that is not part
# of SCons:
for frame in tb:
filename = frame[0]
if filename.find(os.sep+'SCons'+os.sep) == -1:
return frame
return tb[0] | python | def find_deepest_user_frame(tb):
tb.reverse()
# find the deepest traceback frame that is not part
# of SCons:
for frame in tb:
filename = frame[0]
if filename.find(os.sep+'SCons'+os.sep) == -1:
return frame
return tb[0] | [
"def",
"find_deepest_user_frame",
"(",
"tb",
")",
":",
"tb",
".",
"reverse",
"(",
")",
"# find the deepest traceback frame that is not part",
"# of SCons:",
"for",
"frame",
"in",
"tb",
":",
"filename",
"=",
"frame",
"[",
"0",
"]",
"if",
"filename",
".",
"find",
... | Find the deepest stack frame that is not part of SCons.
Input is a "pre-processed" stack trace in the form
returned by traceback.extract_tb() or traceback.extract_stack() | [
"Find",
"the",
"deepest",
"stack",
"frame",
"that",
"is",
"not",
"part",
"of",
"SCons",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py#L558-L574 |
23,504 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py | _scons_user_error | def _scons_user_error(e):
"""Handle user errors. Print out a message and a description of the
error, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself.
"""
global print_stacktrace
etype, value, tb = sys.exc_info()
if print_stacktrace:
traceback.print_exception(etype, value, tb)
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stderr.write("\nscons: *** %s\n" % value)
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine))
sys.exit(2) | python | def _scons_user_error(e):
global print_stacktrace
etype, value, tb = sys.exc_info()
if print_stacktrace:
traceback.print_exception(etype, value, tb)
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stderr.write("\nscons: *** %s\n" % value)
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine))
sys.exit(2) | [
"def",
"_scons_user_error",
"(",
"e",
")",
":",
"global",
"print_stacktrace",
"etype",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"print_stacktrace",
":",
"traceback",
".",
"print_exception",
"(",
"etype",
",",
"value",
",",
"tb"... | Handle user errors. Print out a message and a description of the
error, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself. | [
"Handle",
"user",
"errors",
".",
"Print",
"out",
"a",
"message",
"and",
"a",
"description",
"of",
"the",
"error",
"along",
"with",
"the",
"line",
"number",
"and",
"routine",
"where",
"it",
"occured",
".",
"The",
"file",
"and",
"line",
"number",
"will",
"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py#L576-L589 |
23,505 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py | _scons_user_warning | def _scons_user_warning(e):
"""Handle user warnings. Print out a message and a description of
the warning, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself.
"""
etype, value, tb = sys.exc_info()
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stderr.write("\nscons: warning: %s\n" % e)
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine)) | python | def _scons_user_warning(e):
etype, value, tb = sys.exc_info()
filename, lineno, routine, dummy = find_deepest_user_frame(traceback.extract_tb(tb))
sys.stderr.write("\nscons: warning: %s\n" % e)
sys.stderr.write('File "%s", line %d, in %s\n' % (filename, lineno, routine)) | [
"def",
"_scons_user_warning",
"(",
"e",
")",
":",
"etype",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"filename",
",",
"lineno",
",",
"routine",
",",
"dummy",
"=",
"find_deepest_user_frame",
"(",
"traceback",
".",
"extract_tb",
"(",
... | Handle user warnings. Print out a message and a description of
the warning, along with the line number and routine where it occured.
The file and line number will be the deepest stack frame that is
not part of SCons itself. | [
"Handle",
"user",
"warnings",
".",
"Print",
"out",
"a",
"message",
"and",
"a",
"description",
"of",
"the",
"warning",
"along",
"with",
"the",
"line",
"number",
"and",
"routine",
"where",
"it",
"occured",
".",
"The",
"file",
"and",
"line",
"number",
"will",... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py#L591-L600 |
23,506 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py | _SConstruct_exists | def _SConstruct_exists(dirname='', repositories=[], filelist=None):
"""This function checks that an SConstruct file exists in a directory.
If so, it returns the path of the file. By default, it checks the
current directory.
"""
if not filelist:
filelist = ['SConstruct', 'Sconstruct', 'sconstruct']
for file in filelist:
sfile = os.path.join(dirname, file)
if os.path.isfile(sfile):
return sfile
if not os.path.isabs(sfile):
for rep in repositories:
if os.path.isfile(os.path.join(rep, sfile)):
return sfile
return None | python | def _SConstruct_exists(dirname='', repositories=[], filelist=None):
if not filelist:
filelist = ['SConstruct', 'Sconstruct', 'sconstruct']
for file in filelist:
sfile = os.path.join(dirname, file)
if os.path.isfile(sfile):
return sfile
if not os.path.isabs(sfile):
for rep in repositories:
if os.path.isfile(os.path.join(rep, sfile)):
return sfile
return None | [
"def",
"_SConstruct_exists",
"(",
"dirname",
"=",
"''",
",",
"repositories",
"=",
"[",
"]",
",",
"filelist",
"=",
"None",
")",
":",
"if",
"not",
"filelist",
":",
"filelist",
"=",
"[",
"'SConstruct'",
",",
"'Sconstruct'",
",",
"'sconstruct'",
"]",
"for",
... | This function checks that an SConstruct file exists in a directory.
If so, it returns the path of the file. By default, it checks the
current directory. | [
"This",
"function",
"checks",
"that",
"an",
"SConstruct",
"file",
"exists",
"in",
"a",
"directory",
".",
"If",
"so",
"it",
"returns",
"the",
"path",
"of",
"the",
"file",
".",
"By",
"default",
"it",
"checks",
"the",
"current",
"directory",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py#L618-L633 |
23,507 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py | BuildTask.make_ready | def make_ready(self):
"""Make a task ready for execution"""
SCons.Taskmaster.OutOfDateTask.make_ready(self)
if self.out_of_date and self.options.debug_explain:
explanation = self.out_of_date[0].explain()
if explanation:
sys.stdout.write("scons: " + explanation) | python | def make_ready(self):
SCons.Taskmaster.OutOfDateTask.make_ready(self)
if self.out_of_date and self.options.debug_explain:
explanation = self.out_of_date[0].explain()
if explanation:
sys.stdout.write("scons: " + explanation) | [
"def",
"make_ready",
"(",
"self",
")",
":",
"SCons",
".",
"Taskmaster",
".",
"OutOfDateTask",
".",
"make_ready",
"(",
"self",
")",
"if",
"self",
".",
"out_of_date",
"and",
"self",
".",
"options",
".",
"debug_explain",
":",
"explanation",
"=",
"self",
".",
... | Make a task ready for execution | [
"Make",
"a",
"task",
"ready",
"for",
"execution"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/Main.py#L306-L312 |
23,508 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | _unpack_version | def _unpack_version(tag_data):
"""Parse a packed version info struct into tag and major.minor version.
The tag and version are parsed out according to 20 bits for tag and
6 bits each for major and minor. The more interesting part is the
blacklisting performed for tags that are known to be untrustworthy.
In particular, the following applies to tags.
- tags < 1024 are reserved for development and have only locally defined
meaning. They are not for use in production.
- tags in [1024, 2048) are production tags but were used inconsistently
in the early days of Arch and hence cannot be trusted to correspond with
an actual device model.
- tags >= 2048 are reserved for supported production device variants.
- the tag and version 0 (0.0) is reserved for an unknown wildcard that
does not convey any information except that the tag and version are
not known.
"""
tag = tag_data & ((1 << 20) - 1)
version_data = tag_data >> 20
major = (version_data >> 6) & ((1 << 6) - 1)
minor = (version_data >> 0) & ((1 << 6) - 1)
return (tag, "{}.{}".format(major, minor)) | python | def _unpack_version(tag_data):
tag = tag_data & ((1 << 20) - 1)
version_data = tag_data >> 20
major = (version_data >> 6) & ((1 << 6) - 1)
minor = (version_data >> 0) & ((1 << 6) - 1)
return (tag, "{}.{}".format(major, minor)) | [
"def",
"_unpack_version",
"(",
"tag_data",
")",
":",
"tag",
"=",
"tag_data",
"&",
"(",
"(",
"1",
"<<",
"20",
")",
"-",
"1",
")",
"version_data",
"=",
"tag_data",
">>",
"20",
"major",
"=",
"(",
"version_data",
">>",
"6",
")",
"&",
"(",
"(",
"1",
"... | Parse a packed version info struct into tag and major.minor version.
The tag and version are parsed out according to 20 bits for tag and
6 bits each for major and minor. The more interesting part is the
blacklisting performed for tags that are known to be untrustworthy.
In particular, the following applies to tags.
- tags < 1024 are reserved for development and have only locally defined
meaning. They are not for use in production.
- tags in [1024, 2048) are production tags but were used inconsistently
in the early days of Arch and hence cannot be trusted to correspond with
an actual device model.
- tags >= 2048 are reserved for supported production device variants.
- the tag and version 0 (0.0) is reserved for an unknown wildcard that
does not convey any information except that the tag and version are
not known. | [
"Parse",
"a",
"packed",
"version",
"info",
"struct",
"into",
"tag",
"and",
"major",
".",
"minor",
"version",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L322-L348 |
23,509 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | ReferenceController._handle_reset | def _handle_reset(self):
"""Reset this controller tile.
This process will call _handle_reset() for all of the controller
subsystem mixins in order to make sure they all return to their proper
reset state.
It will then reset all of the peripheral tiles to emulate the behavior
of a physical POD where the controller tile cuts power to all
peripheral tiles on reset for a clean boot.
This will clear all subsystems of this controller to their reset
states.
The order of these calls is important to guarantee that everything is
in the correct state before resetting the next subsystem.
The behavior of this function is different depending on whether
deferred is True or False. If it's true, this function will only
clear the config database and then queue all of the config streaming
rpcs to itself to load in all of our config variables. Once these
have been sent, it will reset the rest of the controller subsystems.
"""
self._logger.info("Resetting controller")
self._device.reset_count += 1
super(ReferenceController, self)._handle_reset()
# Load in all default values into our config variables before streaming
# updated data into them.
self.reset_config_variables() | python | def _handle_reset(self):
self._logger.info("Resetting controller")
self._device.reset_count += 1
super(ReferenceController, self)._handle_reset()
# Load in all default values into our config variables before streaming
# updated data into them.
self.reset_config_variables() | [
"def",
"_handle_reset",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Resetting controller\"",
")",
"self",
".",
"_device",
".",
"reset_count",
"+=",
"1",
"super",
"(",
"ReferenceController",
",",
"self",
")",
".",
"_handle_reset",
"(",... | Reset this controller tile.
This process will call _handle_reset() for all of the controller
subsystem mixins in order to make sure they all return to their proper
reset state.
It will then reset all of the peripheral tiles to emulate the behavior
of a physical POD where the controller tile cuts power to all
peripheral tiles on reset for a clean boot.
This will clear all subsystems of this controller to their reset
states.
The order of these calls is important to guarantee that everything is
in the correct state before resetting the next subsystem.
The behavior of this function is different depending on whether
deferred is True or False. If it's true, this function will only
clear the config database and then queue all of the config streaming
rpcs to itself to load in all of our config variables. Once these
have been sent, it will reset the rest of the controller subsystems. | [
"Reset",
"this",
"controller",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L78-L109 |
23,510 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | ReferenceController._reset_vector | async def _reset_vector(self):
"""Initialize the controller's subsystems inside the emulation thread."""
# Send ourselves all of our config variable assignments
config_rpcs = self.config_database.stream_matching(8, self.name)
for rpc in config_rpcs:
await self._device.emulator.await_rpc(*rpc)
config_assignments = self.latch_config_variables()
self._logger.info("Latched config variables at reset for controller: %s", config_assignments)
for system in self._post_config_subsystems:
try:
system.clear_to_reset(config_assignments)
await asyncio.wait_for(system.initialize(), timeout=2.0)
except:
self._logger.exception("Error initializing %s", system)
raise
self._logger.info("Finished clearing controller to reset condition")
# Now reset all of the tiles
for address, _ in self._device.iter_tiles(include_controller=False):
self._logger.info("Sending reset signal to tile at address %d", address)
try:
await self._device.emulator.await_rpc(address, rpcs.RESET)
except TileNotFoundError:
pass
except:
self._logger.exception("Error sending reset signal to tile at address %d", address)
raise
self.initialized.set() | python | async def _reset_vector(self):
# Send ourselves all of our config variable assignments
config_rpcs = self.config_database.stream_matching(8, self.name)
for rpc in config_rpcs:
await self._device.emulator.await_rpc(*rpc)
config_assignments = self.latch_config_variables()
self._logger.info("Latched config variables at reset for controller: %s", config_assignments)
for system in self._post_config_subsystems:
try:
system.clear_to_reset(config_assignments)
await asyncio.wait_for(system.initialize(), timeout=2.0)
except:
self._logger.exception("Error initializing %s", system)
raise
self._logger.info("Finished clearing controller to reset condition")
# Now reset all of the tiles
for address, _ in self._device.iter_tiles(include_controller=False):
self._logger.info("Sending reset signal to tile at address %d", address)
try:
await self._device.emulator.await_rpc(address, rpcs.RESET)
except TileNotFoundError:
pass
except:
self._logger.exception("Error sending reset signal to tile at address %d", address)
raise
self.initialized.set() | [
"async",
"def",
"_reset_vector",
"(",
"self",
")",
":",
"# Send ourselves all of our config variable assignments",
"config_rpcs",
"=",
"self",
".",
"config_database",
".",
"stream_matching",
"(",
"8",
",",
"self",
".",
"name",
")",
"for",
"rpc",
"in",
"config_rpcs",... | Initialize the controller's subsystems inside the emulation thread. | [
"Initialize",
"the",
"controller",
"s",
"subsystems",
"inside",
"the",
"emulation",
"thread",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L111-L144 |
23,511 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | ReferenceController.hardware_version | def hardware_version(self):
"""Get a hardware identification string."""
hardware_string = self.hardware_string
if not isinstance(hardware_string, bytes):
hardware_string = self.hardware_string.encode('utf-8')
if len(hardware_string) > 10:
self._logger.warn("Truncating hardware string that was longer than 10 bytes: %s", self.hardware_string)
if len(hardware_string) < 10:
hardware_string += b'\0'*(10 - len(hardware_string))
return [hardware_string] | python | def hardware_version(self):
hardware_string = self.hardware_string
if not isinstance(hardware_string, bytes):
hardware_string = self.hardware_string.encode('utf-8')
if len(hardware_string) > 10:
self._logger.warn("Truncating hardware string that was longer than 10 bytes: %s", self.hardware_string)
if len(hardware_string) < 10:
hardware_string += b'\0'*(10 - len(hardware_string))
return [hardware_string] | [
"def",
"hardware_version",
"(",
"self",
")",
":",
"hardware_string",
"=",
"self",
".",
"hardware_string",
"if",
"not",
"isinstance",
"(",
"hardware_string",
",",
"bytes",
")",
":",
"hardware_string",
"=",
"self",
".",
"hardware_string",
".",
"encode",
"(",
"'u... | Get a hardware identification string. | [
"Get",
"a",
"hardware",
"identification",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L199-L213 |
23,512 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | ReferenceController.controller_info | def controller_info(self):
"""Get the controller UUID, app tag and os tag."""
return [self._device.iotile_id, _pack_version(*self.os_info), _pack_version(*self.app_info)] | python | def controller_info(self):
return [self._device.iotile_id, _pack_version(*self.os_info), _pack_version(*self.app_info)] | [
"def",
"controller_info",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_device",
".",
"iotile_id",
",",
"_pack_version",
"(",
"*",
"self",
".",
"os_info",
")",
",",
"_pack_version",
"(",
"*",
"self",
".",
"app_info",
")",
"]"
] | Get the controller UUID, app tag and os tag. | [
"Get",
"the",
"controller",
"UUID",
"app",
"tag",
"and",
"os",
"tag",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L216-L219 |
23,513 | iotile/coretools | iotileemulate/iotile/emulate/reference/reference_controller.py | ReferenceController.load_sgf | def load_sgf(self, sgf_data):
"""Load, persist a sensor_graph file.
The data passed in `sgf_data` can either be a path or the already
loaded sgf lines as a string. It is determined to be sgf lines if
there is a '\n' character in the data, otherwise it is interpreted as
a path.
Note that this scenario just loads the sensor_graph directly into the
persisted sensor_graph inside the device. You will still need to
reset the device for the sensor_graph to enabled and run.
Args:
sgf_data (str): Either the path to an sgf file or its contents
as a string.
"""
if '\n' not in sgf_data:
with open(sgf_data, "r") as infile:
sgf_data = infile.read()
model = DeviceModel()
parser = SensorGraphFileParser()
parser.parse_file(data=sgf_data)
parser.compile(model)
opt = SensorGraphOptimizer()
opt.optimize(parser.sensor_graph, model=model)
sensor_graph = parser.sensor_graph
self._logger.info("Loading sensor_graph with %d nodes, %d streamers and %d configs",
len(sensor_graph.nodes), len(sensor_graph.streamers), len(sensor_graph.config_database))
# Directly load the sensor_graph into our persisted storage
self.sensor_graph.persisted_nodes = sensor_graph.dump_nodes()
self.sensor_graph.persisted_streamers = sensor_graph.dump_streamers()
self.sensor_graph.persisted_constants = []
for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()):
reading = IOTileReading(stream.encode(), 0, value)
self.sensor_graph.persisted_constants.append((stream, reading))
self.sensor_graph.persisted_exists = True
# Clear all config variables and load in those from this sgf file
self.config_database.clear()
for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):
for conf_var, (conf_type, conf_val) in sorted(sensor_graph.config_database[slot].items()):
self.config_database.add_direct(slot, conf_var, conf_type, conf_val)
# If we have an app tag and version set program them in
app_tag = sensor_graph.metadata_database.get('app_tag')
app_version = sensor_graph.metadata_database.get('app_version')
if app_tag is not None:
if app_version is None:
app_version = "0.0"
self.app_info = (app_tag, app_version) | python | def load_sgf(self, sgf_data):
if '\n' not in sgf_data:
with open(sgf_data, "r") as infile:
sgf_data = infile.read()
model = DeviceModel()
parser = SensorGraphFileParser()
parser.parse_file(data=sgf_data)
parser.compile(model)
opt = SensorGraphOptimizer()
opt.optimize(parser.sensor_graph, model=model)
sensor_graph = parser.sensor_graph
self._logger.info("Loading sensor_graph with %d nodes, %d streamers and %d configs",
len(sensor_graph.nodes), len(sensor_graph.streamers), len(sensor_graph.config_database))
# Directly load the sensor_graph into our persisted storage
self.sensor_graph.persisted_nodes = sensor_graph.dump_nodes()
self.sensor_graph.persisted_streamers = sensor_graph.dump_streamers()
self.sensor_graph.persisted_constants = []
for stream, value in sorted(sensor_graph.constant_database.items(), key=lambda x: x[0].encode()):
reading = IOTileReading(stream.encode(), 0, value)
self.sensor_graph.persisted_constants.append((stream, reading))
self.sensor_graph.persisted_exists = True
# Clear all config variables and load in those from this sgf file
self.config_database.clear()
for slot in sorted(sensor_graph.config_database, key=lambda x: x.encode()):
for conf_var, (conf_type, conf_val) in sorted(sensor_graph.config_database[slot].items()):
self.config_database.add_direct(slot, conf_var, conf_type, conf_val)
# If we have an app tag and version set program them in
app_tag = sensor_graph.metadata_database.get('app_tag')
app_version = sensor_graph.metadata_database.get('app_version')
if app_tag is not None:
if app_version is None:
app_version = "0.0"
self.app_info = (app_tag, app_version) | [
"def",
"load_sgf",
"(",
"self",
",",
"sgf_data",
")",
":",
"if",
"'\\n'",
"not",
"in",
"sgf_data",
":",
"with",
"open",
"(",
"sgf_data",
",",
"\"r\"",
")",
"as",
"infile",
":",
"sgf_data",
"=",
"infile",
".",
"read",
"(",
")",
"model",
"=",
"DeviceMo... | Load, persist a sensor_graph file.
The data passed in `sgf_data` can either be a path or the already
loaded sgf lines as a string. It is determined to be sgf lines if
there is a '\n' character in the data, otherwise it is interpreted as
a path.
Note that this scenario just loads the sensor_graph directly into the
persisted sensor_graph inside the device. You will still need to
reset the device for the sensor_graph to enabled and run.
Args:
sgf_data (str): Either the path to an sgf file or its contents
as a string. | [
"Load",
"persist",
"a",
"sensor_graph",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/reference_controller.py#L237-L297 |
23,514 | iotile/coretools | iotilebuild/iotile/build/config/site_scons/cfileparser.py | ParsedCFile._parse_file | def _parse_file(self):
"""Preprocess and parse C file into an AST"""
# We need to set the CPU type to pull in the right register definitions
# only preprocess the file (-E) and get rid of gcc extensions that aren't
# supported in ISO C.
args = utilities.build_includes(self.arch.includes())
# args.append('-mcpu=%s' % self.arch.property('chip'))
args.append('-E')
args.append('-D__attribute__(x)=')
args.append('-D__extension__=')
self.ast = parse_file(self.filepath, use_cpp=True, cpp_path='arm-none-eabi-gcc', cpp_args=args) | python | def _parse_file(self):
# We need to set the CPU type to pull in the right register definitions
# only preprocess the file (-E) and get rid of gcc extensions that aren't
# supported in ISO C.
args = utilities.build_includes(self.arch.includes())
# args.append('-mcpu=%s' % self.arch.property('chip'))
args.append('-E')
args.append('-D__attribute__(x)=')
args.append('-D__extension__=')
self.ast = parse_file(self.filepath, use_cpp=True, cpp_path='arm-none-eabi-gcc', cpp_args=args) | [
"def",
"_parse_file",
"(",
"self",
")",
":",
"# We need to set the CPU type to pull in the right register definitions",
"# only preprocess the file (-E) and get rid of gcc extensions that aren't",
"# supported in ISO C.",
"args",
"=",
"utilities",
".",
"build_includes",
"(",
"self",
... | Preprocess and parse C file into an AST | [
"Preprocess",
"and",
"parse",
"C",
"file",
"into",
"an",
"AST"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/cfileparser.py#L35-L47 |
23,515 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | _clear_queue | def _clear_queue(to_clear):
"""Clear all items from a queue safely."""
while not to_clear.empty():
try:
to_clear.get(False)
to_clear.task_done()
except queue.Empty:
continue | python | def _clear_queue(to_clear):
while not to_clear.empty():
try:
to_clear.get(False)
to_clear.task_done()
except queue.Empty:
continue | [
"def",
"_clear_queue",
"(",
"to_clear",
")",
":",
"while",
"not",
"to_clear",
".",
"empty",
"(",
")",
":",
"try",
":",
"to_clear",
".",
"get",
"(",
"False",
")",
"to_clear",
".",
"task_done",
"(",
")",
"except",
"queue",
".",
"Empty",
":",
"continue"
] | Clear all items from a queue safely. | [
"Clear",
"all",
"items",
"from",
"a",
"queue",
"safely",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L562-L570 |
23,516 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | _RecordedRPC.finish | def finish(self, status, response):
"""Mark the end of a recorded RPC."""
self.response = binascii.hexlify(response).decode('utf-8')
self.status = status
self.runtime = monotonic() - self._start_time | python | def finish(self, status, response):
self.response = binascii.hexlify(response).decode('utf-8')
self.status = status
self.runtime = monotonic() - self._start_time | [
"def",
"finish",
"(",
"self",
",",
"status",
",",
"response",
")",
":",
"self",
".",
"response",
"=",
"binascii",
".",
"hexlify",
"(",
"response",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"status",
"=",
"status",
"self",
".",
"runtime",
... | Mark the end of a recorded RPC. | [
"Mark",
"the",
"end",
"of",
"a",
"recorded",
"RPC",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L43-L48 |
23,517 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | _RecordedRPC.serialize | def serialize(self):
"""Convert this recorded RPC into a string."""
return "{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}".\
format(self.connection, self.start_stamp.isoformat(), self.address, self.rpc_id,
self.status, self.runtime * 1000, self.call, self.response, self.error) | python | def serialize(self):
return "{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}".\
format(self.connection, self.start_stamp.isoformat(), self.address, self.rpc_id,
self.status, self.runtime * 1000, self.call, self.response, self.error) | [
"def",
"serialize",
"(",
"self",
")",
":",
"return",
"\"{},{: <26},{:2d},{:#06x},{:#04x},{:5.0f},{: <40},{: <40},{}\"",
".",
"format",
"(",
"self",
".",
"connection",
",",
"self",
".",
"start_stamp",
".",
"isoformat",
"(",
")",
",",
"self",
".",
"address",
",",
... | Convert this recorded RPC into a string. | [
"Convert",
"this",
"recorded",
"RPC",
"into",
"a",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L50-L55 |
23,518 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.scan | def scan(self, wait=None):
"""Return the devices that have been found for this device adapter.
If the adapter indicates that we need to explicitly tell it to probe for devices, probe now.
By default we return the list of seen devices immediately, however there are two cases where
we will sleep here for a fixed period of time to let devices show up in our result list:
- If we are probing then we wait for 'minimum_scan_time'
- If we are told an explicit wait time that overrides everything and we wait that long
"""
min_scan = self.adapter.get_config('minimum_scan_time', 0.0)
probe_required = self.adapter.get_config('probe_required', False)
# Figure out how long and if we need to wait before returning our scan results
wait_time = None
elapsed = monotonic() - self._start_time
if elapsed < min_scan:
wait_time = min_scan - elapsed
# If we need to probe for devices rather than letting them just bubble up, start the probe
# and then use our min_scan_time to wait for them to arrive via the normal _on_scan event
if probe_required:
self._loop.run_coroutine(self.adapter.probe())
wait_time = min_scan
# If an explicit wait is specified that overrides everything else
if wait is not None:
wait_time = wait
if wait_time is not None:
sleep(wait_time)
to_remove = set()
now = monotonic()
with self._scan_lock:
for name, value in self._scanned_devices.items():
if value['expiration_time'] < now:
to_remove.add(name)
for name in to_remove:
del self._scanned_devices[name]
devices = sorted(self._scanned_devices.values(), key=lambda x: x['uuid'])
return devices | python | def scan(self, wait=None):
min_scan = self.adapter.get_config('minimum_scan_time', 0.0)
probe_required = self.adapter.get_config('probe_required', False)
# Figure out how long and if we need to wait before returning our scan results
wait_time = None
elapsed = monotonic() - self._start_time
if elapsed < min_scan:
wait_time = min_scan - elapsed
# If we need to probe for devices rather than letting them just bubble up, start the probe
# and then use our min_scan_time to wait for them to arrive via the normal _on_scan event
if probe_required:
self._loop.run_coroutine(self.adapter.probe())
wait_time = min_scan
# If an explicit wait is specified that overrides everything else
if wait is not None:
wait_time = wait
if wait_time is not None:
sleep(wait_time)
to_remove = set()
now = monotonic()
with self._scan_lock:
for name, value in self._scanned_devices.items():
if value['expiration_time'] < now:
to_remove.add(name)
for name in to_remove:
del self._scanned_devices[name]
devices = sorted(self._scanned_devices.values(), key=lambda x: x['uuid'])
return devices | [
"def",
"scan",
"(",
"self",
",",
"wait",
"=",
"None",
")",
":",
"min_scan",
"=",
"self",
".",
"adapter",
".",
"get_config",
"(",
"'minimum_scan_time'",
",",
"0.0",
")",
"probe_required",
"=",
"self",
".",
"adapter",
".",
"get_config",
"(",
"'probe_required... | Return the devices that have been found for this device adapter.
If the adapter indicates that we need to explicitly tell it to probe for devices, probe now.
By default we return the list of seen devices immediately, however there are two cases where
we will sleep here for a fixed period of time to let devices show up in our result list:
- If we are probing then we wait for 'minimum_scan_time'
- If we are told an explicit wait time that overrides everything and we wait that long | [
"Return",
"the",
"devices",
"that",
"have",
"been",
"found",
"for",
"this",
"device",
"adapter",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L113-L160 |
23,519 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.connect | def connect(self, uuid_value, wait=None):
"""Connect to a specific device by its uuid
Attempt to connect to a device that we have previously scanned using its UUID.
If wait is not None, then it is used in the same was a scan(wait) to override
default wait times with an explicit value.
Args:
uuid_value (int): The unique id of the device that we would like to connect to.
wait (float): Optional amount of time to force the device adapter to wait before
attempting to connect.
"""
if self.connected:
raise HardwareError("Cannot connect when we are already connected")
if uuid_value not in self._scanned_devices:
self.scan(wait=wait)
with self._scan_lock:
if uuid_value not in self._scanned_devices:
raise HardwareError("Could not find device to connect to by UUID", uuid=uuid_value)
connstring = self._scanned_devices[uuid_value]['connection_string']
self.connect_direct(connstring) | python | def connect(self, uuid_value, wait=None):
if self.connected:
raise HardwareError("Cannot connect when we are already connected")
if uuid_value not in self._scanned_devices:
self.scan(wait=wait)
with self._scan_lock:
if uuid_value not in self._scanned_devices:
raise HardwareError("Could not find device to connect to by UUID", uuid=uuid_value)
connstring = self._scanned_devices[uuid_value]['connection_string']
self.connect_direct(connstring) | [
"def",
"connect",
"(",
"self",
",",
"uuid_value",
",",
"wait",
"=",
"None",
")",
":",
"if",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot connect when we are already connected\"",
")",
"if",
"uuid_value",
"not",
"in",
"self",
".",
"_s... | Connect to a specific device by its uuid
Attempt to connect to a device that we have previously scanned using its UUID.
If wait is not None, then it is used in the same was a scan(wait) to override
default wait times with an explicit value.
Args:
uuid_value (int): The unique id of the device that we would like to connect to.
wait (float): Optional amount of time to force the device adapter to wait before
attempting to connect. | [
"Connect",
"to",
"a",
"specific",
"device",
"by",
"its",
"uuid"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L162-L187 |
23,520 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.connect_direct | def connect_direct(self, connection_string, no_rpc=False, force=False):
"""Directly connect to a device using its stream specific connection string.
Normally, all connections to a device include opening the RPC
interface to send RPCs. However, there are certain, very specific,
circumstances when you would not want to or be able to open the RPC
interface (such as when you are using the debug interface on a bare
MCU that has not been programmed yet). In those cases you can pass
no_rpc=True to not attempt to open the RPC interface. If you do not
open the RPC interface at connection time, there is no public
interface to open it later, so you must disconnect and reconnect to
the device in order to open the interface.
Args:
connection_string (str): The connection string that identifies the desired device.
no_rpc (bool): Do not open the RPC interface on the device (default=False).
force (bool): Whether to force another connection even if we think we are currently
connected. This is for internal use and not designed to be set externally.
"""
if not force and self.connected:
raise HardwareError("Cannot connect when we are already connected to '%s'" % self.connection_string)
self._loop.run_coroutine(self.adapter.connect(0, connection_string))
try:
if no_rpc:
self._logger.info("Not opening RPC interface on device %s", self.connection_string)
else:
self._loop.run_coroutine(self.adapter.open_interface(0, 'rpc'))
except HardwareError as exc:
self._logger.exception("Error opening RPC interface on device %s", connection_string)
self._loop.run_coroutine(self.adapter.disconnect(0))
raise exc
except Exception as exc:
self._logger.exception("Error opening RPC interface on device %s", connection_string)
self._loop.run_coroutine(self.adapter.disconnect(0))
raise HardwareError("Could not open RPC interface on device due to an exception: %s" % str(exc)) from exc
self.connected = True
self.connection_string = connection_string
self.connection_interrupted = False | python | def connect_direct(self, connection_string, no_rpc=False, force=False):
if not force and self.connected:
raise HardwareError("Cannot connect when we are already connected to '%s'" % self.connection_string)
self._loop.run_coroutine(self.adapter.connect(0, connection_string))
try:
if no_rpc:
self._logger.info("Not opening RPC interface on device %s", self.connection_string)
else:
self._loop.run_coroutine(self.adapter.open_interface(0, 'rpc'))
except HardwareError as exc:
self._logger.exception("Error opening RPC interface on device %s", connection_string)
self._loop.run_coroutine(self.adapter.disconnect(0))
raise exc
except Exception as exc:
self._logger.exception("Error opening RPC interface on device %s", connection_string)
self._loop.run_coroutine(self.adapter.disconnect(0))
raise HardwareError("Could not open RPC interface on device due to an exception: %s" % str(exc)) from exc
self.connected = True
self.connection_string = connection_string
self.connection_interrupted = False | [
"def",
"connect_direct",
"(",
"self",
",",
"connection_string",
",",
"no_rpc",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
"and",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot connect when we are already co... | Directly connect to a device using its stream specific connection string.
Normally, all connections to a device include opening the RPC
interface to send RPCs. However, there are certain, very specific,
circumstances when you would not want to or be able to open the RPC
interface (such as when you are using the debug interface on a bare
MCU that has not been programmed yet). In those cases you can pass
no_rpc=True to not attempt to open the RPC interface. If you do not
open the RPC interface at connection time, there is no public
interface to open it later, so you must disconnect and reconnect to
the device in order to open the interface.
Args:
connection_string (str): The connection string that identifies the desired device.
no_rpc (bool): Do not open the RPC interface on the device (default=False).
force (bool): Whether to force another connection even if we think we are currently
connected. This is for internal use and not designed to be set externally. | [
"Directly",
"connect",
"to",
"a",
"device",
"using",
"its",
"stream",
"specific",
"connection",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L189-L230 |
23,521 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.disconnect | def disconnect(self):
"""Disconnect from the device that we are currently connected to."""
if not self.connected:
raise HardwareError("Cannot disconnect when we are not connected")
# Close the streaming and tracing interfaces when we disconnect
self._reports = None
self._traces = None
self._loop.run_coroutine(self.adapter.disconnect(0))
self.connected = False
self.connection_interrupted = False
self.connection_string = None | python | def disconnect(self):
if not self.connected:
raise HardwareError("Cannot disconnect when we are not connected")
# Close the streaming and tracing interfaces when we disconnect
self._reports = None
self._traces = None
self._loop.run_coroutine(self.adapter.disconnect(0))
self.connected = False
self.connection_interrupted = False
self.connection_string = None | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot disconnect when we are not connected\"",
")",
"# Close the streaming and tracing interfaces when we disconnect",
"self",
".",
"_reports",
"=",
... | Disconnect from the device that we are currently connected to. | [
"Disconnect",
"from",
"the",
"device",
"that",
"we",
"are",
"currently",
"connected",
"to",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L232-L245 |
23,522 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream._try_reconnect | def _try_reconnect(self):
"""Try to recover an interrupted connection."""
try:
if self.connection_interrupted:
self.connect_direct(self.connection_string, force=True)
self.connection_interrupted = False
self.connected = True
# Reenable streaming interface if that was open before as well
if self._reports is not None:
self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming'))
# Reenable tracing interface if that was open before as well
if self._traces is not None:
self._loop.run_coroutine(self.adapter.open_interface(0, 'tracing'))
except HardwareError as exc:
self._logger.exception("Error reconnecting to device after an unexpected disconnect")
raise HardwareError("Device disconnected unexpectedly and we could not reconnect", reconnect_error=exc) from exc | python | def _try_reconnect(self):
try:
if self.connection_interrupted:
self.connect_direct(self.connection_string, force=True)
self.connection_interrupted = False
self.connected = True
# Reenable streaming interface if that was open before as well
if self._reports is not None:
self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming'))
# Reenable tracing interface if that was open before as well
if self._traces is not None:
self._loop.run_coroutine(self.adapter.open_interface(0, 'tracing'))
except HardwareError as exc:
self._logger.exception("Error reconnecting to device after an unexpected disconnect")
raise HardwareError("Device disconnected unexpectedly and we could not reconnect", reconnect_error=exc) from exc | [
"def",
"_try_reconnect",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"connection_interrupted",
":",
"self",
".",
"connect_direct",
"(",
"self",
".",
"connection_string",
",",
"force",
"=",
"True",
")",
"self",
".",
"connection_interrupted",
"=",
"F... | Try to recover an interrupted connection. | [
"Try",
"to",
"recover",
"an",
"interrupted",
"connection",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L247-L265 |
23,523 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.send_rpc | def send_rpc(self, address, rpc_id, call_payload, timeout=3.0):
"""Send an rpc to our connected device.
The device must already be connected and the rpc interface open. This
method will synchronously send an RPC and wait for the response. Any
RPC errors will be raised as exceptions and if there were no errors, the
RPC's response payload will be returned as a binary bytearray.
See :meth:`AbstractDeviceAdapter.send_rpc` for documentation of the possible
exceptions that can be raised here.
Args:
address (int): The tile address containing the RPC
rpc_id (int): The ID of the RPC that we wish to call.
call_payload (bytes): The payload containing encoded arguments for the
RPC.
timeout (float): The maximum number of seconds to wait for the RPC to
finish. Defaults to 3s.
Returns:
bytearray: The RPC's response payload.
"""
if not self.connected:
raise HardwareError("Cannot send an RPC if we are not in a connected state")
if timeout is None:
timeout = 3.0
status = -1
payload = b''
recording = None
if self.connection_interrupted:
self._try_reconnect()
if self._record is not None:
recording = _RecordedRPC(self.connection_string, address, rpc_id, call_payload)
recording.start()
try:
payload = self._loop.run_coroutine(self.adapter.send_rpc(0, address, rpc_id, call_payload, timeout))
status, payload = pack_rpc_response(payload, None)
except VALID_RPC_EXCEPTIONS as exc:
status, payload = pack_rpc_response(payload, exc)
if self._record is not None:
recording.finish(status, payload)
self._recording.append(recording)
if self.connection_interrupted:
self._try_reconnect()
return unpack_rpc_response(status, payload, rpc_id, address) | python | def send_rpc(self, address, rpc_id, call_payload, timeout=3.0):
if not self.connected:
raise HardwareError("Cannot send an RPC if we are not in a connected state")
if timeout is None:
timeout = 3.0
status = -1
payload = b''
recording = None
if self.connection_interrupted:
self._try_reconnect()
if self._record is not None:
recording = _RecordedRPC(self.connection_string, address, rpc_id, call_payload)
recording.start()
try:
payload = self._loop.run_coroutine(self.adapter.send_rpc(0, address, rpc_id, call_payload, timeout))
status, payload = pack_rpc_response(payload, None)
except VALID_RPC_EXCEPTIONS as exc:
status, payload = pack_rpc_response(payload, exc)
if self._record is not None:
recording.finish(status, payload)
self._recording.append(recording)
if self.connection_interrupted:
self._try_reconnect()
return unpack_rpc_response(status, payload, rpc_id, address) | [
"def",
"send_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"call_payload",
",",
"timeout",
"=",
"3.0",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot send an RPC if we are not in a connected state\"",
")",
... | Send an rpc to our connected device.
The device must already be connected and the rpc interface open. This
method will synchronously send an RPC and wait for the response. Any
RPC errors will be raised as exceptions and if there were no errors, the
RPC's response payload will be returned as a binary bytearray.
See :meth:`AbstractDeviceAdapter.send_rpc` for documentation of the possible
exceptions that can be raised here.
Args:
address (int): The tile address containing the RPC
rpc_id (int): The ID of the RPC that we wish to call.
call_payload (bytes): The payload containing encoded arguments for the
RPC.
timeout (float): The maximum number of seconds to wait for the RPC to
finish. Defaults to 3s.
Returns:
bytearray: The RPC's response payload. | [
"Send",
"an",
"rpc",
"to",
"our",
"connected",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L267-L320 |
23,524 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.send_highspeed | def send_highspeed(self, data, progress_callback):
"""Send a script to a device at highspeed, reporting progress.
This method takes a binary blob and downloads it to the device as fast
as possible, calling the passed progress_callback periodically with
updates on how far it has gotten.
Args:
data (bytes): The binary blob that should be sent to the device at highspeed.
progress_callback (callable): A function that will be called periodically to
report progress. The signature must be callback(done_count, total_count)
where done_count and total_count will be passed as integers.
"""
if not self.connected:
raise HardwareError("Cannot send a script if we are not in a connected state")
if isinstance(data, str) and not isinstance(data, bytes):
raise ArgumentError("You must send bytes or bytearray to _send_highspeed", type=type(data))
if not isinstance(data, bytes):
data = bytes(data)
try:
self._on_progress = progress_callback
self._loop.run_coroutine(self.adapter.send_script(0, data))
finally:
self._on_progress = None | python | def send_highspeed(self, data, progress_callback):
if not self.connected:
raise HardwareError("Cannot send a script if we are not in a connected state")
if isinstance(data, str) and not isinstance(data, bytes):
raise ArgumentError("You must send bytes or bytearray to _send_highspeed", type=type(data))
if not isinstance(data, bytes):
data = bytes(data)
try:
self._on_progress = progress_callback
self._loop.run_coroutine(self.adapter.send_script(0, data))
finally:
self._on_progress = None | [
"def",
"send_highspeed",
"(",
"self",
",",
"data",
",",
"progress_callback",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot send a script if we are not in a connected state\"",
")",
"if",
"isinstance",
"(",
"data",
","... | Send a script to a device at highspeed, reporting progress.
This method takes a binary blob and downloads it to the device as fast
as possible, calling the passed progress_callback periodically with
updates on how far it has gotten.
Args:
data (bytes): The binary blob that should be sent to the device at highspeed.
progress_callback (callable): A function that will be called periodically to
report progress. The signature must be callback(done_count, total_count)
where done_count and total_count will be passed as integers. | [
"Send",
"a",
"script",
"to",
"a",
"device",
"at",
"highspeed",
"reporting",
"progress",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L322-L349 |
23,525 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.enable_streaming | def enable_streaming(self):
"""Open the streaming interface and accumute reports in a queue.
This method is safe to call multiple times in a single device
connection. There is no way to check if the streaming interface is
opened or to close it once it is opened (apart from disconnecting from
the device).
The first time this method is called, it will open the streaming
interface and return a queue that will be filled asynchronously with
reports as they are received. Subsequent calls will just empty the
queue and return the same queue without interacting with the device at
all.
Returns:
queue.Queue: A queue that will be filled with reports from the device.
"""
if not self.connected:
raise HardwareError("Cannot enable streaming if we are not in a connected state")
if self._reports is not None:
_clear_queue(self._reports)
return self._reports
self._reports = queue.Queue()
self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming'))
return self._reports | python | def enable_streaming(self):
if not self.connected:
raise HardwareError("Cannot enable streaming if we are not in a connected state")
if self._reports is not None:
_clear_queue(self._reports)
return self._reports
self._reports = queue.Queue()
self._loop.run_coroutine(self.adapter.open_interface(0, 'streaming'))
return self._reports | [
"def",
"enable_streaming",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot enable streaming if we are not in a connected state\"",
")",
"if",
"self",
".",
"_reports",
"is",
"not",
"None",
":",
"_clear_queue... | Open the streaming interface and accumute reports in a queue.
This method is safe to call multiple times in a single device
connection. There is no way to check if the streaming interface is
opened or to close it once it is opened (apart from disconnecting from
the device).
The first time this method is called, it will open the streaming
interface and return a queue that will be filled asynchronously with
reports as they are received. Subsequent calls will just empty the
queue and return the same queue without interacting with the device at
all.
Returns:
queue.Queue: A queue that will be filled with reports from the device. | [
"Open",
"the",
"streaming",
"interface",
"and",
"accumute",
"reports",
"in",
"a",
"queue",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L351-L379 |
23,526 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.enable_tracing | def enable_tracing(self):
"""Open the tracing interface and accumulate traces in a queue.
This method is safe to call multiple times in a single device
connection. There is no way to check if the tracing interface is
opened or to close it once it is opened (apart from disconnecting from
the device).
The first time this method is called, it will open the tracing
interface and return a queue that will be filled asynchronously with
reports as they are received. Subsequent calls will just empty the
queue and return the same queue without interacting with the device at
all.
Returns:
queue.Queue: A queue that will be filled with trace data from the device.
The trace data will be in disjoint bytes objects in the queue
"""
if not self.connected:
raise HardwareError("Cannot enable tracing if we are not in a connected state")
if self._traces is not None:
_clear_queue(self._traces)
return self._traces
self._traces = queue.Queue()
self._loop.run_coroutine(self.adapter.open_interface(0, 'tracing'))
return self._traces | python | def enable_tracing(self):
if not self.connected:
raise HardwareError("Cannot enable tracing if we are not in a connected state")
if self._traces is not None:
_clear_queue(self._traces)
return self._traces
self._traces = queue.Queue()
self._loop.run_coroutine(self.adapter.open_interface(0, 'tracing'))
return self._traces | [
"def",
"enable_tracing",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot enable tracing if we are not in a connected state\"",
")",
"if",
"self",
".",
"_traces",
"is",
"not",
"None",
":",
"_clear_queue",
... | Open the tracing interface and accumulate traces in a queue.
This method is safe to call multiple times in a single device
connection. There is no way to check if the tracing interface is
opened or to close it once it is opened (apart from disconnecting from
the device).
The first time this method is called, it will open the tracing
interface and return a queue that will be filled asynchronously with
reports as they are received. Subsequent calls will just empty the
queue and return the same queue without interacting with the device at
all.
Returns:
queue.Queue: A queue that will be filled with trace data from the device.
The trace data will be in disjoint bytes objects in the queue | [
"Open",
"the",
"tracing",
"interface",
"and",
"accumulate",
"traces",
"in",
"a",
"queue",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L381-L411 |
23,527 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.enable_broadcasting | def enable_broadcasting(self):
"""Begin accumulating broadcast reports received from all devices.
This method will allocate a queue to receive broadcast reports that
will be filled asynchronously as broadcast reports are received.
Returns:
queue.Queue: A queue that will be filled with braodcast reports.
"""
if self._broadcast_reports is not None:
_clear_queue(self._broadcast_reports)
return self._broadcast_reports
self._broadcast_reports = queue.Queue()
return self._broadcast_reports | python | def enable_broadcasting(self):
if self._broadcast_reports is not None:
_clear_queue(self._broadcast_reports)
return self._broadcast_reports
self._broadcast_reports = queue.Queue()
return self._broadcast_reports | [
"def",
"enable_broadcasting",
"(",
"self",
")",
":",
"if",
"self",
".",
"_broadcast_reports",
"is",
"not",
"None",
":",
"_clear_queue",
"(",
"self",
".",
"_broadcast_reports",
")",
"return",
"self",
".",
"_broadcast_reports",
"self",
".",
"_broadcast_reports",
"... | Begin accumulating broadcast reports received from all devices.
This method will allocate a queue to receive broadcast reports that
will be filled asynchronously as broadcast reports are received.
Returns:
queue.Queue: A queue that will be filled with braodcast reports. | [
"Begin",
"accumulating",
"broadcast",
"reports",
"received",
"from",
"all",
"devices",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L413-L428 |
23,528 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.enable_debug | def enable_debug(self):
"""Open the debug interface on the connected device."""
if not self.connected:
raise HardwareError("Cannot enable debug if we are not in a connected state")
self._loop.run_coroutine(self.adapter.open_interface(0, 'debug')) | python | def enable_debug(self):
if not self.connected:
raise HardwareError("Cannot enable debug if we are not in a connected state")
self._loop.run_coroutine(self.adapter.open_interface(0, 'debug')) | [
"def",
"enable_debug",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"HardwareError",
"(",
"\"Cannot enable debug if we are not in a connected state\"",
")",
"self",
".",
"_loop",
".",
"run_coroutine",
"(",
"self",
".",
"adapter",
"."... | Open the debug interface on the connected device. | [
"Open",
"the",
"debug",
"interface",
"on",
"the",
"connected",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L430-L436 |
23,529 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.debug_command | def debug_command(self, cmd, args=None, progress_callback=None):
"""Send a debug command to the connected device.
This generic method will send a named debug command with the given
arguments to the connected device. Debug commands are typically used
for things like forcible reflashing of firmware or other, debug-style,
operations. Not all transport protocols support debug commands and
the supported operations vary depeneding on the transport protocol.
Args:
cmd (str): The name of the debug command to send.
args (dict): Any arguments required by the given debug command
progress_callback (callable): A function that will be called periodically to
report progress. The signature must be callback(done_count, total_count)
where done_count and total_count will be passed as integers.
Returns:
object: The return value of the debug command, if there is one.
"""
if args is None:
args = {}
try:
self._on_progress = progress_callback
return self._loop.run_coroutine(self.adapter.debug(0, cmd, args))
finally:
self._on_progress = None | python | def debug_command(self, cmd, args=None, progress_callback=None):
if args is None:
args = {}
try:
self._on_progress = progress_callback
return self._loop.run_coroutine(self.adapter.debug(0, cmd, args))
finally:
self._on_progress = None | [
"def",
"debug_command",
"(",
"self",
",",
"cmd",
",",
"args",
"=",
"None",
",",
"progress_callback",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"{",
"}",
"try",
":",
"self",
".",
"_on_progress",
"=",
"progress_callback",
"retu... | Send a debug command to the connected device.
This generic method will send a named debug command with the given
arguments to the connected device. Debug commands are typically used
for things like forcible reflashing of firmware or other, debug-style,
operations. Not all transport protocols support debug commands and
the supported operations vary depeneding on the transport protocol.
Args:
cmd (str): The name of the debug command to send.
args (dict): Any arguments required by the given debug command
progress_callback (callable): A function that will be called periodically to
report progress. The signature must be callback(done_count, total_count)
where done_count and total_count will be passed as integers.
Returns:
object: The return value of the debug command, if there is one. | [
"Send",
"a",
"debug",
"command",
"to",
"the",
"connected",
"device",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L438-L465 |
23,530 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream.close | def close(self):
"""Close this adapter stream.
This method may only be called once in the lifetime of an
AdapterStream and it will shutdown the underlying device adapter,
disconnect all devices and stop all background activity.
If this stream is configured to save a record of all RPCs, the RPCs
will be logged to a file at this point.
"""
try:
self._loop.run_coroutine(self.adapter.stop())
finally:
self._save_recording() | python | def close(self):
try:
self._loop.run_coroutine(self.adapter.stop())
finally:
self._save_recording() | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_loop",
".",
"run_coroutine",
"(",
"self",
".",
"adapter",
".",
"stop",
"(",
")",
")",
"finally",
":",
"self",
".",
"_save_recording",
"(",
")"
] | Close this adapter stream.
This method may only be called once in the lifetime of an
AdapterStream and it will shutdown the underlying device adapter,
disconnect all devices and stop all background activity.
If this stream is configured to save a record of all RPCs, the RPCs
will be logged to a file at this point. | [
"Close",
"this",
"adapter",
"stream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L467-L481 |
23,531 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream._on_scan | def _on_scan(self, info):
"""Callback called when a new device is discovered on this CMDStream
Args:
info (dict): Information about the scanned device
"""
device_id = info['uuid']
expiration_time = info.get('validity_period', 60)
infocopy = deepcopy(info)
infocopy['expiration_time'] = monotonic() + expiration_time
with self._scan_lock:
self._scanned_devices[device_id] = infocopy | python | def _on_scan(self, info):
device_id = info['uuid']
expiration_time = info.get('validity_period', 60)
infocopy = deepcopy(info)
infocopy['expiration_time'] = monotonic() + expiration_time
with self._scan_lock:
self._scanned_devices[device_id] = infocopy | [
"def",
"_on_scan",
"(",
"self",
",",
"info",
")",
":",
"device_id",
"=",
"info",
"[",
"'uuid'",
"]",
"expiration_time",
"=",
"info",
".",
"get",
"(",
"'validity_period'",
",",
"60",
")",
"infocopy",
"=",
"deepcopy",
"(",
"info",
")",
"infocopy",
"[",
"... | Callback called when a new device is discovered on this CMDStream
Args:
info (dict): Information about the scanned device | [
"Callback",
"called",
"when",
"a",
"new",
"device",
"is",
"discovered",
"on",
"this",
"CMDStream"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L518-L532 |
23,532 | iotile/coretools | iotilecore/iotile/core/hw/transport/adapterstream.py | AdapterStream._on_disconnect | def _on_disconnect(self):
"""Callback when a device is disconnected unexpectedly.
Args:
adapter_id (int): An ID for the adapter that was connected to the device
connection_id (int): An ID for the connection that has become disconnected
"""
self._logger.info("Connection to device %s was interrupted", self.connection_string)
self.connection_interrupted = True | python | def _on_disconnect(self):
self._logger.info("Connection to device %s was interrupted", self.connection_string)
self.connection_interrupted = True | [
"def",
"_on_disconnect",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Connection to device %s was interrupted\"",
",",
"self",
".",
"connection_string",
")",
"self",
".",
"connection_interrupted",
"=",
"True"
] | Callback when a device is disconnected unexpectedly.
Args:
adapter_id (int): An ID for the adapter that was connected to the device
connection_id (int): An ID for the connection that has become disconnected | [
"Callback",
"when",
"a",
"device",
"is",
"disconnected",
"unexpectedly",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapterstream.py#L534-L543 |
23,533 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/midl.py | midl_emitter | def midl_emitter(target, source, env):
"""Produces a list of outputs from the MIDL compiler"""
base, _ = SCons.Util.splitext(str(target[0]))
tlb = target[0]
incl = base + '.h'
interface = base + '_i.c'
targets = [tlb, incl, interface]
midlcom = env['MIDLCOM']
if midlcom.find('/proxy') != -1:
proxy = base + '_p.c'
targets.append(proxy)
if midlcom.find('/dlldata') != -1:
dlldata = base + '_data.c'
targets.append(dlldata)
return (targets, source) | python | def midl_emitter(target, source, env):
base, _ = SCons.Util.splitext(str(target[0]))
tlb = target[0]
incl = base + '.h'
interface = base + '_i.c'
targets = [tlb, incl, interface]
midlcom = env['MIDLCOM']
if midlcom.find('/proxy') != -1:
proxy = base + '_p.c'
targets.append(proxy)
if midlcom.find('/dlldata') != -1:
dlldata = base + '_data.c'
targets.append(dlldata)
return (targets, source) | [
"def",
"midl_emitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"base",
",",
"_",
"=",
"SCons",
".",
"Util",
".",
"splitext",
"(",
"str",
"(",
"target",
"[",
"0",
"]",
")",
")",
"tlb",
"=",
"target",
"[",
"0",
"]",
"incl",
"=",
"base... | Produces a list of outputs from the MIDL compiler | [
"Produces",
"a",
"list",
"of",
"outputs",
"from",
"the",
"MIDL",
"compiler"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/midl.py#L44-L61 |
23,534 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/midl.py | generate | def generate(env):
"""Add Builders and construction variables for midl to an Environment."""
env['MIDL'] = 'MIDL.EXE'
env['MIDLFLAGS'] = SCons.Util.CLVar('/nologo')
env['MIDLCOM'] = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata ${TARGETS[4]} $SOURCE 2> NUL'
env['BUILDERS']['TypeLibrary'] = midl_builder | python | def generate(env):
env['MIDL'] = 'MIDL.EXE'
env['MIDLFLAGS'] = SCons.Util.CLVar('/nologo')
env['MIDLCOM'] = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata ${TARGETS[4]} $SOURCE 2> NUL'
env['BUILDERS']['TypeLibrary'] = midl_builder | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
"[",
"'MIDL'",
"]",
"=",
"'MIDL.EXE'",
"env",
"[",
"'MIDLFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'/nologo'",
")",
"env",
"[",
"'MIDLCOM'",
"]",
"=",
"'$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} ... | Add Builders and construction variables for midl to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"midl",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/midl.py#L73-L79 |
23,535 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConsign.py | Base.set_entry | def set_entry(self, filename, obj):
"""
Set the entry.
"""
self.entries[filename] = obj
self.dirty = True | python | def set_entry(self, filename, obj):
self.entries[filename] = obj
self.dirty = True | [
"def",
"set_entry",
"(",
"self",
",",
"filename",
",",
"obj",
")",
":",
"self",
".",
"entries",
"[",
"filename",
"]",
"=",
"obj",
"self",
".",
"dirty",
"=",
"True"
] | Set the entry. | [
"Set",
"the",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConsign.py#L187-L192 |
23,536 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConsign.py | DirFile.write | def write(self, sync=1):
"""
Write the .sconsign file to disk.
Try to write to a temporary file first, and rename it if we
succeed. If we can't write to the temporary file, it's
probably because the directory isn't writable (and if so,
how did we build anything in this directory, anyway?), so
try to write directly to the .sconsign file as a backup.
If we can't rename, try to copy the temporary contents back
to the .sconsign file. Either way, always try to remove
the temporary file at the end.
"""
if not self.dirty:
return
self.merge()
temp = os.path.join(self.dir.get_internal_path(), '.scons%d' % os.getpid())
try:
file = open(temp, 'wb')
fname = temp
except IOError:
try:
file = open(self.sconsign, 'wb')
fname = self.sconsign
except IOError:
return
for key, entry in self.entries.items():
entry.convert_to_sconsign()
pickle.dump(self.entries, file, PICKLE_PROTOCOL)
file.close()
if fname != self.sconsign:
try:
mode = os.stat(self.sconsign)[0]
os.chmod(self.sconsign, 0o666)
os.unlink(self.sconsign)
except (IOError, OSError):
# Try to carry on in the face of either OSError
# (things like permission issues) or IOError (disk
# or network issues). If there's a really dangerous
# issue, it should get re-raised by the calls below.
pass
try:
os.rename(fname, self.sconsign)
except OSError:
# An OSError failure to rename may indicate something
# like the directory has no write permission, but
# the .sconsign file itself might still be writable,
# so try writing on top of it directly. An IOError
# here, or in any of the following calls, would get
# raised, indicating something like a potentially
# serious disk or network issue.
open(self.sconsign, 'wb').write(open(fname, 'rb').read())
os.chmod(self.sconsign, mode)
try:
os.unlink(temp)
except (IOError, OSError):
pass | python | def write(self, sync=1):
if not self.dirty:
return
self.merge()
temp = os.path.join(self.dir.get_internal_path(), '.scons%d' % os.getpid())
try:
file = open(temp, 'wb')
fname = temp
except IOError:
try:
file = open(self.sconsign, 'wb')
fname = self.sconsign
except IOError:
return
for key, entry in self.entries.items():
entry.convert_to_sconsign()
pickle.dump(self.entries, file, PICKLE_PROTOCOL)
file.close()
if fname != self.sconsign:
try:
mode = os.stat(self.sconsign)[0]
os.chmod(self.sconsign, 0o666)
os.unlink(self.sconsign)
except (IOError, OSError):
# Try to carry on in the face of either OSError
# (things like permission issues) or IOError (disk
# or network issues). If there's a really dangerous
# issue, it should get re-raised by the calls below.
pass
try:
os.rename(fname, self.sconsign)
except OSError:
# An OSError failure to rename may indicate something
# like the directory has no write permission, but
# the .sconsign file itself might still be writable,
# so try writing on top of it directly. An IOError
# here, or in any of the following calls, would get
# raised, indicating something like a potentially
# serious disk or network issue.
open(self.sconsign, 'wb').write(open(fname, 'rb').read())
os.chmod(self.sconsign, mode)
try:
os.unlink(temp)
except (IOError, OSError):
pass | [
"def",
"write",
"(",
"self",
",",
"sync",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"dirty",
":",
"return",
"self",
".",
"merge",
"(",
")",
"temp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dir",
".",
"get_internal_path",
"(",
... | Write the .sconsign file to disk.
Try to write to a temporary file first, and rename it if we
succeed. If we can't write to the temporary file, it's
probably because the directory isn't writable (and if so,
how did we build anything in this directory, anyway?), so
try to write directly to the .sconsign file as a backup.
If we can't rename, try to copy the temporary contents back
to the .sconsign file. Either way, always try to remove
the temporary file at the end. | [
"Write",
"the",
".",
"sconsign",
"file",
"to",
"disk",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConsign.py#L343-L401 |
23,537 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgilink.py | generate | def generate(env):
"""Add Builders and construction variables for MIPSPro to an Environment."""
link.generate(env)
env['LINK'] = env.Detect(linkers) or 'cc'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
# __RPATH is set to $_RPATH in the platform specification if that
# platform supports it.
env['RPATHPREFIX'] = '-rpath '
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}' | python | def generate(env):
link.generate(env)
env['LINK'] = env.Detect(linkers) or 'cc'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
# __RPATH is set to $_RPATH in the platform specification if that
# platform supports it.
env['RPATHPREFIX'] = '-rpath '
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}' | [
"def",
"generate",
"(",
"env",
")",
":",
"link",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'LINK'",
"]",
"=",
"env",
".",
"Detect",
"(",
"linkers",
")",
"or",
"'cc'",
"env",
"[",
"'SHLINKFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
... | Add Builders and construction variables for MIPSPro to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"MIPSPro",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgilink.py#L42-L53 |
23,538 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.start | async def start(self):
"""Start the supervisor server."""
await self.server.start()
self.port = self.server.port | python | async def start(self):
await self.server.start()
self.port = self.server.port | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"await",
"self",
".",
"server",
".",
"start",
"(",
")",
"self",
".",
"port",
"=",
"self",
".",
"server",
".",
"port"
] | Start the supervisor server. | [
"Start",
"the",
"supervisor",
"server",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L86-L90 |
23,539 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.prepare_conn | async def prepare_conn(self, conn):
"""Setup a new connection from a client."""
client_id = str(uuid.uuid4())
monitor = functools.partial(self.send_event, client_id)
self._logger.info("New client connection: %s", client_id)
self.service_manager.add_monitor(monitor)
self.clients[client_id] = dict(connection=conn, monitor=monitor)
return client_id | python | async def prepare_conn(self, conn):
client_id = str(uuid.uuid4())
monitor = functools.partial(self.send_event, client_id)
self._logger.info("New client connection: %s", client_id)
self.service_manager.add_monitor(monitor)
self.clients[client_id] = dict(connection=conn, monitor=monitor)
return client_id | [
"async",
"def",
"prepare_conn",
"(",
"self",
",",
"conn",
")",
":",
"client_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"monitor",
"=",
"functools",
".",
"partial",
"(",
"self",
".",
"send_event",
",",
"client_id",
")",
"self",
".",
"_... | Setup a new connection from a client. | [
"Setup",
"a",
"new",
"connection",
"from",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L97-L108 |
23,540 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.teardown_conn | async def teardown_conn(self, context):
"""Teardown a connection from a client."""
client_id = context.user_data
self._logger.info("Tearing down client connection: %s", client_id)
if client_id not in self.clients:
self._logger.warning("client_id %s did not exist in teardown_conn", client_id)
else:
del self.clients[client_id] | python | async def teardown_conn(self, context):
client_id = context.user_data
self._logger.info("Tearing down client connection: %s", client_id)
if client_id not in self.clients:
self._logger.warning("client_id %s did not exist in teardown_conn", client_id)
else:
del self.clients[client_id] | [
"async",
"def",
"teardown_conn",
"(",
"self",
",",
"context",
")",
":",
"client_id",
"=",
"context",
".",
"user_data",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Tearing down client connection: %s\"",
",",
"client_id",
")",
"if",
"client_id",
"not",
"in",
"s... | Teardown a connection from a client. | [
"Teardown",
"a",
"connection",
"from",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L110-L119 |
23,541 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.send_event | async def send_event(self, client_id, service_name, event_name, event_info, directed_client=None):
"""Send an event to a client."""
if directed_client is not None and directed_client != client_id:
return
client_info = self.clients.get(client_id)
if client_info is None:
self._logger.warning("Attempted to send event to invalid client id: %s", client_id)
return
conn = client_info['connection']
event = dict(service=service_name)
if event_info is not None:
event['payload'] = event_info
self._logger.debug("Sending event: %s", event)
await self.server.send_event(conn, event_name, event) | python | async def send_event(self, client_id, service_name, event_name, event_info, directed_client=None):
if directed_client is not None and directed_client != client_id:
return
client_info = self.clients.get(client_id)
if client_info is None:
self._logger.warning("Attempted to send event to invalid client id: %s", client_id)
return
conn = client_info['connection']
event = dict(service=service_name)
if event_info is not None:
event['payload'] = event_info
self._logger.debug("Sending event: %s", event)
await self.server.send_event(conn, event_name, event) | [
"async",
"def",
"send_event",
"(",
"self",
",",
"client_id",
",",
"service_name",
",",
"event_name",
",",
"event_info",
",",
"directed_client",
"=",
"None",
")",
":",
"if",
"directed_client",
"is",
"not",
"None",
"and",
"directed_client",
"!=",
"client_id",
":... | Send an event to a client. | [
"Send",
"an",
"event",
"to",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L121-L140 |
23,542 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.send_rpc | async def send_rpc(self, msg, _context):
"""Send an RPC to a service on behalf of a client."""
service = msg.get('name')
rpc_id = msg.get('rpc_id')
payload = msg.get('payload')
timeout = msg.get('timeout')
response_id = await self.service_manager.send_rpc_command(service, rpc_id, payload,
timeout)
try:
result = await self.service_manager.rpc_results.get(response_id, timeout=timeout)
except asyncio.TimeoutError:
self._logger.warning("RPC 0x%04X on service %s timed out after %f seconds",
rpc_id, service, timeout)
result = dict(result='timeout', response=b'')
return result | python | async def send_rpc(self, msg, _context):
service = msg.get('name')
rpc_id = msg.get('rpc_id')
payload = msg.get('payload')
timeout = msg.get('timeout')
response_id = await self.service_manager.send_rpc_command(service, rpc_id, payload,
timeout)
try:
result = await self.service_manager.rpc_results.get(response_id, timeout=timeout)
except asyncio.TimeoutError:
self._logger.warning("RPC 0x%04X on service %s timed out after %f seconds",
rpc_id, service, timeout)
result = dict(result='timeout', response=b'')
return result | [
"async",
"def",
"send_rpc",
"(",
"self",
",",
"msg",
",",
"_context",
")",
":",
"service",
"=",
"msg",
".",
"get",
"(",
"'name'",
")",
"rpc_id",
"=",
"msg",
".",
"get",
"(",
"'rpc_id'",
")",
"payload",
"=",
"msg",
".",
"get",
"(",
"'payload'",
")",... | Send an RPC to a service on behalf of a client. | [
"Send",
"an",
"RPC",
"to",
"a",
"service",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L142-L160 |
23,543 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.respond_rpc | async def respond_rpc(self, msg, _context):
"""Respond to an RPC previously sent to a service."""
rpc_id = msg.get('response_uuid')
result = msg.get('result')
payload = msg.get('response')
self.service_manager.send_rpc_response(rpc_id, result, payload) | python | async def respond_rpc(self, msg, _context):
rpc_id = msg.get('response_uuid')
result = msg.get('result')
payload = msg.get('response')
self.service_manager.send_rpc_response(rpc_id, result, payload) | [
"async",
"def",
"respond_rpc",
"(",
"self",
",",
"msg",
",",
"_context",
")",
":",
"rpc_id",
"=",
"msg",
".",
"get",
"(",
"'response_uuid'",
")",
"result",
"=",
"msg",
".",
"get",
"(",
"'result'",
")",
"payload",
"=",
"msg",
".",
"get",
"(",
"'respon... | Respond to an RPC previously sent to a service. | [
"Respond",
"to",
"an",
"RPC",
"previously",
"sent",
"to",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L162-L169 |
23,544 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.set_agent | async def set_agent(self, msg, context):
"""Mark a client as the RPC agent for a service."""
service = msg.get('name')
client = context.user_data
self.service_manager.set_agent(service, client) | python | async def set_agent(self, msg, context):
service = msg.get('name')
client = context.user_data
self.service_manager.set_agent(service, client) | [
"async",
"def",
"set_agent",
"(",
"self",
",",
"msg",
",",
"context",
")",
":",
"service",
"=",
"msg",
".",
"get",
"(",
"'name'",
")",
"client",
"=",
"context",
".",
"user_data",
"self",
".",
"service_manager",
".",
"set_agent",
"(",
"service",
",",
"c... | Mark a client as the RPC agent for a service. | [
"Mark",
"a",
"client",
"as",
"the",
"RPC",
"agent",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L176-L182 |
23,545 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.service_messages | async def service_messages(self, msg, _context):
"""Get all messages for a service."""
msgs = self.service_manager.service_messages(msg.get('name'))
return [x.to_dict() for x in msgs] | python | async def service_messages(self, msg, _context):
msgs = self.service_manager.service_messages(msg.get('name'))
return [x.to_dict() for x in msgs] | [
"async",
"def",
"service_messages",
"(",
"self",
",",
"msg",
",",
"_context",
")",
":",
"msgs",
"=",
"self",
".",
"service_manager",
".",
"service_messages",
"(",
"msg",
".",
"get",
"(",
"'name'",
")",
")",
"return",
"[",
"x",
".",
"to_dict",
"(",
")",... | Get all messages for a service. | [
"Get",
"all",
"messages",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L219-L223 |
23,546 | iotile/coretools | iotilegateway/iotilegateway/supervisor/server.py | IOTileSupervisor.service_headline | async def service_headline(self, msg, _context):
"""Get the headline for a service."""
headline = self.service_manager.service_headline(msg.get('name'))
if headline is not None:
headline = headline.to_dict()
return headline | python | async def service_headline(self, msg, _context):
headline = self.service_manager.service_headline(msg.get('name'))
if headline is not None:
headline = headline.to_dict()
return headline | [
"async",
"def",
"service_headline",
"(",
"self",
",",
"msg",
",",
"_context",
")",
":",
"headline",
"=",
"self",
".",
"service_manager",
".",
"service_headline",
"(",
"msg",
".",
"get",
"(",
"'name'",
")",
")",
"if",
"headline",
"is",
"not",
"None",
":",... | Get the headline for a service. | [
"Get",
"the",
"headline",
"for",
"a",
"service",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/server.py#L225-L232 |
23,547 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/nasm.py | generate | def generate(env):
"""Add Builders and construction variables for nasm to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
env['AS'] = 'nasm'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES' | python | def generate(env):
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
env['AS'] = 'nasm'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES' | [
"def",
"generate",
"(",
"env",
")",
":",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffix",
"in",
"ASSuffixes",
":",
"static_obj",
".",
"add_action",
"(",
"suffix",
",",
"SCons",
".",
"... | Add Builders and construction variables for nasm to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"nasm",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/nasm.py#L47-L63 |
23,548 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sunlink.py | generate | def generate(env):
"""Add Builders and construction variables for Forte to an Environment."""
link.generate(env)
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -G')
env['RPATHPREFIX'] = '-R'
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}'
# Support for versioned libraries
link._setup_versioned_lib_variables(env, tool = 'sunlink', use_soname = True)
env['LINKCALLBACKS'] = link._versioned_lib_callbacks() | python | def generate(env):
link.generate(env)
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -G')
env['RPATHPREFIX'] = '-R'
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}'
# Support for versioned libraries
link._setup_versioned_lib_variables(env, tool = 'sunlink', use_soname = True)
env['LINKCALLBACKS'] = link._versioned_lib_callbacks() | [
"def",
"generate",
"(",
"env",
")",
":",
"link",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'SHLINKFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$LINKFLAGS -G'",
")",
"env",
"[",
"'RPATHPREFIX'",
"]",
"=",
"'-R'",
"env",
"[",
"'RP... | Add Builders and construction variables for Forte to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Forte",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sunlink.py#L59-L71 |
23,549 | iotile/coretools | iotilecore/iotile/core/utilities/schema_verify/verifier.py | Verifier._get_short_description | def _get_short_description(self):
"""Return the first line of a multiline description
Returns:
string: The short description, otherwise None
"""
if self.description is None:
return None
lines = [x for x in self.description.split('\n')]
if len(lines) == 1:
return lines[0]
elif len(lines) >= 3 and lines[1] == '':
return lines[0]
return None | python | def _get_short_description(self):
if self.description is None:
return None
lines = [x for x in self.description.split('\n')]
if len(lines) == 1:
return lines[0]
elif len(lines) >= 3 and lines[1] == '':
return lines[0]
return None | [
"def",
"_get_short_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"description",
"is",
"None",
":",
"return",
"None",
"lines",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"description",
".",
"split",
"(",
"'\\n'",
")",
"]",
"if",
"len",
"(... | Return the first line of a multiline description
Returns:
string: The short description, otherwise None | [
"Return",
"the",
"first",
"line",
"of",
"a",
"multiline",
"description"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/verifier.py#L70-L86 |
23,550 | iotile/coretools | iotilecore/iotile/core/utilities/schema_verify/verifier.py | Verifier._get_long_description | def _get_long_description(self):
"""Return the subsequent lines of a multiline description
Returns:
string: The long description, otherwise None
"""
if self.description is None:
return None
lines = [x for x in self.description.split('\n')]
if len(lines) == 1:
return None
elif len(lines) >= 3 and lines[1] == '':
return '\n'.join(lines[2:])
return self.description | python | def _get_long_description(self):
if self.description is None:
return None
lines = [x for x in self.description.split('\n')]
if len(lines) == 1:
return None
elif len(lines) >= 3 and lines[1] == '':
return '\n'.join(lines[2:])
return self.description | [
"def",
"_get_long_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"description",
"is",
"None",
":",
"return",
"None",
"lines",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"description",
".",
"split",
"(",
"'\\n'",
")",
"]",
"if",
"len",
"("... | Return the subsequent lines of a multiline description
Returns:
string: The long description, otherwise None | [
"Return",
"the",
"subsequent",
"lines",
"of",
"a",
"multiline",
"description"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/verifier.py#L88-L105 |
23,551 | iotile/coretools | iotilecore/iotile/core/utilities/schema_verify/verifier.py | Verifier.wrap_lines | def wrap_lines(self, text, indent_level, indent_size=4):
"""Indent a multiline string
Args:
text (string): The string to indent
indent_level (int): The number of indent_size spaces to prepend
to each line
indent_size (int): The number of spaces to prepend for each indent
level
Returns:
string: The indented block of text
"""
indent = ' '*indent_size*indent_level
lines = text.split('\n')
wrapped_lines = []
for line in lines:
if line == '':
wrapped_lines.append(line)
else:
wrapped_lines.append(indent + line)
return '\n'.join(wrapped_lines) | python | def wrap_lines(self, text, indent_level, indent_size=4):
indent = ' '*indent_size*indent_level
lines = text.split('\n')
wrapped_lines = []
for line in lines:
if line == '':
wrapped_lines.append(line)
else:
wrapped_lines.append(indent + line)
return '\n'.join(wrapped_lines) | [
"def",
"wrap_lines",
"(",
"self",
",",
"text",
",",
"indent_level",
",",
"indent_size",
"=",
"4",
")",
":",
"indent",
"=",
"' '",
"*",
"indent_size",
"*",
"indent_level",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"wrapped_lines",
"=",
"[",
... | Indent a multiline string
Args:
text (string): The string to indent
indent_level (int): The number of indent_size spaces to prepend
to each line
indent_size (int): The number of spaces to prepend for each indent
level
Returns:
string: The indented block of text | [
"Indent",
"a",
"multiline",
"string"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/verifier.py#L107-L132 |
23,552 | iotile/coretools | iotilecore/iotile/core/utilities/schema_verify/verifier.py | Verifier.format_name | def format_name(self, name, indent_size=4):
"""Format the name of this verifier
The name will be formatted as:
<name>: <short description>
long description if one is given followed by \n
otherwise no long description
Args:
name (string): A name for this validator
indent_size (int): The number of spaces to indent the
description
Returns:
string: The formatted name block with a short and or long
description appended.
"""
name_block = ''
if self.short_desc is None:
name_block += name + '\n'
else:
name_block += name + ': ' + self.short_desc + '\n'
if self.long_desc is not None:
name_block += self.wrap_lines(self.long_desc, 1, indent_size=indent_size)
name_block += '\n'
return name_block | python | def format_name(self, name, indent_size=4):
name_block = ''
if self.short_desc is None:
name_block += name + '\n'
else:
name_block += name + ': ' + self.short_desc + '\n'
if self.long_desc is not None:
name_block += self.wrap_lines(self.long_desc, 1, indent_size=indent_size)
name_block += '\n'
return name_block | [
"def",
"format_name",
"(",
"self",
",",
"name",
",",
"indent_size",
"=",
"4",
")",
":",
"name_block",
"=",
"''",
"if",
"self",
".",
"short_desc",
"is",
"None",
":",
"name_block",
"+=",
"name",
"+",
"'\\n'",
"else",
":",
"name_block",
"+=",
"name",
"+",... | Format the name of this verifier
The name will be formatted as:
<name>: <short description>
long description if one is given followed by \n
otherwise no long description
Args:
name (string): A name for this validator
indent_size (int): The number of spaces to indent the
description
Returns:
string: The formatted name block with a short and or long
description appended. | [
"Format",
"the",
"name",
"of",
"this",
"verifier"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/verifier.py#L134-L162 |
23,553 | iotile/coretools | iotilecore/iotile/core/utilities/schema_verify/verifier.py | Verifier.trim_whitespace | def trim_whitespace(self, text):
"""Remove leading whitespace from each line of a multiline string
Args:
text (string): The text to be unindented
Returns:
string: The unindented block of text
"""
lines = text.split('\n')
new_lines = [x.lstrip() for x in lines]
return '\n'.join(new_lines) | python | def trim_whitespace(self, text):
lines = text.split('\n')
new_lines = [x.lstrip() for x in lines]
return '\n'.join(new_lines) | [
"def",
"trim_whitespace",
"(",
"self",
",",
"text",
")",
":",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"new_lines",
"=",
"[",
"x",
".",
"lstrip",
"(",
")",
"for",
"x",
"in",
"lines",
"]",
"return",
"'\\n'",
".",
"join",
"(",
"new_line... | Remove leading whitespace from each line of a multiline string
Args:
text (string): The text to be unindented
Returns:
string: The unindented block of text | [
"Remove",
"leading",
"whitespace",
"from",
"each",
"line",
"of",
"a",
"multiline",
"string"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/schema_verify/verifier.py#L164-L177 |
23,554 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __extend_targets_sources | def __extend_targets_sources(target, source):
""" Prepare the lists of target and source files. """
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target[:]
elif not SCons.Util.is_List(source):
source = [source]
if len(target) < len(source):
target.extend(source[len(target):])
return target, source | python | def __extend_targets_sources(target, source):
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target[:]
elif not SCons.Util.is_List(source):
source = [source]
if len(target) < len(source):
target.extend(source[len(target):])
return target, source | [
"def",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
":",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"target",
")",
":",
"target",
"=",
"[",
"target",
"]",
"if",
"not",
"source",
":",
"source",
"=",
"target",
"[",
":",
"... | Prepare the lists of target and source files. | [
"Prepare",
"the",
"lists",
"of",
"target",
"and",
"source",
"files",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L77-L88 |
23,555 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __select_builder | def __select_builder(lxml_builder, libxml2_builder, cmdline_builder):
""" Selects a builder, based on which Python modules are present. """
if prefer_xsltproc:
return cmdline_builder
if not has_libxml2:
# At the moment we prefer libxml2 over lxml, the latter can lead
# to conflicts when installed together with libxml2.
if has_lxml:
return lxml_builder
else:
return cmdline_builder
return libxml2_builder | python | def __select_builder(lxml_builder, libxml2_builder, cmdline_builder):
if prefer_xsltproc:
return cmdline_builder
if not has_libxml2:
# At the moment we prefer libxml2 over lxml, the latter can lead
# to conflicts when installed together with libxml2.
if has_lxml:
return lxml_builder
else:
return cmdline_builder
return libxml2_builder | [
"def",
"__select_builder",
"(",
"lxml_builder",
",",
"libxml2_builder",
",",
"cmdline_builder",
")",
":",
"if",
"prefer_xsltproc",
":",
"return",
"cmdline_builder",
"if",
"not",
"has_libxml2",
":",
"# At the moment we prefer libxml2 over lxml, the latter can lead",
"# to conf... | Selects a builder, based on which Python modules are present. | [
"Selects",
"a",
"builder",
"based",
"on",
"which",
"Python",
"modules",
"are",
"present",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L98-L111 |
23,556 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __ensure_suffix | def __ensure_suffix(t, suffix):
""" Ensure that the target t has the given suffix. """
tpath = str(t)
if not tpath.endswith(suffix):
return tpath+suffix
return t | python | def __ensure_suffix(t, suffix):
tpath = str(t)
if not tpath.endswith(suffix):
return tpath+suffix
return t | [
"def",
"__ensure_suffix",
"(",
"t",
",",
"suffix",
")",
":",
"tpath",
"=",
"str",
"(",
"t",
")",
"if",
"not",
"tpath",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"tpath",
"+",
"suffix",
"return",
"t"
] | Ensure that the target t has the given suffix. | [
"Ensure",
"that",
"the",
"target",
"t",
"has",
"the",
"given",
"suffix",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L113-L119 |
23,557 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __ensure_suffix_stem | def __ensure_suffix_stem(t, suffix):
""" Ensure that the target t has the given suffix, and return the file's stem. """
tpath = str(t)
if not tpath.endswith(suffix):
stem = tpath
tpath += suffix
return tpath, stem
else:
stem, ext = os.path.splitext(tpath)
return t, stem | python | def __ensure_suffix_stem(t, suffix):
tpath = str(t)
if not tpath.endswith(suffix):
stem = tpath
tpath += suffix
return tpath, stem
else:
stem, ext = os.path.splitext(tpath)
return t, stem | [
"def",
"__ensure_suffix_stem",
"(",
"t",
",",
"suffix",
")",
":",
"tpath",
"=",
"str",
"(",
"t",
")",
"if",
"not",
"tpath",
".",
"endswith",
"(",
"suffix",
")",
":",
"stem",
"=",
"tpath",
"tpath",
"+=",
"suffix",
"return",
"tpath",
",",
"stem",
"else... | Ensure that the target t has the given suffix, and return the file's stem. | [
"Ensure",
"that",
"the",
"target",
"t",
"has",
"the",
"given",
"suffix",
"and",
"return",
"the",
"file",
"s",
"stem",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L121-L132 |
23,558 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __create_output_dir | def __create_output_dir(base_dir):
""" Ensure that the output directory base_dir exists. """
root, tail = os.path.split(base_dir)
dir = None
if tail:
if base_dir.endswith('/'):
dir = base_dir
else:
dir = root
else:
if base_dir.endswith('/'):
dir = base_dir
if dir and not os.path.isdir(dir):
os.makedirs(dir) | python | def __create_output_dir(base_dir):
root, tail = os.path.split(base_dir)
dir = None
if tail:
if base_dir.endswith('/'):
dir = base_dir
else:
dir = root
else:
if base_dir.endswith('/'):
dir = base_dir
if dir and not os.path.isdir(dir):
os.makedirs(dir) | [
"def",
"__create_output_dir",
"(",
"base_dir",
")",
":",
"root",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"base_dir",
")",
"dir",
"=",
"None",
"if",
"tail",
":",
"if",
"base_dir",
".",
"endswith",
"(",
"'/'",
")",
":",
"dir",
"=",
"b... | Ensure that the output directory base_dir exists. | [
"Ensure",
"that",
"the",
"output",
"directory",
"base_dir",
"exists",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L142-L156 |
23,559 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __detect_cl_tool | def __detect_cl_tool(env, chainkey, cdict, cpriority=None):
"""
Helper function, picks a command line tool from the list
and initializes its environment variables.
"""
if env.get(chainkey,'') == '':
clpath = ''
if cpriority is None:
cpriority = cdict.keys()
for cltool in cpriority:
if __debug_tool_location:
print("DocBook: Looking for %s"%cltool)
clpath = env.WhereIs(cltool)
if clpath:
if __debug_tool_location:
print("DocBook: Found:%s"%cltool)
env[chainkey] = clpath
if not env[chainkey + 'COM']:
env[chainkey + 'COM'] = cdict[cltool]
break | python | def __detect_cl_tool(env, chainkey, cdict, cpriority=None):
if env.get(chainkey,'') == '':
clpath = ''
if cpriority is None:
cpriority = cdict.keys()
for cltool in cpriority:
if __debug_tool_location:
print("DocBook: Looking for %s"%cltool)
clpath = env.WhereIs(cltool)
if clpath:
if __debug_tool_location:
print("DocBook: Found:%s"%cltool)
env[chainkey] = clpath
if not env[chainkey + 'COM']:
env[chainkey + 'COM'] = cdict[cltool]
break | [
"def",
"__detect_cl_tool",
"(",
"env",
",",
"chainkey",
",",
"cdict",
",",
"cpriority",
"=",
"None",
")",
":",
"if",
"env",
".",
"get",
"(",
"chainkey",
",",
"''",
")",
"==",
"''",
":",
"clpath",
"=",
"''",
"if",
"cpriority",
"is",
"None",
":",
"cp... | Helper function, picks a command line tool from the list
and initializes its environment variables. | [
"Helper",
"function",
"picks",
"a",
"command",
"line",
"tool",
"from",
"the",
"list",
"and",
"initializes",
"its",
"environment",
"variables",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L176-L196 |
23,560 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | _detect | def _detect(env):
"""
Detect all the command line tools that we might need for creating
the requested output formats.
"""
global prefer_xsltproc
if env.get('DOCBOOK_PREFER_XSLTPROC',''):
prefer_xsltproc = True
if ((not has_libxml2 and not has_lxml) or (prefer_xsltproc)):
# Try to find the XSLT processors
__detect_cl_tool(env, 'DOCBOOK_XSLTPROC', xsltproc_com, xsltproc_com_priority)
__detect_cl_tool(env, 'DOCBOOK_XMLLINT', xmllint_com)
__detect_cl_tool(env, 'DOCBOOK_FOP', fop_com, ['fop','xep','jw']) | python | def _detect(env):
global prefer_xsltproc
if env.get('DOCBOOK_PREFER_XSLTPROC',''):
prefer_xsltproc = True
if ((not has_libxml2 and not has_lxml) or (prefer_xsltproc)):
# Try to find the XSLT processors
__detect_cl_tool(env, 'DOCBOOK_XSLTPROC', xsltproc_com, xsltproc_com_priority)
__detect_cl_tool(env, 'DOCBOOK_XMLLINT', xmllint_com)
__detect_cl_tool(env, 'DOCBOOK_FOP', fop_com, ['fop','xep','jw']) | [
"def",
"_detect",
"(",
"env",
")",
":",
"global",
"prefer_xsltproc",
"if",
"env",
".",
"get",
"(",
"'DOCBOOK_PREFER_XSLTPROC'",
",",
"''",
")",
":",
"prefer_xsltproc",
"=",
"True",
"if",
"(",
"(",
"not",
"has_libxml2",
"and",
"not",
"has_lxml",
")",
"or",
... | Detect all the command line tools that we might need for creating
the requested output formats. | [
"Detect",
"all",
"the",
"command",
"line",
"tools",
"that",
"we",
"might",
"need",
"for",
"creating",
"the",
"requested",
"output",
"formats",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L198-L213 |
23,561 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __xml_scan | def __xml_scan(node, env, path, arg):
""" Simple XML file scanner, detecting local images and XIncludes as implicit dependencies. """
# Does the node exist yet?
if not os.path.isfile(str(node)):
return []
if env.get('DOCBOOK_SCANENT',''):
# Use simple pattern matching for system entities..., no support
# for recursion yet.
contents = node.get_text_contents()
return sentity_re.findall(contents)
xsl_file = os.path.join(scriptpath,'utils','xmldepend.xsl')
if not has_libxml2 or prefer_xsltproc:
if has_lxml and not prefer_xsltproc:
from lxml import etree
xsl_tree = etree.parse(xsl_file)
doc = etree.parse(str(node))
result = doc.xslt(xsl_tree)
depfiles = [x.strip() for x in str(result).splitlines() if x.strip() != "" and not x.startswith("<?xml ")]
return depfiles
else:
# Try to call xsltproc
xsltproc = env.subst("$DOCBOOK_XSLTPROC")
if xsltproc and xsltproc.endswith('xsltproc'):
result = env.backtick(' '.join([xsltproc, xsl_file, str(node)]))
depfiles = [x.strip() for x in str(result).splitlines() if x.strip() != "" and not x.startswith("<?xml ")]
return depfiles
else:
# Use simple pattern matching, there is currently no support
# for xi:includes...
contents = node.get_text_contents()
return include_re.findall(contents)
styledoc = libxml2.parseFile(xsl_file)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.readFile(str(node), None, libxml2.XML_PARSE_NOENT)
result = style.applyStylesheet(doc, None)
depfiles = []
for x in str(result).splitlines():
if x.strip() != "" and not x.startswith("<?xml "):
depfiles.extend(x.strip().split())
style.freeStylesheet()
doc.freeDoc()
result.freeDoc()
return depfiles | python | def __xml_scan(node, env, path, arg):
# Does the node exist yet?
if not os.path.isfile(str(node)):
return []
if env.get('DOCBOOK_SCANENT',''):
# Use simple pattern matching for system entities..., no support
# for recursion yet.
contents = node.get_text_contents()
return sentity_re.findall(contents)
xsl_file = os.path.join(scriptpath,'utils','xmldepend.xsl')
if not has_libxml2 or prefer_xsltproc:
if has_lxml and not prefer_xsltproc:
from lxml import etree
xsl_tree = etree.parse(xsl_file)
doc = etree.parse(str(node))
result = doc.xslt(xsl_tree)
depfiles = [x.strip() for x in str(result).splitlines() if x.strip() != "" and not x.startswith("<?xml ")]
return depfiles
else:
# Try to call xsltproc
xsltproc = env.subst("$DOCBOOK_XSLTPROC")
if xsltproc and xsltproc.endswith('xsltproc'):
result = env.backtick(' '.join([xsltproc, xsl_file, str(node)]))
depfiles = [x.strip() for x in str(result).splitlines() if x.strip() != "" and not x.startswith("<?xml ")]
return depfiles
else:
# Use simple pattern matching, there is currently no support
# for xi:includes...
contents = node.get_text_contents()
return include_re.findall(contents)
styledoc = libxml2.parseFile(xsl_file)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.readFile(str(node), None, libxml2.XML_PARSE_NOENT)
result = style.applyStylesheet(doc, None)
depfiles = []
for x in str(result).splitlines():
if x.strip() != "" and not x.startswith("<?xml "):
depfiles.extend(x.strip().split())
style.freeStylesheet()
doc.freeDoc()
result.freeDoc()
return depfiles | [
"def",
"__xml_scan",
"(",
"node",
",",
"env",
",",
"path",
",",
"arg",
")",
":",
"# Does the node exist yet?",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"str",
"(",
"node",
")",
")",
":",
"return",
"[",
"]",
"if",
"env",
".",
"get",
"(",
... | Simple XML file scanner, detecting local images and XIncludes as implicit dependencies. | [
"Simple",
"XML",
"file",
"scanner",
"detecting",
"local",
"images",
"and",
"XIncludes",
"as",
"implicit",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L221-L272 |
23,562 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __xinclude_libxml2 | def __xinclude_libxml2(target, source, env):
"""
Resolving XIncludes, using the libxml2 module.
"""
doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)
doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)
doc.saveFile(str(target[0]))
doc.freeDoc()
return None | python | def __xinclude_libxml2(target, source, env):
doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)
doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)
doc.saveFile(str(target[0]))
doc.freeDoc()
return None | [
"def",
"__xinclude_libxml2",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"doc",
"=",
"libxml2",
".",
"readFile",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
",",
"None",
",",
"libxml2",
".",
"XML_PARSE_NOENT",
")",
"doc",
".",
"xincludeProce... | Resolving XIncludes, using the libxml2 module. | [
"Resolving",
"XIncludes",
"using",
"the",
"libxml2",
"module",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L361-L370 |
23,563 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | __xinclude_lxml | def __xinclude_lxml(target, source, env):
"""
Resolving XIncludes, using the lxml module.
"""
from lxml import etree
doc = etree.parse(str(source[0]))
doc.xinclude()
try:
doc.write(str(target[0]), xml_declaration=True,
encoding="UTF-8", pretty_print=True)
except:
pass
return None | python | def __xinclude_lxml(target, source, env):
from lxml import etree
doc = etree.parse(str(source[0]))
doc.xinclude()
try:
doc.write(str(target[0]), xml_declaration=True,
encoding="UTF-8", pretty_print=True)
except:
pass
return None | [
"def",
"__xinclude_lxml",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"from",
"lxml",
"import",
"etree",
"doc",
"=",
"etree",
".",
"parse",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
")",
"doc",
".",
"xinclude",
"(",
")",
"try",
":",
... | Resolving XIncludes, using the lxml module. | [
"Resolving",
"XIncludes",
"using",
"the",
"lxml",
"module",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L372-L386 |
23,564 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | DocbookHtml | def DocbookHtml(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for HTML output.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_HTML', ['html','docbook.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
r = __builder.__call__(env, __ensure_suffix(t,'.html'), s, **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
return result | python | def DocbookHtml(env, target, source=None, *args, **kw):
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_HTML', ['html','docbook.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
r = __builder.__call__(env, __ensure_suffix(t,'.html'), s, **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
return result | [
"def",
"DocbookHtml",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
"# ... | A pseudo-Builder, providing a Docbook toolchain for HTML output. | [
"A",
"pseudo",
"-",
"Builder",
"providing",
"a",
"Docbook",
"toolchain",
"for",
"HTML",
"output",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L550-L570 |
23,565 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | DocbookMan | def DocbookMan(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for Man page output.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_MAN', ['manpages','docbook.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
volnum = "1"
outfiles = []
srcfile = __ensure_suffix(str(s),'.xml')
if os.path.isfile(srcfile):
try:
import xml.dom.minidom
dom = xml.dom.minidom.parse(__ensure_suffix(str(s),'.xml'))
# Extract volume number, default is 1
for node in dom.getElementsByTagName('refmeta'):
for vol in node.getElementsByTagName('manvolnum'):
volnum = __get_xml_text(vol)
# Extract output filenames
for node in dom.getElementsByTagName('refnamediv'):
for ref in node.getElementsByTagName('refname'):
outfiles.append(__get_xml_text(ref)+'.'+volnum)
except:
# Use simple regex parsing
f = open(__ensure_suffix(str(s),'.xml'), 'r')
content = f.read()
f.close()
for m in re_manvolnum.finditer(content):
volnum = m.group(1)
for m in re_refname.finditer(content):
outfiles.append(m.group(1)+'.'+volnum)
if not outfiles:
# Use stem of the source file
spath = str(s)
if not spath.endswith('.xml'):
outfiles.append(spath+'.'+volnum)
else:
stem, ext = os.path.splitext(spath)
outfiles.append(stem+'.'+volnum)
else:
# We have to completely rely on the given target name
outfiles.append(t)
__builder.__call__(env, outfiles[0], s, **kw)
env.Depends(outfiles[0], kw['DOCBOOK_XSL'])
result.append(outfiles[0])
if len(outfiles) > 1:
env.Clean(outfiles[0], outfiles[1:])
return result | python | def DocbookMan(env, target, source=None, *args, **kw):
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_MAN', ['manpages','docbook.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
volnum = "1"
outfiles = []
srcfile = __ensure_suffix(str(s),'.xml')
if os.path.isfile(srcfile):
try:
import xml.dom.minidom
dom = xml.dom.minidom.parse(__ensure_suffix(str(s),'.xml'))
# Extract volume number, default is 1
for node in dom.getElementsByTagName('refmeta'):
for vol in node.getElementsByTagName('manvolnum'):
volnum = __get_xml_text(vol)
# Extract output filenames
for node in dom.getElementsByTagName('refnamediv'):
for ref in node.getElementsByTagName('refname'):
outfiles.append(__get_xml_text(ref)+'.'+volnum)
except:
# Use simple regex parsing
f = open(__ensure_suffix(str(s),'.xml'), 'r')
content = f.read()
f.close()
for m in re_manvolnum.finditer(content):
volnum = m.group(1)
for m in re_refname.finditer(content):
outfiles.append(m.group(1)+'.'+volnum)
if not outfiles:
# Use stem of the source file
spath = str(s)
if not spath.endswith('.xml'):
outfiles.append(spath+'.'+volnum)
else:
stem, ext = os.path.splitext(spath)
outfiles.append(stem+'.'+volnum)
else:
# We have to completely rely on the given target name
outfiles.append(t)
__builder.__call__(env, outfiles[0], s, **kw)
env.Depends(outfiles[0], kw['DOCBOOK_XSL'])
result.append(outfiles[0])
if len(outfiles) > 1:
env.Clean(outfiles[0], outfiles[1:])
return result | [
"def",
"DocbookMan",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
"# I... | A pseudo-Builder, providing a Docbook toolchain for Man page output. | [
"A",
"pseudo",
"-",
"Builder",
"providing",
"a",
"Docbook",
"toolchain",
"for",
"Man",
"page",
"output",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L666-L731 |
23,566 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | DocbookSlidesPdf | def DocbookSlidesPdf(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for PDF slides output.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_SLIDESPDF', ['slides','fo','plain.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
t, stem = __ensure_suffix_stem(t, '.pdf')
xsl = __builder.__call__(env, stem+'.fo', s, **kw)
env.Depends(xsl, kw['DOCBOOK_XSL'])
result.extend(xsl)
result.extend(__fop_builder.__call__(env, t, xsl, **kw))
return result | python | def DocbookSlidesPdf(env, target, source=None, *args, **kw):
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_SLIDESPDF', ['slides','fo','plain.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
t, stem = __ensure_suffix_stem(t, '.pdf')
xsl = __builder.__call__(env, stem+'.fo', s, **kw)
env.Depends(xsl, kw['DOCBOOK_XSL'])
result.extend(xsl)
result.extend(__fop_builder.__call__(env, t, xsl, **kw))
return result | [
"def",
"DocbookSlidesPdf",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
... | A pseudo-Builder, providing a Docbook toolchain for PDF slides output. | [
"A",
"pseudo",
"-",
"Builder",
"providing",
"a",
"Docbook",
"toolchain",
"for",
"PDF",
"slides",
"output",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L733-L755 |
23,567 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | DocbookSlidesHtml | def DocbookSlidesHtml(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, providing a Docbook toolchain for HTML slides output.
"""
# Init list of targets/sources
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target
target = ['index.html']
elif not SCons.Util.is_List(source):
source = [source]
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_SLIDESHTML', ['slides','html','plain.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Detect base dir
base_dir = kw.get('base_dir', '')
if base_dir:
__create_output_dir(base_dir)
# Create targets
result = []
r = __builder.__call__(env, __ensure_suffix(str(target[0]), '.html'), source[0], **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
# Add supporting files for cleanup
env.Clean(r, [os.path.join(base_dir, 'toc.html')] +
glob.glob(os.path.join(base_dir, 'foil*.html')))
return result | python | def DocbookSlidesHtml(env, target, source=None, *args, **kw):
# Init list of targets/sources
if not SCons.Util.is_List(target):
target = [target]
if not source:
source = target
target = ['index.html']
elif not SCons.Util.is_List(source):
source = [source]
# Init XSL stylesheet
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_SLIDESHTML', ['slides','html','plain.xsl'])
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Detect base dir
base_dir = kw.get('base_dir', '')
if base_dir:
__create_output_dir(base_dir)
# Create targets
result = []
r = __builder.__call__(env, __ensure_suffix(str(target[0]), '.html'), source[0], **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
# Add supporting files for cleanup
env.Clean(r, [os.path.join(base_dir, 'toc.html')] +
glob.glob(os.path.join(base_dir, 'foil*.html')))
return result | [
"def",
"DocbookSlidesHtml",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",
"(",
"target",
")",
":",
"target",
... | A pseudo-Builder, providing a Docbook toolchain for HTML slides output. | [
"A",
"pseudo",
"-",
"Builder",
"providing",
"a",
"Docbook",
"toolchain",
"for",
"HTML",
"slides",
"output",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L757-L790 |
23,568 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | DocbookXInclude | def DocbookXInclude(env, target, source, *args, **kw):
"""
A pseudo-Builder, for resolving XIncludes in a separate processing step.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Setup builder
__builder = __select_builder(__xinclude_lxml_builder,__xinclude_libxml2_builder,__xmllint_builder)
# Create targets
result = []
for t,s in zip(target,source):
result.extend(__builder.__call__(env, t, s, **kw))
return result | python | def DocbookXInclude(env, target, source, *args, **kw):
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Setup builder
__builder = __select_builder(__xinclude_lxml_builder,__xinclude_libxml2_builder,__xmllint_builder)
# Create targets
result = []
for t,s in zip(target,source):
result.extend(__builder.__call__(env, t, s, **kw))
return result | [
"def",
"DocbookXInclude",
"(",
"env",
",",
"target",
",",
"source",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
"# Setup builder... | A pseudo-Builder, for resolving XIncludes in a separate processing step. | [
"A",
"pseudo",
"-",
"Builder",
"for",
"resolving",
"XIncludes",
"in",
"a",
"separate",
"processing",
"step",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L792-L807 |
23,569 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | DocbookXslt | def DocbookXslt(env, target, source=None, *args, **kw):
"""
A pseudo-Builder, applying a simple XSL transformation to the input file.
"""
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
kw['DOCBOOK_XSL'] = kw.get('xsl', 'transform.xsl')
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
r = __builder.__call__(env, t, s, **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
return result | python | def DocbookXslt(env, target, source=None, *args, **kw):
# Init list of targets/sources
target, source = __extend_targets_sources(target, source)
# Init XSL stylesheet
kw['DOCBOOK_XSL'] = kw.get('xsl', 'transform.xsl')
# Setup builder
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
# Create targets
result = []
for t,s in zip(target,source):
r = __builder.__call__(env, t, s, **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
return result | [
"def",
"DocbookXslt",
"(",
"env",
",",
"target",
",",
"source",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Init list of targets/sources",
"target",
",",
"source",
"=",
"__extend_targets_sources",
"(",
"target",
",",
"source",
")",
"# ... | A pseudo-Builder, applying a simple XSL transformation to the input file. | [
"A",
"pseudo",
"-",
"Builder",
"applying",
"a",
"simple",
"XSL",
"transformation",
"to",
"the",
"input",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L809-L829 |
23,570 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py | generate | def generate(env):
"""Add Builders and construction variables for docbook to an Environment."""
env.SetDefault(
# Default names for customized XSL stylesheets
DOCBOOK_DEFAULT_XSL_EPUB = '',
DOCBOOK_DEFAULT_XSL_HTML = '',
DOCBOOK_DEFAULT_XSL_HTMLCHUNKED = '',
DOCBOOK_DEFAULT_XSL_HTMLHELP = '',
DOCBOOK_DEFAULT_XSL_PDF = '',
DOCBOOK_DEFAULT_XSL_MAN = '',
DOCBOOK_DEFAULT_XSL_SLIDESPDF = '',
DOCBOOK_DEFAULT_XSL_SLIDESHTML = '',
# Paths to the detected executables
DOCBOOK_XSLTPROC = '',
DOCBOOK_XMLLINT = '',
DOCBOOK_FOP = '',
# Additional flags for the text processors
DOCBOOK_XSLTPROCFLAGS = SCons.Util.CLVar(''),
DOCBOOK_XMLLINTFLAGS = SCons.Util.CLVar(''),
DOCBOOK_FOPFLAGS = SCons.Util.CLVar(''),
DOCBOOK_XSLTPROCPARAMS = SCons.Util.CLVar(''),
# Default command lines for the detected executables
DOCBOOK_XSLTPROCCOM = xsltproc_com['xsltproc'],
DOCBOOK_XMLLINTCOM = xmllint_com['xmllint'],
DOCBOOK_FOPCOM = fop_com['fop'],
# Screen output for the text processors
DOCBOOK_XSLTPROCCOMSTR = None,
DOCBOOK_XMLLINTCOMSTR = None,
DOCBOOK_FOPCOMSTR = None,
)
_detect(env)
env.AddMethod(DocbookEpub, "DocbookEpub")
env.AddMethod(DocbookHtml, "DocbookHtml")
env.AddMethod(DocbookHtmlChunked, "DocbookHtmlChunked")
env.AddMethod(DocbookHtmlhelp, "DocbookHtmlhelp")
env.AddMethod(DocbookPdf, "DocbookPdf")
env.AddMethod(DocbookMan, "DocbookMan")
env.AddMethod(DocbookSlidesPdf, "DocbookSlidesPdf")
env.AddMethod(DocbookSlidesHtml, "DocbookSlidesHtml")
env.AddMethod(DocbookXInclude, "DocbookXInclude")
env.AddMethod(DocbookXslt, "DocbookXslt") | python | def generate(env):
env.SetDefault(
# Default names for customized XSL stylesheets
DOCBOOK_DEFAULT_XSL_EPUB = '',
DOCBOOK_DEFAULT_XSL_HTML = '',
DOCBOOK_DEFAULT_XSL_HTMLCHUNKED = '',
DOCBOOK_DEFAULT_XSL_HTMLHELP = '',
DOCBOOK_DEFAULT_XSL_PDF = '',
DOCBOOK_DEFAULT_XSL_MAN = '',
DOCBOOK_DEFAULT_XSL_SLIDESPDF = '',
DOCBOOK_DEFAULT_XSL_SLIDESHTML = '',
# Paths to the detected executables
DOCBOOK_XSLTPROC = '',
DOCBOOK_XMLLINT = '',
DOCBOOK_FOP = '',
# Additional flags for the text processors
DOCBOOK_XSLTPROCFLAGS = SCons.Util.CLVar(''),
DOCBOOK_XMLLINTFLAGS = SCons.Util.CLVar(''),
DOCBOOK_FOPFLAGS = SCons.Util.CLVar(''),
DOCBOOK_XSLTPROCPARAMS = SCons.Util.CLVar(''),
# Default command lines for the detected executables
DOCBOOK_XSLTPROCCOM = xsltproc_com['xsltproc'],
DOCBOOK_XMLLINTCOM = xmllint_com['xmllint'],
DOCBOOK_FOPCOM = fop_com['fop'],
# Screen output for the text processors
DOCBOOK_XSLTPROCCOMSTR = None,
DOCBOOK_XMLLINTCOMSTR = None,
DOCBOOK_FOPCOMSTR = None,
)
_detect(env)
env.AddMethod(DocbookEpub, "DocbookEpub")
env.AddMethod(DocbookHtml, "DocbookHtml")
env.AddMethod(DocbookHtmlChunked, "DocbookHtmlChunked")
env.AddMethod(DocbookHtmlhelp, "DocbookHtmlhelp")
env.AddMethod(DocbookPdf, "DocbookPdf")
env.AddMethod(DocbookMan, "DocbookMan")
env.AddMethod(DocbookSlidesPdf, "DocbookSlidesPdf")
env.AddMethod(DocbookSlidesHtml, "DocbookSlidesHtml")
env.AddMethod(DocbookXInclude, "DocbookXInclude")
env.AddMethod(DocbookXslt, "DocbookXslt") | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
".",
"SetDefault",
"(",
"# Default names for customized XSL stylesheets",
"DOCBOOK_DEFAULT_XSL_EPUB",
"=",
"''",
",",
"DOCBOOK_DEFAULT_XSL_HTML",
"=",
"''",
",",
"DOCBOOK_DEFAULT_XSL_HTMLCHUNKED",
"=",
"''",
",",
"DOCBOOK_... | Add Builders and construction variables for docbook to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"docbook",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/docbook/__init__.py#L832-L879 |
23,571 | iotile/coretools | iotilecore/iotile/core/utilities/rcfile.py | RCFile.save | def save(self):
"""Update the configuration file on disk with the current contents of self.contents.
Previous contents are overwritten.
"""
try:
with open(self.path, "w") as f:
f.writelines(self.contents)
except IOError as e:
raise InternalError("Could not write RCFile contents", name=self.name, path=self.path, error_message=str(e)) | python | def save(self):
try:
with open(self.path, "w") as f:
f.writelines(self.contents)
except IOError as e:
raise InternalError("Could not write RCFile contents", name=self.name, path=self.path, error_message=str(e)) | [
"def",
"save",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"writelines",
"(",
"self",
".",
"contents",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"InternalError",... | Update the configuration file on disk with the current contents of self.contents.
Previous contents are overwritten. | [
"Update",
"the",
"configuration",
"file",
"on",
"disk",
"with",
"the",
"current",
"contents",
"of",
"self",
".",
"contents",
".",
"Previous",
"contents",
"are",
"overwritten",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/rcfile.py#L52-L61 |
23,572 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.probe_message | async def probe_message(self, _message, context):
"""Handle a probe message.
See :meth:`AbstractDeviceAdapter.probe`.
"""
client_id = context.user_data
await self.probe(client_id) | python | async def probe_message(self, _message, context):
client_id = context.user_data
await self.probe(client_id) | [
"async",
"def",
"probe_message",
"(",
"self",
",",
"_message",
",",
"context",
")",
":",
"client_id",
"=",
"context",
".",
"user_data",
"await",
"self",
".",
"probe",
"(",
"client_id",
")"
] | Handle a probe message.
See :meth:`AbstractDeviceAdapter.probe`. | [
"Handle",
"a",
"probe",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L111-L118 |
23,573 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.connect_message | async def connect_message(self, message, context):
"""Handle a connect message.
See :meth:`AbstractDeviceAdapter.connect`.
"""
conn_string = message.get('connection_string')
client_id = context.user_data
await self.connect(client_id, conn_string) | python | async def connect_message(self, message, context):
conn_string = message.get('connection_string')
client_id = context.user_data
await self.connect(client_id, conn_string) | [
"async",
"def",
"connect_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"client_id",
"=",
"context",
".",
"user_data",
"await",
"self",
".",
"connect",
"(",
"client... | Handle a connect message.
See :meth:`AbstractDeviceAdapter.connect`. | [
"Handle",
"a",
"connect",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L120-L128 |
23,574 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.disconnect_message | async def disconnect_message(self, message, context):
"""Handle a disconnect message.
See :meth:`AbstractDeviceAdapter.disconnect`.
"""
conn_string = message.get('connection_string')
client_id = context.user_data
await self.disconnect(client_id, conn_string) | python | async def disconnect_message(self, message, context):
conn_string = message.get('connection_string')
client_id = context.user_data
await self.disconnect(client_id, conn_string) | [
"async",
"def",
"disconnect_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"client_id",
"=",
"context",
".",
"user_data",
"await",
"self",
".",
"disconnect",
"(",
"... | Handle a disconnect message.
See :meth:`AbstractDeviceAdapter.disconnect`. | [
"Handle",
"a",
"disconnect",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L130-L139 |
23,575 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.open_interface_message | async def open_interface_message(self, message, context):
"""Handle an open_interface message.
See :meth:`AbstractDeviceAdapter.open_interface`.
"""
conn_string = message.get('connection_string')
interface = message.get('interface')
client_id = context.user_data
await self.open_interface(client_id, conn_string, interface) | python | async def open_interface_message(self, message, context):
conn_string = message.get('connection_string')
interface = message.get('interface')
client_id = context.user_data
await self.open_interface(client_id, conn_string, interface) | [
"async",
"def",
"open_interface_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"interface",
"=",
"message",
".",
"get",
"(",
"'interface'",
")",
"client_id",
"=",
"... | Handle an open_interface message.
See :meth:`AbstractDeviceAdapter.open_interface`. | [
"Handle",
"an",
"open_interface",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L141-L151 |
23,576 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.close_interface_message | async def close_interface_message(self, message, context):
"""Handle a close_interface message.
See :meth:`AbstractDeviceAdapter.close_interface`.
"""
conn_string = message.get('connection_string')
interface = message.get('interface')
client_id = context.user_data
await self.close_interface(client_id, conn_string, interface) | python | async def close_interface_message(self, message, context):
conn_string = message.get('connection_string')
interface = message.get('interface')
client_id = context.user_data
await self.close_interface(client_id, conn_string, interface) | [
"async",
"def",
"close_interface_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"interface",
"=",
"message",
".",
"get",
"(",
"'interface'",
")",
"client_id",
"=",
... | Handle a close_interface message.
See :meth:`AbstractDeviceAdapter.close_interface`. | [
"Handle",
"a",
"close_interface",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L153-L163 |
23,577 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.send_rpc_message | async def send_rpc_message(self, message, context):
"""Handle a send_rpc message.
See :meth:`AbstractDeviceAdapter.send_rpc`.
"""
conn_string = message.get('connection_string')
rpc_id = message.get('rpc_id')
address = message.get('address')
timeout = message.get('timeout')
payload = message.get('payload')
client_id = context.user_data
self._logger.debug("Calling RPC %d:0x%04X with payload %s on %s",
address, rpc_id, payload, conn_string)
response = bytes()
err = None
try:
response = await self.send_rpc(client_id, conn_string, address, rpc_id, payload, timeout=timeout)
except VALID_RPC_EXCEPTIONS as internal_err:
err = internal_err
except (DeviceAdapterError, DeviceServerError):
raise
except Exception as internal_err:
self._logger.warning("Unexpected exception calling RPC %d:0x%04x", address, rpc_id, exc_info=True)
raise ServerCommandError('send_rpc', str(internal_err)) from internal_err
status, response = pack_rpc_response(response, err)
return {
'status': status,
'payload': base64.b64encode(response)
} | python | async def send_rpc_message(self, message, context):
conn_string = message.get('connection_string')
rpc_id = message.get('rpc_id')
address = message.get('address')
timeout = message.get('timeout')
payload = message.get('payload')
client_id = context.user_data
self._logger.debug("Calling RPC %d:0x%04X with payload %s on %s",
address, rpc_id, payload, conn_string)
response = bytes()
err = None
try:
response = await self.send_rpc(client_id, conn_string, address, rpc_id, payload, timeout=timeout)
except VALID_RPC_EXCEPTIONS as internal_err:
err = internal_err
except (DeviceAdapterError, DeviceServerError):
raise
except Exception as internal_err:
self._logger.warning("Unexpected exception calling RPC %d:0x%04x", address, rpc_id, exc_info=True)
raise ServerCommandError('send_rpc', str(internal_err)) from internal_err
status, response = pack_rpc_response(response, err)
return {
'status': status,
'payload': base64.b64encode(response)
} | [
"async",
"def",
"send_rpc_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"rpc_id",
"=",
"message",
".",
"get",
"(",
"'rpc_id'",
")",
"address",
"=",
"message",
".... | Handle a send_rpc message.
See :meth:`AbstractDeviceAdapter.send_rpc`. | [
"Handle",
"a",
"send_rpc",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L165-L197 |
23,578 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.send_script_message | async def send_script_message(self, message, context):
"""Handle a send_script message.
See :meth:`AbstractDeviceAdapter.send_script`.
"""
script = message.get('script')
conn_string = message.get('connection_string')
client_id = context.user_data
if message.get('fragment_count') != 1:
raise DeviceServerError(client_id, conn_string, 'send_script', 'fragmented scripts are not yet supported')
await self.send_script(client_id, conn_string, script) | python | async def send_script_message(self, message, context):
script = message.get('script')
conn_string = message.get('connection_string')
client_id = context.user_data
if message.get('fragment_count') != 1:
raise DeviceServerError(client_id, conn_string, 'send_script', 'fragmented scripts are not yet supported')
await self.send_script(client_id, conn_string, script) | [
"async",
"def",
"send_script_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"script",
"=",
"message",
".",
"get",
"(",
"'script'",
")",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"client_id",
"=",
"context",... | Handle a send_script message.
See :meth:`AbstractDeviceAdapter.send_script`. | [
"Handle",
"a",
"send_script",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L199-L212 |
23,579 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.debug_command_message | async def debug_command_message(self, message, context):
"""Handle a debug message.
See :meth:`AbstractDeviceAdapter.debug`.
"""
conn_string = message.get('connection_string')
command = message.get('command')
args = message.get('args')
client_id = context.user_data
result = await self.debug(client_id, conn_string, command, args)
return result | python | async def debug_command_message(self, message, context):
conn_string = message.get('connection_string')
command = message.get('command')
args = message.get('args')
client_id = context.user_data
result = await self.debug(client_id, conn_string, command, args)
return result | [
"async",
"def",
"debug_command_message",
"(",
"self",
",",
"message",
",",
"context",
")",
":",
"conn_string",
"=",
"message",
".",
"get",
"(",
"'connection_string'",
")",
"command",
"=",
"message",
".",
"get",
"(",
"'command'",
")",
"args",
"=",
"message",
... | Handle a debug message.
See :meth:`AbstractDeviceAdapter.debug`. | [
"Handle",
"a",
"debug",
"message",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L214-L226 |
23,580 | iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/device_server.py | WebSocketDeviceServer.client_event_handler | async def client_event_handler(self, client_id, event_tuple, user_data):
"""Forward an event on behalf of a client.
This method is called by StandardDeviceServer when it has an event that
should be sent to a client.
Args:
client_id (str): The client that we should send this event to
event_tuple (tuple): The conn_string, event_name and event
object passed from the call to notify_event.
user_data (object): The user data passed in the call to
:meth:`setup_client`.
"""
#TODO: Support sending disconnection events
conn_string, event_name, event = event_tuple
if event_name == 'report':
report = event.serialize()
report['encoded_report'] = base64.b64encode(report['encoded_report'])
msg_payload = dict(connection_string=conn_string, serialized_report=report)
msg_name = OPERATIONS.NOTIFY_REPORT
elif event_name == 'trace':
encoded_payload = base64.b64encode(event)
msg_payload = dict(connection_string=conn_string, payload=encoded_payload)
msg_name = OPERATIONS.NOTIFY_TRACE
elif event_name == 'progress':
msg_payload = dict(connection_string=conn_string, operation=event.get('operation'),
done_count=event.get('finished'), total_count=event.get('total'))
msg_name = OPERATIONS.NOTIFY_PROGRESS
elif event_name == 'device_seen':
msg_payload = event
msg_name = OPERATIONS.NOTIFY_DEVICE_FOUND
elif event_name == 'broadcast':
report = event.serialize()
report['encoded_report'] = base64.b64encode(report['encoded_report'])
msg_payload = dict(connection_string=conn_string, serialized_report=report)
msg_name = OPERATIONS.NOTIFY_BROADCAST
else:
self._logger.debug("Not forwarding unknown event over websockets: %s", event_tuple)
return
try:
self._logger.debug("Sending event %s: %s", msg_name, msg_payload)
await self.server.send_event(user_data, msg_name, msg_payload)
except websockets.exceptions.ConnectionClosed:
self._logger.debug("Could not send notification because connection was closed for client %s", client_id) | python | async def client_event_handler(self, client_id, event_tuple, user_data):
#TODO: Support sending disconnection events
conn_string, event_name, event = event_tuple
if event_name == 'report':
report = event.serialize()
report['encoded_report'] = base64.b64encode(report['encoded_report'])
msg_payload = dict(connection_string=conn_string, serialized_report=report)
msg_name = OPERATIONS.NOTIFY_REPORT
elif event_name == 'trace':
encoded_payload = base64.b64encode(event)
msg_payload = dict(connection_string=conn_string, payload=encoded_payload)
msg_name = OPERATIONS.NOTIFY_TRACE
elif event_name == 'progress':
msg_payload = dict(connection_string=conn_string, operation=event.get('operation'),
done_count=event.get('finished'), total_count=event.get('total'))
msg_name = OPERATIONS.NOTIFY_PROGRESS
elif event_name == 'device_seen':
msg_payload = event
msg_name = OPERATIONS.NOTIFY_DEVICE_FOUND
elif event_name == 'broadcast':
report = event.serialize()
report['encoded_report'] = base64.b64encode(report['encoded_report'])
msg_payload = dict(connection_string=conn_string, serialized_report=report)
msg_name = OPERATIONS.NOTIFY_BROADCAST
else:
self._logger.debug("Not forwarding unknown event over websockets: %s", event_tuple)
return
try:
self._logger.debug("Sending event %s: %s", msg_name, msg_payload)
await self.server.send_event(user_data, msg_name, msg_payload)
except websockets.exceptions.ConnectionClosed:
self._logger.debug("Could not send notification because connection was closed for client %s", client_id) | [
"async",
"def",
"client_event_handler",
"(",
"self",
",",
"client_id",
",",
"event_tuple",
",",
"user_data",
")",
":",
"#TODO: Support sending disconnection events",
"conn_string",
",",
"event_name",
",",
"event",
"=",
"event_tuple",
"if",
"event_name",
"==",
"'report... | Forward an event on behalf of a client.
This method is called by StandardDeviceServer when it has an event that
should be sent to a client.
Args:
client_id (str): The client that we should send this event to
event_tuple (tuple): The conn_string, event_name and event
object passed from the call to notify_event.
user_data (object): The user data passed in the call to
:meth:`setup_client`. | [
"Forward",
"an",
"event",
"on",
"behalf",
"of",
"a",
"client",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/device_server.py#L228-L275 |
23,581 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sunf90.py | generate | def generate(env):
"""Add Builders and construction variables for sun f90 compiler to an
Environment."""
add_all_to_env(env)
fcomp = env.Detect(compilers) or 'f90'
env['FORTRAN'] = fcomp
env['F90'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['SHF90'] = '$F90'
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC')
env['SHF90FLAGS'] = SCons.Util.CLVar('$F90FLAGS -KPIC') | python | def generate(env):
add_all_to_env(env)
fcomp = env.Detect(compilers) or 'f90'
env['FORTRAN'] = fcomp
env['F90'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['SHF90'] = '$F90'
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC')
env['SHF90FLAGS'] = SCons.Util.CLVar('$F90FLAGS -KPIC') | [
"def",
"generate",
"(",
"env",
")",
":",
"add_all_to_env",
"(",
"env",
")",
"fcomp",
"=",
"env",
".",
"Detect",
"(",
"compilers",
")",
"or",
"'f90'",
"env",
"[",
"'FORTRAN'",
"]",
"=",
"fcomp",
"env",
"[",
"'F90'",
"]",
"=",
"fcomp",
"env",
"[",
"'... | Add Builders and construction variables for sun f90 compiler to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"sun",
"f90",
"compiler",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sunf90.py#L42-L55 |
23,582 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | Builder | def Builder(**kw):
"""A factory for builder objects."""
composite = None
if 'generator' in kw:
if 'action' in kw:
raise UserError("You must not specify both an action and a generator.")
kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {})
del kw['generator']
elif 'action' in kw:
source_ext_match = kw.get('source_ext_match', 1)
if 'source_ext_match' in kw:
del kw['source_ext_match']
if SCons.Util.is_Dict(kw['action']):
composite = DictCmdGenerator(kw['action'], source_ext_match)
kw['action'] = SCons.Action.CommandGeneratorAction(composite, {})
kw['src_suffix'] = composite.src_suffixes()
else:
kw['action'] = SCons.Action.Action(kw['action'])
if 'emitter' in kw:
emitter = kw['emitter']
if SCons.Util.is_String(emitter):
# This allows users to pass in an Environment
# variable reference (like "$FOO") as an emitter.
# We will look in that Environment variable for
# a callable to use as the actual emitter.
var = SCons.Util.get_environment_var(emitter)
if not var:
raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter)
kw['emitter'] = EmitterProxy(var)
elif SCons.Util.is_Dict(emitter):
kw['emitter'] = DictEmitter(emitter)
elif SCons.Util.is_List(emitter):
kw['emitter'] = ListEmitter(emitter)
result = BuilderBase(**kw)
if not composite is None:
result = CompositeBuilder(result, composite)
return result | python | def Builder(**kw):
composite = None
if 'generator' in kw:
if 'action' in kw:
raise UserError("You must not specify both an action and a generator.")
kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {})
del kw['generator']
elif 'action' in kw:
source_ext_match = kw.get('source_ext_match', 1)
if 'source_ext_match' in kw:
del kw['source_ext_match']
if SCons.Util.is_Dict(kw['action']):
composite = DictCmdGenerator(kw['action'], source_ext_match)
kw['action'] = SCons.Action.CommandGeneratorAction(composite, {})
kw['src_suffix'] = composite.src_suffixes()
else:
kw['action'] = SCons.Action.Action(kw['action'])
if 'emitter' in kw:
emitter = kw['emitter']
if SCons.Util.is_String(emitter):
# This allows users to pass in an Environment
# variable reference (like "$FOO") as an emitter.
# We will look in that Environment variable for
# a callable to use as the actual emitter.
var = SCons.Util.get_environment_var(emitter)
if not var:
raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter)
kw['emitter'] = EmitterProxy(var)
elif SCons.Util.is_Dict(emitter):
kw['emitter'] = DictEmitter(emitter)
elif SCons.Util.is_List(emitter):
kw['emitter'] = ListEmitter(emitter)
result = BuilderBase(**kw)
if not composite is None:
result = CompositeBuilder(result, composite)
return result | [
"def",
"Builder",
"(",
"*",
"*",
"kw",
")",
":",
"composite",
"=",
"None",
"if",
"'generator'",
"in",
"kw",
":",
"if",
"'action'",
"in",
"kw",
":",
"raise",
"UserError",
"(",
"\"You must not specify both an action and a generator.\"",
")",
"kw",
"[",
"'action'... | A factory for builder objects. | [
"A",
"factory",
"for",
"builder",
"objects",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L240-L280 |
23,583 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | _node_errors | def _node_errors(builder, env, tlist, slist):
"""Validate that the lists of target and source nodes are
legal for this builder and environment. Raise errors or
issue warnings as appropriate.
"""
# First, figure out if there are any errors in the way the targets
# were specified.
for t in tlist:
if t.side_effect:
raise UserError("Multiple ways to build the same target were specified for: %s" % t)
if t.has_explicit_builder():
# Check for errors when the environments are different
# No error if environments are the same Environment instance
if (not t.env is None and not t.env is env and
# Check OverrideEnvironment case - no error if wrapped Environments
# are the same instance, and overrides lists match
not (getattr(t.env, '__subject', 0) is getattr(env, '__subject', 1) and
getattr(t.env, 'overrides', 0) == getattr(env, 'overrides', 1) and
not builder.multi)):
action = t.builder.action
t_contents = t.builder.action.get_contents(tlist, slist, t.env)
contents = builder.action.get_contents(tlist, slist, env)
if t_contents == contents:
msg = "Two different environments were specified for target %s,\n\tbut they appear to have the same action: %s" % (t, action.genstring(tlist, slist, t.env))
SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg)
else:
try:
msg = "Two environments with different actions were specified for the same target: %s\n(action 1: %s)\n(action 2: %s)" % (t,t_contents.decode('utf-8'),contents.decode('utf-8'))
except UnicodeDecodeError as e:
msg = "Two environments with different actions were specified for the same target: %s"%t
raise UserError(msg)
if builder.multi:
if t.builder != builder:
msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t)
raise UserError(msg)
# TODO(batch): list constructed each time!
if t.get_executor().get_all_targets() != tlist:
msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist)))
raise UserError(msg)
elif t.sources != slist:
msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist)))
raise UserError(msg)
if builder.single_source:
if len(slist) > 1:
raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist)))) | python | def _node_errors(builder, env, tlist, slist):
# First, figure out if there are any errors in the way the targets
# were specified.
for t in tlist:
if t.side_effect:
raise UserError("Multiple ways to build the same target were specified for: %s" % t)
if t.has_explicit_builder():
# Check for errors when the environments are different
# No error if environments are the same Environment instance
if (not t.env is None and not t.env is env and
# Check OverrideEnvironment case - no error if wrapped Environments
# are the same instance, and overrides lists match
not (getattr(t.env, '__subject', 0) is getattr(env, '__subject', 1) and
getattr(t.env, 'overrides', 0) == getattr(env, 'overrides', 1) and
not builder.multi)):
action = t.builder.action
t_contents = t.builder.action.get_contents(tlist, slist, t.env)
contents = builder.action.get_contents(tlist, slist, env)
if t_contents == contents:
msg = "Two different environments were specified for target %s,\n\tbut they appear to have the same action: %s" % (t, action.genstring(tlist, slist, t.env))
SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg)
else:
try:
msg = "Two environments with different actions were specified for the same target: %s\n(action 1: %s)\n(action 2: %s)" % (t,t_contents.decode('utf-8'),contents.decode('utf-8'))
except UnicodeDecodeError as e:
msg = "Two environments with different actions were specified for the same target: %s"%t
raise UserError(msg)
if builder.multi:
if t.builder != builder:
msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t)
raise UserError(msg)
# TODO(batch): list constructed each time!
if t.get_executor().get_all_targets() != tlist:
msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist)))
raise UserError(msg)
elif t.sources != slist:
msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist)))
raise UserError(msg)
if builder.single_source:
if len(slist) > 1:
raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist)))) | [
"def",
"_node_errors",
"(",
"builder",
",",
"env",
",",
"tlist",
",",
"slist",
")",
":",
"# First, figure out if there are any errors in the way the targets",
"# were specified.",
"for",
"t",
"in",
"tlist",
":",
"if",
"t",
".",
"side_effect",
":",
"raise",
"UserErro... | Validate that the lists of target and source nodes are
legal for this builder and environment. Raise errors or
issue warnings as appropriate. | [
"Validate",
"that",
"the",
"lists",
"of",
"target",
"and",
"source",
"nodes",
"are",
"legal",
"for",
"this",
"builder",
"and",
"environment",
".",
"Raise",
"errors",
"or",
"issue",
"warnings",
"as",
"appropriate",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L282-L329 |
23,584 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | is_a_Builder | def is_a_Builder(obj):
""""Returns True if the specified obj is one of our Builder classes.
The test is complicated a bit by the fact that CompositeBuilder
is a proxy, not a subclass of BuilderBase.
"""
return (isinstance(obj, BuilderBase)
or isinstance(obj, CompositeBuilder)
or callable(obj)) | python | def is_a_Builder(obj):
"return (isinstance(obj, BuilderBase)
or isinstance(obj, CompositeBuilder)
or callable(obj)) | [
"def",
"is_a_Builder",
"(",
"obj",
")",
":",
"return",
"(",
"isinstance",
"(",
"obj",
",",
"BuilderBase",
")",
"or",
"isinstance",
"(",
"obj",
",",
"CompositeBuilder",
")",
"or",
"callable",
"(",
"obj",
")",
")"
] | Returns True if the specified obj is one of our Builder classes.
The test is complicated a bit by the fact that CompositeBuilder
is a proxy, not a subclass of BuilderBase. | [
"Returns",
"True",
"if",
"the",
"specified",
"obj",
"is",
"one",
"of",
"our",
"Builder",
"classes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L874-L882 |
23,585 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | BuilderBase.get_name | def get_name(self, env):
"""Attempts to get the name of the Builder.
Look at the BUILDERS variable of env, expecting it to be a
dictionary containing this Builder, and return the key of the
dictionary. If there's no key, then return a directly-configured
name (if there is one) or the name of the class (by default)."""
try:
index = list(env['BUILDERS'].values()).index(self)
return list(env['BUILDERS'].keys())[index]
except (AttributeError, KeyError, TypeError, ValueError):
try:
return self.name
except AttributeError:
return str(self.__class__) | python | def get_name(self, env):
try:
index = list(env['BUILDERS'].values()).index(self)
return list(env['BUILDERS'].keys())[index]
except (AttributeError, KeyError, TypeError, ValueError):
try:
return self.name
except AttributeError:
return str(self.__class__) | [
"def",
"get_name",
"(",
"self",
",",
"env",
")",
":",
"try",
":",
"index",
"=",
"list",
"(",
"env",
"[",
"'BUILDERS'",
"]",
".",
"values",
"(",
")",
")",
".",
"index",
"(",
"self",
")",
"return",
"list",
"(",
"env",
"[",
"'BUILDERS'",
"]",
".",
... | Attempts to get the name of the Builder.
Look at the BUILDERS variable of env, expecting it to be a
dictionary containing this Builder, and return the key of the
dictionary. If there's no key, then return a directly-configured
name (if there is one) or the name of the class (by default). | [
"Attempts",
"to",
"get",
"the",
"name",
"of",
"the",
"Builder",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L443-L458 |
23,586 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | BuilderBase._create_nodes | def _create_nodes(self, env, target = None, source = None):
"""Create and return lists of target and source nodes.
"""
src_suf = self.get_src_suffix(env)
target_factory = env.get_factory(self.target_factory)
source_factory = env.get_factory(self.source_factory)
source = self._adjustixes(source, None, src_suf)
slist = env.arg2nodes(source, source_factory)
pre = self.get_prefix(env, slist)
suf = self.get_suffix(env, slist)
if target is None:
try:
t_from_s = slist[0].target_from_source
except AttributeError:
raise UserError("Do not know how to create a target from source `%s'" % slist[0])
except IndexError:
tlist = []
else:
splitext = lambda S: self.splitext(S,env)
tlist = [ t_from_s(pre, suf, splitext) ]
else:
target = self._adjustixes(target, pre, suf, self.ensure_suffix)
tlist = env.arg2nodes(target, target_factory, target=target, source=source)
if self.emitter:
# The emitter is going to do str(node), but because we're
# being called *from* a builder invocation, the new targets
# don't yet have a builder set on them and will look like
# source files. Fool the emitter's str() calls by setting
# up a temporary builder on the new targets.
new_targets = []
for t in tlist:
if not t.is_derived():
t.builder_set(self)
new_targets.append(t)
orig_tlist = tlist[:]
orig_slist = slist[:]
target, source = self.emitter(target=tlist, source=slist, env=env)
# Now delete the temporary builders that we attached to any
# new targets, so that _node_errors() doesn't do weird stuff
# to them because it thinks they already have builders.
for t in new_targets:
if t.builder is self:
# Only delete the temporary builder if the emitter
# didn't change it on us.
t.builder_set(None)
# Have to call arg2nodes yet again, since it is legal for
# emitters to spit out strings as well as Node instances.
tlist = env.arg2nodes(target, target_factory,
target=orig_tlist, source=orig_slist)
slist = env.arg2nodes(source, source_factory,
target=orig_tlist, source=orig_slist)
return tlist, slist | python | def _create_nodes(self, env, target = None, source = None):
src_suf = self.get_src_suffix(env)
target_factory = env.get_factory(self.target_factory)
source_factory = env.get_factory(self.source_factory)
source = self._adjustixes(source, None, src_suf)
slist = env.arg2nodes(source, source_factory)
pre = self.get_prefix(env, slist)
suf = self.get_suffix(env, slist)
if target is None:
try:
t_from_s = slist[0].target_from_source
except AttributeError:
raise UserError("Do not know how to create a target from source `%s'" % slist[0])
except IndexError:
tlist = []
else:
splitext = lambda S: self.splitext(S,env)
tlist = [ t_from_s(pre, suf, splitext) ]
else:
target = self._adjustixes(target, pre, suf, self.ensure_suffix)
tlist = env.arg2nodes(target, target_factory, target=target, source=source)
if self.emitter:
# The emitter is going to do str(node), but because we're
# being called *from* a builder invocation, the new targets
# don't yet have a builder set on them and will look like
# source files. Fool the emitter's str() calls by setting
# up a temporary builder on the new targets.
new_targets = []
for t in tlist:
if not t.is_derived():
t.builder_set(self)
new_targets.append(t)
orig_tlist = tlist[:]
orig_slist = slist[:]
target, source = self.emitter(target=tlist, source=slist, env=env)
# Now delete the temporary builders that we attached to any
# new targets, so that _node_errors() doesn't do weird stuff
# to them because it thinks they already have builders.
for t in new_targets:
if t.builder is self:
# Only delete the temporary builder if the emitter
# didn't change it on us.
t.builder_set(None)
# Have to call arg2nodes yet again, since it is legal for
# emitters to spit out strings as well as Node instances.
tlist = env.arg2nodes(target, target_factory,
target=orig_tlist, source=orig_slist)
slist = env.arg2nodes(source, source_factory,
target=orig_tlist, source=orig_slist)
return tlist, slist | [
"def",
"_create_nodes",
"(",
"self",
",",
"env",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"src_suf",
"=",
"self",
".",
"get_src_suffix",
"(",
"env",
")",
"target_factory",
"=",
"env",
".",
"get_factory",
"(",
"self",
".",
"targ... | Create and return lists of target and source nodes. | [
"Create",
"and",
"return",
"lists",
"of",
"target",
"and",
"source",
"nodes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L485-L546 |
23,587 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | BuilderBase._get_sdict | def _get_sdict(self, env):
"""
Returns a dictionary mapping all of the source suffixes of all
src_builders of this Builder to the underlying Builder that
should be called first.
This dictionary is used for each target specified, so we save a
lot of extra computation by memoizing it for each construction
environment.
Note that this is re-computed each time, not cached, because there
might be changes to one of our source Builders (or one of their
source Builders, and so on, and so on...) that we can't "see."
The underlying methods we call cache their computed values,
though, so we hope repeatedly aggregating them into a dictionary
like this won't be too big a hit. We may need to look for a
better way to do this if performance data show this has turned
into a significant bottleneck.
"""
sdict = {}
for bld in self.get_src_builders(env):
for suf in bld.src_suffixes(env):
sdict[suf] = bld
return sdict | python | def _get_sdict(self, env):
sdict = {}
for bld in self.get_src_builders(env):
for suf in bld.src_suffixes(env):
sdict[suf] = bld
return sdict | [
"def",
"_get_sdict",
"(",
"self",
",",
"env",
")",
":",
"sdict",
"=",
"{",
"}",
"for",
"bld",
"in",
"self",
".",
"get_src_builders",
"(",
"env",
")",
":",
"for",
"suf",
"in",
"bld",
".",
"src_suffixes",
"(",
"env",
")",
":",
"sdict",
"[",
"suf",
... | Returns a dictionary mapping all of the source suffixes of all
src_builders of this Builder to the underlying Builder that
should be called first.
This dictionary is used for each target specified, so we save a
lot of extra computation by memoizing it for each construction
environment.
Note that this is re-computed each time, not cached, because there
might be changes to one of our source Builders (or one of their
source Builders, and so on, and so on...) that we can't "see."
The underlying methods we call cache their computed values,
though, so we hope repeatedly aggregating them into a dictionary
like this won't be too big a hit. We may need to look for a
better way to do this if performance data show this has turned
into a significant bottleneck. | [
"Returns",
"a",
"dictionary",
"mapping",
"all",
"of",
"the",
"source",
"suffixes",
"of",
"all",
"src_builders",
"of",
"this",
"Builder",
"to",
"the",
"underlying",
"Builder",
"that",
"should",
"be",
"called",
"first",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L703-L727 |
23,588 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | BuilderBase.get_src_builders | def get_src_builders(self, env):
"""
Returns the list of source Builders for this Builder.
This exists mainly to look up Builders referenced as
strings in the 'BUILDER' variable of the construction
environment and cache the result.
"""
memo_key = id(env)
try:
memo_dict = self._memo['get_src_builders']
except KeyError:
memo_dict = {}
self._memo['get_src_builders'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
builders = []
for bld in self.src_builder:
if SCons.Util.is_String(bld):
try:
bld = env['BUILDERS'][bld]
except KeyError:
continue
builders.append(bld)
memo_dict[memo_key] = builders
return builders | python | def get_src_builders(self, env):
memo_key = id(env)
try:
memo_dict = self._memo['get_src_builders']
except KeyError:
memo_dict = {}
self._memo['get_src_builders'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
builders = []
for bld in self.src_builder:
if SCons.Util.is_String(bld):
try:
bld = env['BUILDERS'][bld]
except KeyError:
continue
builders.append(bld)
memo_dict[memo_key] = builders
return builders | [
"def",
"get_src_builders",
"(",
"self",
",",
"env",
")",
":",
"memo_key",
"=",
"id",
"(",
"env",
")",
"try",
":",
"memo_dict",
"=",
"self",
".",
"_memo",
"[",
"'get_src_builders'",
"]",
"except",
"KeyError",
":",
"memo_dict",
"=",
"{",
"}",
"self",
"."... | Returns the list of source Builders for this Builder.
This exists mainly to look up Builders referenced as
strings in the 'BUILDER' variable of the construction
environment and cache the result. | [
"Returns",
"the",
"list",
"of",
"source",
"Builders",
"for",
"this",
"Builder",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L776-L806 |
23,589 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | BuilderBase.subst_src_suffixes | def subst_src_suffixes(self, env):
"""
The suffix list may contain construction variable expansions,
so we have to evaluate the individual strings. To avoid doing
this over and over, we memoize the results for each construction
environment.
"""
memo_key = id(env)
try:
memo_dict = self._memo['subst_src_suffixes']
except KeyError:
memo_dict = {}
self._memo['subst_src_suffixes'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
suffixes = [env.subst(x) for x in self.src_suffix]
memo_dict[memo_key] = suffixes
return suffixes | python | def subst_src_suffixes(self, env):
memo_key = id(env)
try:
memo_dict = self._memo['subst_src_suffixes']
except KeyError:
memo_dict = {}
self._memo['subst_src_suffixes'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
suffixes = [env.subst(x) for x in self.src_suffix]
memo_dict[memo_key] = suffixes
return suffixes | [
"def",
"subst_src_suffixes",
"(",
"self",
",",
"env",
")",
":",
"memo_key",
"=",
"id",
"(",
"env",
")",
"try",
":",
"memo_dict",
"=",
"self",
".",
"_memo",
"[",
"'subst_src_suffixes'",
"]",
"except",
"KeyError",
":",
"memo_dict",
"=",
"{",
"}",
"self",
... | The suffix list may contain construction variable expansions,
so we have to evaluate the individual strings. To avoid doing
this over and over, we memoize the results for each construction
environment. | [
"The",
"suffix",
"list",
"may",
"contain",
"construction",
"variable",
"expansions",
"so",
"we",
"have",
"to",
"evaluate",
"the",
"individual",
"strings",
".",
"To",
"avoid",
"doing",
"this",
"over",
"and",
"over",
"we",
"memoize",
"the",
"results",
"for",
"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L812-L832 |
23,590 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | BuilderBase.src_suffixes | def src_suffixes(self, env):
"""
Returns the list of source suffixes for all src_builders of this
Builder.
This is essentially a recursive descent of the src_builder "tree."
(This value isn't cached because there may be changes in a
src_builder many levels deep that we can't see.)
"""
sdict = {}
suffixes = self.subst_src_suffixes(env)
for s in suffixes:
sdict[s] = 1
for builder in self.get_src_builders(env):
for s in builder.src_suffixes(env):
if s not in sdict:
sdict[s] = 1
suffixes.append(s)
return suffixes | python | def src_suffixes(self, env):
sdict = {}
suffixes = self.subst_src_suffixes(env)
for s in suffixes:
sdict[s] = 1
for builder in self.get_src_builders(env):
for s in builder.src_suffixes(env):
if s not in sdict:
sdict[s] = 1
suffixes.append(s)
return suffixes | [
"def",
"src_suffixes",
"(",
"self",
",",
"env",
")",
":",
"sdict",
"=",
"{",
"}",
"suffixes",
"=",
"self",
".",
"subst_src_suffixes",
"(",
"env",
")",
"for",
"s",
"in",
"suffixes",
":",
"sdict",
"[",
"s",
"]",
"=",
"1",
"for",
"builder",
"in",
"sel... | Returns the list of source suffixes for all src_builders of this
Builder.
This is essentially a recursive descent of the src_builder "tree."
(This value isn't cached because there may be changes in a
src_builder many levels deep that we can't see.) | [
"Returns",
"the",
"list",
"of",
"source",
"suffixes",
"for",
"all",
"src_builders",
"of",
"this",
"Builder",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L834-L852 |
23,591 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/aixlink.py | generate | def generate(env):
"""
Add Builders and construction variables for Visual Age linker to
an Environment.
"""
link.generate(env)
env['SMARTLINKFLAGS'] = smart_linkflags
env['LINKFLAGS'] = SCons.Util.CLVar('$SMARTLINKFLAGS')
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -qmkshrobj -qsuppress=1501-218')
env['SHLIBSUFFIX'] = '.a' | python | def generate(env):
link.generate(env)
env['SMARTLINKFLAGS'] = smart_linkflags
env['LINKFLAGS'] = SCons.Util.CLVar('$SMARTLINKFLAGS')
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -qmkshrobj -qsuppress=1501-218')
env['SHLIBSUFFIX'] = '.a' | [
"def",
"generate",
"(",
"env",
")",
":",
"link",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'SMARTLINKFLAGS'",
"]",
"=",
"smart_linkflags",
"env",
"[",
"'LINKFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'$SMARTLINKFLAGS'",
")",
"env",... | Add Builders and construction variables for Visual Age linker to
an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Visual",
"Age",
"linker",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/aixlink.py#L55-L65 |
23,592 | iotile/coretools | iotilecore/iotile/core/hw/update/records/reflash_tile.py | _parse_target | def _parse_target(target):
"""Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (bytes): The binary targeting data blob.
Returns:
dict: The parsed targeting data
"""
if len(target) != 8:
raise ArgumentError("Invalid targeting data length", expected=8, length=len(target))
slot, match_op = struct.unpack("<B6xB", target)
if match_op == _MATCH_CONTROLLER:
return {'controller': True, 'slot': 0}
elif match_op == _MATCH_SLOT:
return {'controller': False, 'slot': slot}
raise ArgumentError("Unsupported complex targeting specified", match_op=match_op) | python | def _parse_target(target):
if len(target) != 8:
raise ArgumentError("Invalid targeting data length", expected=8, length=len(target))
slot, match_op = struct.unpack("<B6xB", target)
if match_op == _MATCH_CONTROLLER:
return {'controller': True, 'slot': 0}
elif match_op == _MATCH_SLOT:
return {'controller': False, 'slot': slot}
raise ArgumentError("Unsupported complex targeting specified", match_op=match_op) | [
"def",
"_parse_target",
"(",
"target",
")",
":",
"if",
"len",
"(",
"target",
")",
"!=",
"8",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid targeting data length\"",
",",
"expected",
"=",
"8",
",",
"length",
"=",
"len",
"(",
"target",
")",
")",
"slot",
"... | Parse a binary targeting information structure.
This function only supports extracting the slot number or controller from
the target and will raise an ArgumentError if more complicated targeting
is desired.
Args:
target (bytes): The binary targeting data blob.
Returns:
dict: The parsed targeting data | [
"Parse",
"a",
"binary",
"targeting",
"information",
"structure",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/records/reflash_tile.py#L165-L188 |
23,593 | iotile/coretools | iotileemulate/iotile/emulate/internal/rpc_queue.py | RPCQueue.put_task | def put_task(self, func, args, response):
"""Place a task onto the RPC queue.
This temporary functionality will go away but it lets you run a
task synchronously with RPC dispatch by placing it onto the
RCP queue.
Args:
func (callable): The function to execute
args (iterable): The function arguments
response (GenericResponse): The response object to signal the
result on.
"""
self._rpc_queue.put_nowait((func, args, response)) | python | def put_task(self, func, args, response):
self._rpc_queue.put_nowait((func, args, response)) | [
"def",
"put_task",
"(",
"self",
",",
"func",
",",
"args",
",",
"response",
")",
":",
"self",
".",
"_rpc_queue",
".",
"put_nowait",
"(",
"(",
"func",
",",
"args",
",",
"response",
")",
")"
] | Place a task onto the RPC queue.
This temporary functionality will go away but it lets you run a
task synchronously with RPC dispatch by placing it onto the
RCP queue.
Args:
func (callable): The function to execute
args (iterable): The function arguments
response (GenericResponse): The response object to signal the
result on. | [
"Place",
"a",
"task",
"onto",
"the",
"RPC",
"queue",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/rpc_queue.py#L44-L58 |
23,594 | iotile/coretools | iotileemulate/iotile/emulate/internal/rpc_queue.py | RPCQueue.put_rpc | def put_rpc(self, address, rpc_id, arg_payload, response):
"""Place an RPC onto the RPC queue.
The rpc will be dispatched asynchronously by the background dispatch
task. This method must be called from the event loop. This method
does not block.
Args:
address (int): The address of the tile with the RPC
rpc_id (int): The id of the rpc you want to call
arg_payload (bytes): The RPC payload
respones (GenericResponse): The object to use to signal the result.
"""
self._rpc_queue.put_nowait((address, rpc_id, arg_payload, response)) | python | def put_rpc(self, address, rpc_id, arg_payload, response):
self._rpc_queue.put_nowait((address, rpc_id, arg_payload, response)) | [
"def",
"put_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"arg_payload",
",",
"response",
")",
":",
"self",
".",
"_rpc_queue",
".",
"put_nowait",
"(",
"(",
"address",
",",
"rpc_id",
",",
"arg_payload",
",",
"response",
")",
")"
] | Place an RPC onto the RPC queue.
The rpc will be dispatched asynchronously by the background dispatch
task. This method must be called from the event loop. This method
does not block.
Args:
address (int): The address of the tile with the RPC
rpc_id (int): The id of the rpc you want to call
arg_payload (bytes): The RPC payload
respones (GenericResponse): The object to use to signal the result. | [
"Place",
"an",
"RPC",
"onto",
"the",
"RPC",
"queue",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/rpc_queue.py#L60-L74 |
23,595 | iotile/coretools | iotileemulate/iotile/emulate/internal/rpc_queue.py | RPCQueue.stop | async def stop(self):
"""Stop the rpc queue from inside the event loop."""
if self._rpc_task is not None:
self._rpc_task.cancel()
try:
await self._rpc_task
except asyncio.CancelledError:
pass
self._rpc_task = None | python | async def stop(self):
if self._rpc_task is not None:
self._rpc_task.cancel()
try:
await self._rpc_task
except asyncio.CancelledError:
pass
self._rpc_task = None | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_rpc_task",
"is",
"not",
"None",
":",
"self",
".",
"_rpc_task",
".",
"cancel",
"(",
")",
"try",
":",
"await",
"self",
".",
"_rpc_task",
"except",
"asyncio",
".",
"CancelledError",
":",
... | Stop the rpc queue from inside the event loop. | [
"Stop",
"the",
"rpc",
"queue",
"from",
"inside",
"the",
"event",
"loop",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/rpc_queue.py#L152-L163 |
23,596 | iotile/coretools | iotilecore/iotile/core/hw/debug/sparse_memory.py | SparseMemory.add_segment | def add_segment(self, address, data, overwrite=False):
"""Add a contiguous segment of data to this memory map
If the segment overlaps with a segment already added , an
ArgumentError is raised unless the overwrite flag is True.
Params:
address (int): The starting address for this segment
data (bytearray): The data to add
overwrite (bool): Overwrite data if this segment overlaps
with one previously added.
"""
seg_type = self._classify_segment(address, len(data))
if not isinstance(seg_type, DisjointSegment):
raise ArgumentError("Unsupported segment type")
segment = MemorySegment(address, address+len(data)-1, len(data), bytearray(data))
self._segments.append(segment) | python | def add_segment(self, address, data, overwrite=False):
seg_type = self._classify_segment(address, len(data))
if not isinstance(seg_type, DisjointSegment):
raise ArgumentError("Unsupported segment type")
segment = MemorySegment(address, address+len(data)-1, len(data), bytearray(data))
self._segments.append(segment) | [
"def",
"add_segment",
"(",
"self",
",",
"address",
",",
"data",
",",
"overwrite",
"=",
"False",
")",
":",
"seg_type",
"=",
"self",
".",
"_classify_segment",
"(",
"address",
",",
"len",
"(",
"data",
")",
")",
"if",
"not",
"isinstance",
"(",
"seg_type",
... | Add a contiguous segment of data to this memory map
If the segment overlaps with a segment already added , an
ArgumentError is raised unless the overwrite flag is True.
Params:
address (int): The starting address for this segment
data (bytearray): The data to add
overwrite (bool): Overwrite data if this segment overlaps
with one previously added. | [
"Add",
"a",
"contiguous",
"segment",
"of",
"data",
"to",
"this",
"memory",
"map"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/debug/sparse_memory.py#L24-L42 |
23,597 | iotile/coretools | iotilecore/iotile/core/hw/debug/sparse_memory.py | SparseMemory._create_slice | def _create_slice(self, key):
"""Create a slice in a memory segment corresponding to a key."""
if isinstance(key, slice):
step = key.step
if step is None:
step = 1
if step != 1:
raise ArgumentError("You cannot slice with a step that is not equal to 1", step=key.step)
start_address = key.start
end_address = key.stop - 1
start_i, start_seg = self._find_address(start_address)
end_i, _end_seg = self._find_address(end_address)
if start_seg is None or start_i != end_i:
raise ArgumentError("Slice would span invalid data in memory",
start_address=start_address, end_address=end_address)
block_offset = start_address - start_seg.start_address
block_length = end_address - start_address + 1
return start_seg, block_offset, block_offset + block_length
elif isinstance(key, int):
start_i, start_seg = self._find_address(key)
if start_seg is None:
raise ArgumentError("Requested invalid address", address=key)
return start_seg, key - start_seg.start_address, None
else:
raise ArgumentError("Unknown type of address key", address=key) | python | def _create_slice(self, key):
if isinstance(key, slice):
step = key.step
if step is None:
step = 1
if step != 1:
raise ArgumentError("You cannot slice with a step that is not equal to 1", step=key.step)
start_address = key.start
end_address = key.stop - 1
start_i, start_seg = self._find_address(start_address)
end_i, _end_seg = self._find_address(end_address)
if start_seg is None or start_i != end_i:
raise ArgumentError("Slice would span invalid data in memory",
start_address=start_address, end_address=end_address)
block_offset = start_address - start_seg.start_address
block_length = end_address - start_address + 1
return start_seg, block_offset, block_offset + block_length
elif isinstance(key, int):
start_i, start_seg = self._find_address(key)
if start_seg is None:
raise ArgumentError("Requested invalid address", address=key)
return start_seg, key - start_seg.start_address, None
else:
raise ArgumentError("Unknown type of address key", address=key) | [
"def",
"_create_slice",
"(",
"self",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"step",
"=",
"key",
".",
"step",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"1",
"if",
"step",
"!=",
"1",
":",
"raise",
"Argumen... | Create a slice in a memory segment corresponding to a key. | [
"Create",
"a",
"slice",
"in",
"a",
"memory",
"segment",
"corresponding",
"to",
"a",
"key",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/debug/sparse_memory.py#L44-L76 |
23,598 | iotile/coretools | iotilecore/iotile/core/hw/debug/sparse_memory.py | SparseMemory._classify_segment | def _classify_segment(self, address, length):
"""Determine how a new data segment fits into our existing world
Params:
address (int): The address we wish to classify
length (int): The length of the segment
Returns:
int: One of SparseMemoryMap.prepended
"""
end_address = address + length - 1
_, start_seg = self._find_address(address)
_, end_seg = self._find_address(end_address)
if start_seg is not None or end_seg is not None:
raise ArgumentError("Overlapping segments are not yet supported", address=address, length=length)
return DisjointSegment() | python | def _classify_segment(self, address, length):
end_address = address + length - 1
_, start_seg = self._find_address(address)
_, end_seg = self._find_address(end_address)
if start_seg is not None or end_seg is not None:
raise ArgumentError("Overlapping segments are not yet supported", address=address, length=length)
return DisjointSegment() | [
"def",
"_classify_segment",
"(",
"self",
",",
"address",
",",
"length",
")",
":",
"end_address",
"=",
"address",
"+",
"length",
"-",
"1",
"_",
",",
"start_seg",
"=",
"self",
".",
"_find_address",
"(",
"address",
")",
"_",
",",
"end_seg",
"=",
"self",
"... | Determine how a new data segment fits into our existing world
Params:
address (int): The address we wish to classify
length (int): The length of the segment
Returns:
int: One of SparseMemoryMap.prepended | [
"Determine",
"how",
"a",
"new",
"data",
"segment",
"fits",
"into",
"our",
"existing",
"world"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/debug/sparse_memory.py#L105-L124 |
23,599 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifort.py | generate | def generate(env):
"""Add Builders and construction variables for ifort to an Environment."""
# ifort supports Fortran 90 and Fortran 95
# Additionally, ifort recognizes more file extensions.
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES'].append('.i')
if 'F90FILESUFFIXES' not in env:
env['F90FILESUFFIXES'] = ['.i90']
else:
env['F90FILESUFFIXES'].append('.i90')
add_all_to_env(env)
fc = 'ifort'
for dialect in ['F77', 'F90', 'FORTRAN', 'F95']:
env['%s' % dialect] = fc
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] == 'posix':
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
if env['PLATFORM'] == 'win32':
# On Windows, the ifort compiler specifies the object on the
# command line with -object:, not -o. Massage the necessary
# command-line construction variables.
for dialect in ['F77', 'F90', 'FORTRAN', 'F95']:
for var in ['%sCOM' % dialect, '%sPPCOM' % dialect,
'SH%sCOM' % dialect, 'SH%sPPCOM' % dialect]:
env[var] = env[var].replace('-o $TARGET', '-object:$TARGET')
env['FORTRANMODDIRPREFIX'] = "/module:"
else:
env['FORTRANMODDIRPREFIX'] = "-module " | python | def generate(env):
# ifort supports Fortran 90 and Fortran 95
# Additionally, ifort recognizes more file extensions.
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES'].append('.i')
if 'F90FILESUFFIXES' not in env:
env['F90FILESUFFIXES'] = ['.i90']
else:
env['F90FILESUFFIXES'].append('.i90')
add_all_to_env(env)
fc = 'ifort'
for dialect in ['F77', 'F90', 'FORTRAN', 'F95']:
env['%s' % dialect] = fc
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] == 'posix':
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
if env['PLATFORM'] == 'win32':
# On Windows, the ifort compiler specifies the object on the
# command line with -object:, not -o. Massage the necessary
# command-line construction variables.
for dialect in ['F77', 'F90', 'FORTRAN', 'F95']:
for var in ['%sCOM' % dialect, '%sPPCOM' % dialect,
'SH%sCOM' % dialect, 'SH%sPPCOM' % dialect]:
env[var] = env[var].replace('-o $TARGET', '-object:$TARGET')
env['FORTRANMODDIRPREFIX'] = "/module:"
else:
env['FORTRANMODDIRPREFIX'] = "-module " | [
"def",
"generate",
"(",
"env",
")",
":",
"# ifort supports Fortran 90 and Fortran 95",
"# Additionally, ifort recognizes more file extensions.",
"fscan",
"=",
"FortranScan",
"(",
"\"FORTRANPATH\"",
")",
"SCons",
".",
"Tool",
".",
"SourceFileScanner",
".",
"add_scanner",
"("... | Add Builders and construction variables for ifort to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"ifort",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifort.py#L41-L79 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.