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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.clear_components | def clear_components(self):
"""Clear all of the registered components
"""
ComponentRegistry._component_overlays = {}
for key in self.list_components():
self.remove_component(key) | python | def clear_components(self):
"""Clear all of the registered components
"""
ComponentRegistry._component_overlays = {}
for key in self.list_components():
self.remove_component(key) | [
"def",
"clear_components",
"(",
"self",
")",
":",
"ComponentRegistry",
".",
"_component_overlays",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"list_components",
"(",
")",
":",
"self",
".",
"remove_component",
"(",
"key",
")"
] | Clear all of the registered components | [
"Clear",
"all",
"of",
"the",
"registered",
"components"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L473-L480 | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.list_components | def list_components(self):
"""List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list of component names.
Any of these names can be passed to get_component as is to get the
corresponding IOTile object.
"""
overlays = list(self._component_overlays)
items = self.kvstore.get_all()
return overlays + [x[0] for x in items if not x[0].startswith('config:')] | python | def list_components(self):
"""List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list of component names.
Any of these names can be passed to get_component as is to get the
corresponding IOTile object.
"""
overlays = list(self._component_overlays)
items = self.kvstore.get_all()
return overlays + [x[0] for x in items if not x[0].startswith('config:')] | [
"def",
"list_components",
"(",
"self",
")",
":",
"overlays",
"=",
"list",
"(",
"self",
".",
"_component_overlays",
")",
"items",
"=",
"self",
".",
"kvstore",
".",
"get_all",
"(",
")",
"return",
"overlays",
"+",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"i... | List all of the registered component names.
This list will include all of the permanently stored components as
well as any temporary components that were added with a temporary=True
flag in this session.
Returns:
list of str: The list of component names.
Any of these names can be passed to get_component as is to get the
corresponding IOTile object. | [
"List",
"all",
"of",
"the",
"registered",
"component",
"names",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L488-L505 | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.iter_components | def iter_components(self):
"""Iterate over all defined components yielding IOTile objects."""
names = self.list_components()
for name in names:
yield self.get_component(name) | python | def iter_components(self):
"""Iterate over all defined components yielding IOTile objects."""
names = self.list_components()
for name in names:
yield self.get_component(name) | [
"def",
"iter_components",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"list_components",
"(",
")",
"for",
"name",
"in",
"names",
":",
"yield",
"self",
".",
"get_component",
"(",
"name",
")"
] | Iterate over all defined components yielding IOTile objects. | [
"Iterate",
"over",
"all",
"defined",
"components",
"yielding",
"IOTile",
"objects",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L507-L513 | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.list_config | def list_config(self):
"""List all of the configuration variables
"""
items = self.kvstore.get_all()
return ["{0}={1}".format(x[0][len('config:'):], x[1])
for x in items if x[0].startswith('config:')] | python | def list_config(self):
"""List all of the configuration variables
"""
items = self.kvstore.get_all()
return ["{0}={1}".format(x[0][len('config:'):], x[1])
for x in items if x[0].startswith('config:')] | [
"def",
"list_config",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"kvstore",
".",
"get_all",
"(",
")",
"return",
"[",
"\"{0}={1}\"",
".",
"format",
"(",
"x",
"[",
"0",
"]",
"[",
"len",
"(",
"'config:'",
")",
":",
"]",
",",
"x",
"[",
"1",
... | List all of the configuration variables | [
"List",
"all",
"of",
"the",
"configuration",
"variables"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L515-L520 | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.set_config | def set_config(self, key, value):
"""Set a persistent config key to a value, stored in the registry
Args:
key (string): The key name
value (string): The key value
"""
keyname = "config:" + key
self.kvstore.set(keyname, value) | python | def set_config(self, key, value):
"""Set a persistent config key to a value, stored in the registry
Args:
key (string): The key name
value (string): The key value
"""
keyname = "config:" + key
self.kvstore.set(keyname, value) | [
"def",
"set_config",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"keyname",
"=",
"\"config:\"",
"+",
"key",
"self",
".",
"kvstore",
".",
"set",
"(",
"keyname",
",",
"value",
")"
] | Set a persistent config key to a value, stored in the registry
Args:
key (string): The key name
value (string): The key value | [
"Set",
"a",
"persistent",
"config",
"key",
"to",
"a",
"value",
"stored",
"in",
"the",
"registry"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L522-L532 | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | ComponentRegistry.get_config | def get_config(self, key, default=MISSING):
"""Get the value of a persistent config key from the registry
If no default is specified and the key is not found ArgumentError is raised.
Args:
key (string): The key name to fetch
default (string): an optional value to be returned if key cannot be found
Returns:
string: the key's value
"""
keyname = "config:" + key
try:
return self.kvstore.get(keyname)
except KeyError:
if default is MISSING:
raise ArgumentError("No config value found for key", key=key)
return default | python | def get_config(self, key, default=MISSING):
"""Get the value of a persistent config key from the registry
If no default is specified and the key is not found ArgumentError is raised.
Args:
key (string): The key name to fetch
default (string): an optional value to be returned if key cannot be found
Returns:
string: the key's value
"""
keyname = "config:" + key
try:
return self.kvstore.get(keyname)
except KeyError:
if default is MISSING:
raise ArgumentError("No config value found for key", key=key)
return default | [
"def",
"get_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"MISSING",
")",
":",
"keyname",
"=",
"\"config:\"",
"+",
"key",
"try",
":",
"return",
"self",
".",
"kvstore",
".",
"get",
"(",
"keyname",
")",
"except",
"KeyError",
":",
"if",
"default"... | Get the value of a persistent config key from the registry
If no default is specified and the key is not found ArgumentError is raised.
Args:
key (string): The key name to fetch
default (string): an optional value to be returned if key cannot be found
Returns:
string: the key's value | [
"Get",
"the",
"value",
"of",
"a",
"persistent",
"config",
"key",
"from",
"the",
"registry"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L534-L555 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | execute_action_list | def execute_action_list(obj, target, kw):
"""Actually execute the action list."""
env = obj.get_build_env()
kw = obj.get_kw(kw)
status = 0
for act in obj.get_action_list():
args = ([], [], env)
status = act(*args, **kw)
if isinstance(status, SCons.Errors.BuildError):
status.executor = obj
raise status
elif status:
msg = "Error %s" % status
raise SCons.Errors.BuildError(
errstr=msg,
node=obj.batches[0].targets,
executor=obj,
action=act)
return status | python | def execute_action_list(obj, target, kw):
"""Actually execute the action list."""
env = obj.get_build_env()
kw = obj.get_kw(kw)
status = 0
for act in obj.get_action_list():
args = ([], [], env)
status = act(*args, **kw)
if isinstance(status, SCons.Errors.BuildError):
status.executor = obj
raise status
elif status:
msg = "Error %s" % status
raise SCons.Errors.BuildError(
errstr=msg,
node=obj.batches[0].targets,
executor=obj,
action=act)
return status | [
"def",
"execute_action_list",
"(",
"obj",
",",
"target",
",",
"kw",
")",
":",
"env",
"=",
"obj",
".",
"get_build_env",
"(",
")",
"kw",
"=",
"obj",
".",
"get_kw",
"(",
"kw",
")",
"status",
"=",
"0",
"for",
"act",
"in",
"obj",
".",
"get_action_list",
... | Actually execute the action list. | [
"Actually",
"execute",
"the",
"action",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L119-L137 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_all_targets | def get_all_targets(self):
"""Returns all targets for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.targets)
return result | python | def get_all_targets(self):
"""Returns all targets for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.targets)
return result | [
"def",
"get_all_targets",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"batch",
"in",
"self",
".",
"batches",
":",
"result",
".",
"extend",
"(",
"batch",
".",
"targets",
")",
"return",
"result"
] | Returns all targets for all batches of this Executor. | [
"Returns",
"all",
"targets",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L295-L300 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_all_sources | def get_all_sources(self):
"""Returns all sources for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.sources)
return result | python | def get_all_sources(self):
"""Returns all sources for all batches of this Executor."""
result = []
for batch in self.batches:
result.extend(batch.sources)
return result | [
"def",
"get_all_sources",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"batch",
"in",
"self",
".",
"batches",
":",
"result",
".",
"extend",
"(",
"batch",
".",
"sources",
")",
"return",
"result"
] | Returns all sources for all batches of this Executor. | [
"Returns",
"all",
"sources",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L302-L307 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_action_side_effects | def get_action_side_effects(self):
"""Returns all side effects for all batches of this
Executor used by the underlying Action.
"""
result = SCons.Util.UniqueList([])
for target in self.get_action_targets():
result.extend(target.side_effects)
return result | python | def get_action_side_effects(self):
"""Returns all side effects for all batches of this
Executor used by the underlying Action.
"""
result = SCons.Util.UniqueList([])
for target in self.get_action_targets():
result.extend(target.side_effects)
return result | [
"def",
"get_action_side_effects",
"(",
"self",
")",
":",
"result",
"=",
"SCons",
".",
"Util",
".",
"UniqueList",
"(",
"[",
"]",
")",
"for",
"target",
"in",
"self",
".",
"get_action_targets",
"(",
")",
":",
"result",
".",
"extend",
"(",
"target",
".",
"... | Returns all side effects for all batches of this
Executor used by the underlying Action. | [
"Returns",
"all",
"side",
"effects",
"for",
"all",
"batches",
"of",
"this",
"Executor",
"used",
"by",
"the",
"underlying",
"Action",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L335-L343 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_build_env | def get_build_env(self):
"""Fetch or create the appropriate build Environment
for this Executor.
"""
try:
return self._memo['get_build_env']
except KeyError:
pass
# Create the build environment instance with appropriate
# overrides. These get evaluated against the current
# environment's construction variables so that users can
# add to existing values by referencing the variable in
# the expansion.
overrides = {}
for odict in self.overridelist:
overrides.update(odict)
import SCons.Defaults
env = self.env or SCons.Defaults.DefaultEnvironment()
build_env = env.Override(overrides)
self._memo['get_build_env'] = build_env
return build_env | python | def get_build_env(self):
"""Fetch or create the appropriate build Environment
for this Executor.
"""
try:
return self._memo['get_build_env']
except KeyError:
pass
# Create the build environment instance with appropriate
# overrides. These get evaluated against the current
# environment's construction variables so that users can
# add to existing values by referencing the variable in
# the expansion.
overrides = {}
for odict in self.overridelist:
overrides.update(odict)
import SCons.Defaults
env = self.env or SCons.Defaults.DefaultEnvironment()
build_env = env.Override(overrides)
self._memo['get_build_env'] = build_env
return build_env | [
"def",
"get_build_env",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'get_build_env'",
"]",
"except",
"KeyError",
":",
"pass",
"overrides",
"=",
"{",
"}",
"for",
"odict",
"in",
"self",
".",
"overridelist",
":",
"overrides",
".... | Fetch or create the appropriate build Environment
for this Executor. | [
"Fetch",
"or",
"create",
"the",
"appropriate",
"build",
"Environment",
"for",
"this",
"Executor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L346-L370 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_build_scanner_path | def get_build_scanner_path(self, scanner):
"""Fetch the scanner path for this executor's targets and sources.
"""
env = self.get_build_env()
try:
cwd = self.batches[0].targets[0].cwd
except (IndexError, AttributeError):
cwd = None
return scanner.path(env, cwd,
self.get_all_targets(),
self.get_all_sources()) | python | def get_build_scanner_path(self, scanner):
"""Fetch the scanner path for this executor's targets and sources.
"""
env = self.get_build_env()
try:
cwd = self.batches[0].targets[0].cwd
except (IndexError, AttributeError):
cwd = None
return scanner.path(env, cwd,
self.get_all_targets(),
self.get_all_sources()) | [
"def",
"get_build_scanner_path",
"(",
"self",
",",
"scanner",
")",
":",
"env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"try",
":",
"cwd",
"=",
"self",
".",
"batches",
"[",
"0",
"]",
".",
"targets",
"[",
"0",
"]",
".",
"cwd",
"except",
"(",
"In... | Fetch the scanner path for this executor's targets and sources. | [
"Fetch",
"the",
"scanner",
"path",
"for",
"this",
"executor",
"s",
"targets",
"and",
"sources",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L372-L382 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.add_sources | def add_sources(self, sources):
"""Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target."""
# TODO(batch): extend to multiple batches
assert (len(self.batches) == 1)
# TODO(batch): remove duplicates?
sources = [x for x in sources if x not in self.batches[0].sources]
self.batches[0].sources.extend(sources) | python | def add_sources(self, sources):
"""Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target."""
# TODO(batch): extend to multiple batches
assert (len(self.batches) == 1)
# TODO(batch): remove duplicates?
sources = [x for x in sources if x not in self.batches[0].sources]
self.batches[0].sources.extend(sources) | [
"def",
"add_sources",
"(",
"self",
",",
"sources",
")",
":",
"assert",
"(",
"len",
"(",
"self",
".",
"batches",
")",
"==",
"1",
")",
"sources",
"=",
"[",
"x",
"for",
"x",
"in",
"sources",
"if",
"x",
"not",
"in",
"self",
".",
"batches",
"[",
"0",
... | Add source files to this Executor's list. This is necessary
for "multi" Builders that can be called repeatedly to build up
a source file list for a given target. | [
"Add",
"source",
"files",
"to",
"this",
"Executor",
"s",
"list",
".",
"This",
"is",
"necessary",
"for",
"multi",
"Builders",
"that",
"can",
"be",
"called",
"repeatedly",
"to",
"build",
"up",
"a",
"source",
"file",
"list",
"for",
"a",
"given",
"target",
"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L400-L408 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.add_batch | def add_batch(self, targets, sources):
"""Add pair of associated target and source to this Executor's list.
This is necessary for "batch" Builders that can be called repeatedly
to build up a list of matching target and source files that will be
used in order to update multiple target files at once from multiple
corresponding source files, for tools like MSVC that support it."""
self.batches.append(Batch(targets, sources)) | python | def add_batch(self, targets, sources):
"""Add pair of associated target and source to this Executor's list.
This is necessary for "batch" Builders that can be called repeatedly
to build up a list of matching target and source files that will be
used in order to update multiple target files at once from multiple
corresponding source files, for tools like MSVC that support it."""
self.batches.append(Batch(targets, sources)) | [
"def",
"add_batch",
"(",
"self",
",",
"targets",
",",
"sources",
")",
":",
"self",
".",
"batches",
".",
"append",
"(",
"Batch",
"(",
"targets",
",",
"sources",
")",
")"
] | Add pair of associated target and source to this Executor's list.
This is necessary for "batch" Builders that can be called repeatedly
to build up a list of matching target and source files that will be
used in order to update multiple target files at once from multiple
corresponding source files, for tools like MSVC that support it. | [
"Add",
"pair",
"of",
"associated",
"target",
"and",
"source",
"to",
"this",
"Executor",
"s",
"list",
".",
"This",
"is",
"necessary",
"for",
"batch",
"Builders",
"that",
"can",
"be",
"called",
"repeatedly",
"to",
"build",
"up",
"a",
"list",
"of",
"matching"... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L413-L419 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_contents | def get_contents(self):
"""Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are.
"""
try:
return self._memo['get_contents']
except KeyError:
pass
env = self.get_build_env()
action_list = self.get_action_list()
all_targets = self.get_all_targets()
all_sources = self.get_all_sources()
result = bytearray("",'utf-8').join([action.get_contents(all_targets,
all_sources,
env)
for action in action_list])
self._memo['get_contents'] = result
return result | python | def get_contents(self):
"""Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are.
"""
try:
return self._memo['get_contents']
except KeyError:
pass
env = self.get_build_env()
action_list = self.get_action_list()
all_targets = self.get_all_targets()
all_sources = self.get_all_sources()
result = bytearray("",'utf-8').join([action.get_contents(all_targets,
all_sources,
env)
for action in action_list])
self._memo['get_contents'] = result
return result | [
"def",
"get_contents",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'get_contents'",
"]",
"except",
"KeyError",
":",
"pass",
"env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"action_list",
"=",
"self",
".",
"get_action_list",... | Fetch the signature contents. This is the main reason this
class exists, so we can compute this once and cache it regardless
of how many target or source Nodes there are. | [
"Fetch",
"the",
"signature",
"contents",
".",
"This",
"is",
"the",
"main",
"reason",
"this",
"class",
"exists",
"so",
"we",
"can",
"compute",
"this",
"once",
"and",
"cache",
"it",
"regardless",
"of",
"how",
"many",
"target",
"or",
"source",
"Nodes",
"there... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L448-L469 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Executor.get_implicit_deps | def get_implicit_deps(self):
"""Return the executor's implicit dependencies, i.e. the nodes of
the commands to be executed."""
result = []
build_env = self.get_build_env()
for act in self.get_action_list():
deps = act.get_implicit_deps(self.get_all_targets(),
self.get_all_sources(),
build_env)
result.extend(deps)
return result | python | def get_implicit_deps(self):
"""Return the executor's implicit dependencies, i.e. the nodes of
the commands to be executed."""
result = []
build_env = self.get_build_env()
for act in self.get_action_list():
deps = act.get_implicit_deps(self.get_all_targets(),
self.get_all_sources(),
build_env)
result.extend(deps)
return result | [
"def",
"get_implicit_deps",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"build_env",
"=",
"self",
".",
"get_build_env",
"(",
")",
"for",
"act",
"in",
"self",
".",
"get_action_list",
"(",
")",
":",
"deps",
"=",
"act",
".",
"get_implicit_deps",
"(",
... | Return the executor's implicit dependencies, i.e. the nodes of
the commands to be executed. | [
"Return",
"the",
"executor",
"s",
"implicit",
"dependencies",
"i",
".",
"e",
".",
"the",
"nodes",
"of",
"the",
"commands",
"to",
"be",
"executed",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L546-L556 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py | Null._morph | def _morph(self):
"""Morph this Null executor to a real Executor object."""
batches = self.batches
self.__class__ = Executor
self.__init__([])
self.batches = batches | python | def _morph(self):
"""Morph this Null executor to a real Executor object."""
batches = self.batches
self.__class__ = Executor
self.__init__([])
self.batches = batches | [
"def",
"_morph",
"(",
"self",
")",
":",
"batches",
"=",
"self",
".",
"batches",
"self",
".",
"__class__",
"=",
"Executor",
"self",
".",
"__init__",
"(",
"[",
"]",
")",
"self",
".",
"batches",
"=",
"batches"
] | Morph this Null executor to a real Executor object. | [
"Morph",
"this",
"Null",
"executor",
"to",
"a",
"real",
"Executor",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L645-L650 | train |
iotile/coretools | iotilecore/iotile/core/hw/update/record.py | UpdateRecord.LoadPlugins | def LoadPlugins(cls):
"""Load all registered iotile.update_record plugins."""
if cls.PLUGINS_LOADED:
return
reg = ComponentRegistry()
for _, record in reg.load_extensions('iotile.update_record'):
cls.RegisterRecordType(record)
cls.PLUGINS_LOADED = True | python | def LoadPlugins(cls):
"""Load all registered iotile.update_record plugins."""
if cls.PLUGINS_LOADED:
return
reg = ComponentRegistry()
for _, record in reg.load_extensions('iotile.update_record'):
cls.RegisterRecordType(record)
cls.PLUGINS_LOADED = True | [
"def",
"LoadPlugins",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"PLUGINS_LOADED",
":",
"return",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_",
",",
"record",
"in",
"reg",
".",
"load_extensions",
"(",
"'iotile.update_record'",
")",
":",
"cls",
".",
... | Load all registered iotile.update_record plugins. | [
"Load",
"all",
"registered",
"iotile",
".",
"update_record",
"plugins",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/record.py#L82-L92 | train |
iotile/coretools | iotilecore/iotile/core/hw/update/record.py | UpdateRecord.RegisterRecordType | def RegisterRecordType(cls, record_class):
"""Register a known record type in KNOWN_CLASSES.
Args:
record_class (UpdateRecord): An update record subclass.
"""
record_type = record_class.MatchType()
if record_type not in UpdateRecord.KNOWN_CLASSES:
UpdateRecord.KNOWN_CLASSES[record_type] = []
UpdateRecord.KNOWN_CLASSES[record_type].append(record_class) | python | def RegisterRecordType(cls, record_class):
"""Register a known record type in KNOWN_CLASSES.
Args:
record_class (UpdateRecord): An update record subclass.
"""
record_type = record_class.MatchType()
if record_type not in UpdateRecord.KNOWN_CLASSES:
UpdateRecord.KNOWN_CLASSES[record_type] = []
UpdateRecord.KNOWN_CLASSES[record_type].append(record_class) | [
"def",
"RegisterRecordType",
"(",
"cls",
",",
"record_class",
")",
":",
"record_type",
"=",
"record_class",
".",
"MatchType",
"(",
")",
"if",
"record_type",
"not",
"in",
"UpdateRecord",
".",
"KNOWN_CLASSES",
":",
"UpdateRecord",
".",
"KNOWN_CLASSES",
"[",
"recor... | Register a known record type in KNOWN_CLASSES.
Args:
record_class (UpdateRecord): An update record subclass. | [
"Register",
"a",
"known",
"record",
"type",
"in",
"KNOWN_CLASSES",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/update/record.py#L131-L142 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/root_scope.py | RootScope._setup | def _setup(self):
"""Prepare for code generation by setting up root clock nodes.
These nodes are subsequently used as the basis for all clock operations.
"""
# Create a root system ticks and user configurable ticks
systick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
fasttick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user1tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user2tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(system_tick, systick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(fast_tick, fasttick))
self.sensor_graph.add_config(SlotIdentifier.FromString('controller'), config_fast_tick_secs, 'uint32_t', 1)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_1, user1tick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_2, user2tick))
self.system_tick = systick
self.fast_tick = fasttick
self.user1_tick = user1tick
self.user2_tick = user2tick | python | def _setup(self):
"""Prepare for code generation by setting up root clock nodes.
These nodes are subsequently used as the basis for all clock operations.
"""
# Create a root system ticks and user configurable ticks
systick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
fasttick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user1tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
user2tick = self.allocator.allocate_stream(DataStream.CounterType, attach=True)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(system_tick, systick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(fast_tick, fasttick))
self.sensor_graph.add_config(SlotIdentifier.FromString('controller'), config_fast_tick_secs, 'uint32_t', 1)
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_1, user1tick))
self.sensor_graph.add_node("({} always) => {} using copy_all_a".format(tick_2, user2tick))
self.system_tick = systick
self.fast_tick = fasttick
self.user1_tick = user1tick
self.user2_tick = user2tick | [
"def",
"_setup",
"(",
"self",
")",
":",
"systick",
"=",
"self",
".",
"allocator",
".",
"allocate_stream",
"(",
"DataStream",
".",
"CounterType",
",",
"attach",
"=",
"True",
")",
"fasttick",
"=",
"self",
".",
"allocator",
".",
"allocate_stream",
"(",
"DataS... | Prepare for code generation by setting up root clock nodes.
These nodes are subsequently used as the basis for all clock operations. | [
"Prepare",
"for",
"code",
"generation",
"by",
"setting",
"up",
"root",
"clock",
"nodes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/scopes/root_scope.py#L30-L51 | train |
iotile/coretools | iotilecore/iotile/core/hw/proxy/external_proxy.py | find_proxy_plugin | def find_proxy_plugin(component, plugin_name):
""" Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError
"""
reg = ComponentRegistry()
plugins = reg.load_extensions('iotile.proxy_plugin', comp_filter=component, class_filter=TileBusProxyPlugin,
product_name='proxy_plugin')
for _name, plugin in plugins:
if plugin.__name__ == plugin_name:
return plugin
raise DataError("Could not find proxy plugin module in registered components or installed distributions",
component=component, name=plugin_name) | python | def find_proxy_plugin(component, plugin_name):
""" Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError
"""
reg = ComponentRegistry()
plugins = reg.load_extensions('iotile.proxy_plugin', comp_filter=component, class_filter=TileBusProxyPlugin,
product_name='proxy_plugin')
for _name, plugin in plugins:
if plugin.__name__ == plugin_name:
return plugin
raise DataError("Could not find proxy plugin module in registered components or installed distributions",
component=component, name=plugin_name) | [
"def",
"find_proxy_plugin",
"(",
"component",
",",
"plugin_name",
")",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"plugins",
"=",
"reg",
".",
"load_extensions",
"(",
"'iotile.proxy_plugin'",
",",
"comp_filter",
"=",
"component",
",",
"class_filter",
"=",
"T... | Attempt to find a proxy plugin provided by a specific component
Args:
component (string): The name of the component that provides the plugin
plugin_name (string): The name of the plugin to load
Returns:
TileBuxProxyPlugin: The plugin, if found, otherwise raises DataError | [
"Attempt",
"to",
"find",
"a",
"proxy",
"plugin",
"provided",
"by",
"a",
"specific",
"component"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/proxy/external_proxy.py#L12-L33 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/statements/on_block.py | OnBlock._convert_trigger | def _convert_trigger(self, trigger_def, parent):
"""Convert a TriggerDefinition into a stream, trigger pair."""
if trigger_def.explicit_stream is None:
stream = parent.resolve_identifier(trigger_def.named_event, DataStream)
trigger = TrueTrigger()
else:
stream = trigger_def.explicit_stream
trigger = trigger_def.explicit_trigger
return (stream, trigger) | python | def _convert_trigger(self, trigger_def, parent):
"""Convert a TriggerDefinition into a stream, trigger pair."""
if trigger_def.explicit_stream is None:
stream = parent.resolve_identifier(trigger_def.named_event, DataStream)
trigger = TrueTrigger()
else:
stream = trigger_def.explicit_stream
trigger = trigger_def.explicit_trigger
return (stream, trigger) | [
"def",
"_convert_trigger",
"(",
"self",
",",
"trigger_def",
",",
"parent",
")",
":",
"if",
"trigger_def",
".",
"explicit_stream",
"is",
"None",
":",
"stream",
"=",
"parent",
".",
"resolve_identifier",
"(",
"trigger_def",
".",
"named_event",
",",
"DataStream",
... | Convert a TriggerDefinition into a stream, trigger pair. | [
"Convert",
"a",
"TriggerDefinition",
"into",
"a",
"stream",
"trigger",
"pair",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/statements/on_block.py#L46-L56 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/statements/on_block.py | OnBlock._parse_trigger | def _parse_trigger(self, trigger_clause):
"""Parse a named event or explicit stream trigger into a TriggerDefinition."""
cond = trigger_clause[0]
named_event = None
explicit_stream = None
explicit_trigger = None
# Identifier parse tree is Group(Identifier)
if cond.getName() == 'identifier':
named_event = cond[0]
elif cond.getName() == 'stream_trigger':
trigger_type = cond[0]
stream = cond[1]
oper = cond[2]
ref = cond[3]
trigger = InputTrigger(trigger_type, oper, ref)
explicit_stream = stream
explicit_trigger = trigger
elif cond.getName() == 'stream_always':
stream = cond[0]
trigger = TrueTrigger()
explicit_stream = stream
explicit_trigger = trigger
else:
raise ArgumentError("OnBlock created from an invalid ParseResults object", parse_results=trigger_clause)
return TriggerDefinition(named_event, explicit_stream, explicit_trigger) | python | def _parse_trigger(self, trigger_clause):
"""Parse a named event or explicit stream trigger into a TriggerDefinition."""
cond = trigger_clause[0]
named_event = None
explicit_stream = None
explicit_trigger = None
# Identifier parse tree is Group(Identifier)
if cond.getName() == 'identifier':
named_event = cond[0]
elif cond.getName() == 'stream_trigger':
trigger_type = cond[0]
stream = cond[1]
oper = cond[2]
ref = cond[3]
trigger = InputTrigger(trigger_type, oper, ref)
explicit_stream = stream
explicit_trigger = trigger
elif cond.getName() == 'stream_always':
stream = cond[0]
trigger = TrueTrigger()
explicit_stream = stream
explicit_trigger = trigger
else:
raise ArgumentError("OnBlock created from an invalid ParseResults object", parse_results=trigger_clause)
return TriggerDefinition(named_event, explicit_stream, explicit_trigger) | [
"def",
"_parse_trigger",
"(",
"self",
",",
"trigger_clause",
")",
":",
"cond",
"=",
"trigger_clause",
"[",
"0",
"]",
"named_event",
"=",
"None",
"explicit_stream",
"=",
"None",
"explicit_trigger",
"=",
"None",
"if",
"cond",
".",
"getName",
"(",
")",
"==",
... | Parse a named event or explicit stream trigger into a TriggerDefinition. | [
"Parse",
"a",
"named",
"event",
"or",
"explicit",
"stream",
"trigger",
"into",
"a",
"TriggerDefinition",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/statements/on_block.py#L58-L87 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | platform_default | def platform_default():
"""Return the platform string for our execution environment.
The returned value should map to one of the SCons/Platform/*.py
files. Since we're architecture independent, though, we don't
care about the machine architecture.
"""
osname = os.name
if osname == 'java':
osname = os._osType
if osname == 'posix':
if sys.platform == 'cygwin':
return 'cygwin'
elif sys.platform.find('irix') != -1:
return 'irix'
elif sys.platform.find('sunos') != -1:
return 'sunos'
elif sys.platform.find('hp-ux') != -1:
return 'hpux'
elif sys.platform.find('aix') != -1:
return 'aix'
elif sys.platform.find('darwin') != -1:
return 'darwin'
else:
return 'posix'
elif os.name == 'os2':
return 'os2'
else:
return sys.platform | python | def platform_default():
"""Return the platform string for our execution environment.
The returned value should map to one of the SCons/Platform/*.py
files. Since we're architecture independent, though, we don't
care about the machine architecture.
"""
osname = os.name
if osname == 'java':
osname = os._osType
if osname == 'posix':
if sys.platform == 'cygwin':
return 'cygwin'
elif sys.platform.find('irix') != -1:
return 'irix'
elif sys.platform.find('sunos') != -1:
return 'sunos'
elif sys.platform.find('hp-ux') != -1:
return 'hpux'
elif sys.platform.find('aix') != -1:
return 'aix'
elif sys.platform.find('darwin') != -1:
return 'darwin'
else:
return 'posix'
elif os.name == 'os2':
return 'os2'
else:
return sys.platform | [
"def",
"platform_default",
"(",
")",
":",
"osname",
"=",
"os",
".",
"name",
"if",
"osname",
"==",
"'java'",
":",
"osname",
"=",
"os",
".",
"_osType",
"if",
"osname",
"==",
"'posix'",
":",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"return",
... | Return the platform string for our execution environment.
The returned value should map to one of the SCons/Platform/*.py
files. Since we're architecture independent, though, we don't
care about the machine architecture. | [
"Return",
"the",
"platform",
"string",
"for",
"our",
"execution",
"environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L59-L87 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | platform_module | def platform_module(name = platform_default()):
"""Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment.
"""
full_name = 'SCons.Platform.' + name
if full_name not in sys.modules:
if os.name == 'java':
eval(full_name)
else:
try:
file, path, desc = imp.find_module(name,
sys.modules['SCons.Platform'].__path__)
try:
mod = imp.load_module(full_name, file, path, desc)
finally:
if file:
file.close()
except ImportError:
try:
import zipimport
importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] )
mod = importer.load_module(full_name)
except ImportError:
raise SCons.Errors.UserError("No platform named '%s'" % name)
setattr(SCons.Platform, name, mod)
return sys.modules[full_name] | python | def platform_module(name = platform_default()):
"""Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment.
"""
full_name = 'SCons.Platform.' + name
if full_name not in sys.modules:
if os.name == 'java':
eval(full_name)
else:
try:
file, path, desc = imp.find_module(name,
sys.modules['SCons.Platform'].__path__)
try:
mod = imp.load_module(full_name, file, path, desc)
finally:
if file:
file.close()
except ImportError:
try:
import zipimport
importer = zipimport.zipimporter( sys.modules['SCons.Platform'].__path__[0] )
mod = importer.load_module(full_name)
except ImportError:
raise SCons.Errors.UserError("No platform named '%s'" % name)
setattr(SCons.Platform, name, mod)
return sys.modules[full_name] | [
"def",
"platform_module",
"(",
"name",
"=",
"platform_default",
"(",
")",
")",
":",
"full_name",
"=",
"'SCons.Platform.'",
"+",
"name",
"if",
"full_name",
"not",
"in",
"sys",
".",
"modules",
":",
"if",
"os",
".",
"name",
"==",
"'java'",
":",
"eval",
"(",... | Return the imported module for the platform.
This looks for a module name that matches the specified argument.
If the name is unspecified, we fetch the appropriate default for
our execution environment. | [
"Return",
"the",
"imported",
"module",
"for",
"the",
"platform",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L89-L117 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py | Platform | def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec | python | def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec | [
"def",
"Platform",
"(",
"name",
"=",
"platform_default",
"(",
")",
")",
":",
"module",
"=",
"platform_module",
"(",
"name",
")",
"spec",
"=",
"PlatformSpec",
"(",
"name",
",",
"module",
".",
"generate",
")",
"return",
"spec"
] | Select a canned Platform specification. | [
"Select",
"a",
"canned",
"Platform",
"specification",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Platform/__init__.py#L255-L260 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | jarSources | def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
else:
jarchdir_set = True
jarchdir = env.subst('$JARCHDIR', target=target, source=source)
if jarchdir:
jarchdir = env.fs.Dir(jarchdir)
result = []
for src in source:
contents = src.get_text_contents()
if contents[:16] != "Manifest-Version":
if jarchdir_set:
_chdir = jarchdir
else:
try:
_chdir = src.attributes.java_classdir
except AttributeError:
_chdir = None
if _chdir:
# If we are changing the dir with -C, then sources should
# be relative to that directory.
src = SCons.Subst.Literal(src.get_path(_chdir))
result.append('-C')
result.append(_chdir)
result.append(src)
return result | python | def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
else:
jarchdir_set = True
jarchdir = env.subst('$JARCHDIR', target=target, source=source)
if jarchdir:
jarchdir = env.fs.Dir(jarchdir)
result = []
for src in source:
contents = src.get_text_contents()
if contents[:16] != "Manifest-Version":
if jarchdir_set:
_chdir = jarchdir
else:
try:
_chdir = src.attributes.java_classdir
except AttributeError:
_chdir = None
if _chdir:
# If we are changing the dir with -C, then sources should
# be relative to that directory.
src = SCons.Subst.Literal(src.get_path(_chdir))
result.append('-C')
result.append(_chdir)
result.append(src)
return result | [
"def",
"jarSources",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"try",
":",
"env",
"[",
"'JARCHDIR'",
"]",
"except",
"KeyError",
":",
"jarchdir_set",
"=",
"False",
"else",
":",
"jarchdir_set",
"=",
"True",
"jarchdir",
"=",
... | Only include sources that are not a manifest file. | [
"Only",
"include",
"sources",
"that",
"are",
"not",
"a",
"manifest",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L41-L70 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | jarManifest | def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | python | def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | [
"def",
"jarManifest",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"for",
"src",
"in",
"source",
":",
"contents",
"=",
"src",
".",
"get_text_contents",
"(",
")",
"if",
"contents",
"[",
":",
"16",
"]",
"==",
"\"Manifest-Versio... | Look in sources for a manifest file, if any. | [
"Look",
"in",
"sources",
"for",
"a",
"manifest",
"file",
"if",
"any",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L72-L78 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | jarFlags | def jarFlags(target, source, env, for_signature):
"""If we have a manifest, make sure that the 'm'
flag is specified."""
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
if not 'm' in jarflags:
return jarflags + 'm'
break
return jarflags | python | def jarFlags(target, source, env, for_signature):
"""If we have a manifest, make sure that the 'm'
flag is specified."""
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
if not 'm' in jarflags:
return jarflags + 'm'
break
return jarflags | [
"def",
"jarFlags",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"jarflags",
"=",
"env",
".",
"subst",
"(",
"'$JARFLAGS'",
",",
"target",
"=",
"target",
",",
"source",
"=",
"source",
")",
"for",
"src",
"in",
"source",
":",
... | If we have a manifest, make sure that the 'm'
flag is specified. | [
"If",
"we",
"have",
"a",
"manifest",
"make",
"sure",
"that",
"the",
"m",
"flag",
"is",
"specified",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L80-L90 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | generate | def generate(env):
"""Add Builders and construction variables for jar to an Environment."""
SCons.Tool.CreateJarBuilder(env)
SCons.Tool.CreateJavaFileBuilder(env)
SCons.Tool.CreateJavaClassFileBuilder(env)
SCons.Tool.CreateJavaClassDirBuilder(env)
env.AddMethod(Jar)
env['JAR'] = 'jar'
env['JARFLAGS'] = SCons.Util.CLVar('cf')
env['_JARFLAGS'] = jarFlags
env['_JARMANIFEST'] = jarManifest
env['_JARSOURCES'] = jarSources
env['_JARCOM'] = '$JAR $_JARFLAGS $TARGET $_JARMANIFEST $_JARSOURCES'
env['JARCOM'] = "${TEMPFILE('$_JARCOM','$JARCOMSTR')}"
env['JARSUFFIX'] = '.jar' | python | def generate(env):
"""Add Builders and construction variables for jar to an Environment."""
SCons.Tool.CreateJarBuilder(env)
SCons.Tool.CreateJavaFileBuilder(env)
SCons.Tool.CreateJavaClassFileBuilder(env)
SCons.Tool.CreateJavaClassDirBuilder(env)
env.AddMethod(Jar)
env['JAR'] = 'jar'
env['JARFLAGS'] = SCons.Util.CLVar('cf')
env['_JARFLAGS'] = jarFlags
env['_JARMANIFEST'] = jarManifest
env['_JARSOURCES'] = jarSources
env['_JARCOM'] = '$JAR $_JARFLAGS $TARGET $_JARMANIFEST $_JARSOURCES'
env['JARCOM'] = "${TEMPFILE('$_JARCOM','$JARCOMSTR')}"
env['JARSUFFIX'] = '.jar' | [
"def",
"generate",
"(",
"env",
")",
":",
"SCons",
".",
"Tool",
".",
"CreateJarBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"CreateJavaFileBuilder",
"(",
"env",
")",
"SCons",
".",
"Tool",
".",
"CreateJavaClassFileBuilder",
"(",
"env",
")",
"SCons",... | Add Builders and construction variables for jar to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"jar",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L199-L216 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/sim/executor.py | RPCExecutor.mock | def mock(self, slot, rpc_id, value):
"""Store a mock return value for an RPC
Args:
slot (SlotIdentifier): The slot we are mocking
rpc_id (int): The rpc we are mocking
value (int): The value that should be returned
when the RPC is called.
"""
address = slot.address
if address not in self.mock_rpcs:
self.mock_rpcs[address] = {}
self.mock_rpcs[address][rpc_id] = value | python | def mock(self, slot, rpc_id, value):
"""Store a mock return value for an RPC
Args:
slot (SlotIdentifier): The slot we are mocking
rpc_id (int): The rpc we are mocking
value (int): The value that should be returned
when the RPC is called.
"""
address = slot.address
if address not in self.mock_rpcs:
self.mock_rpcs[address] = {}
self.mock_rpcs[address][rpc_id] = value | [
"def",
"mock",
"(",
"self",
",",
"slot",
",",
"rpc_id",
",",
"value",
")",
":",
"address",
"=",
"slot",
".",
"address",
"if",
"address",
"not",
"in",
"self",
".",
"mock_rpcs",
":",
"self",
".",
"mock_rpcs",
"[",
"address",
"]",
"=",
"{",
"}",
"self... | Store a mock return value for an RPC
Args:
slot (SlotIdentifier): The slot we are mocking
rpc_id (int): The rpc we are mocking
value (int): The value that should be returned
when the RPC is called. | [
"Store",
"a",
"mock",
"return",
"value",
"for",
"an",
"RPC"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/executor.py#L21-L36 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/sim/executor.py | RPCExecutor.rpc | def rpc(self, address, rpc_id):
"""Call an RPC and receive the result as an integer.
If the RPC does not properly return a 32 bit integer, raise a warning
unless it cannot be converted into an integer at all, in which case
a HardwareError is thrown.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
Returns:
int: The result of the RPC call. If the rpc did not succeed
an error is thrown instead.
"""
# Always allow mocking an RPC to override whatever the defaul behavior is
if address in self.mock_rpcs and rpc_id in self.mock_rpcs[address]:
value = self.mock_rpcs[address][rpc_id]
return value
result = self._call_rpc(address, rpc_id, bytes())
if len(result) != 4:
self.warn(u"RPC 0x%X on address %d: response had invalid length %d not equal to 4" % (rpc_id, address, len(result)))
if len(result) < 4:
raise HardwareError("Response from RPC was not long enough to parse as an integer", rpc_id=rpc_id, address=address, response_length=len(result))
if len(result) > 4:
result = result[:4]
res, = struct.unpack("<L", result)
return res | python | def rpc(self, address, rpc_id):
"""Call an RPC and receive the result as an integer.
If the RPC does not properly return a 32 bit integer, raise a warning
unless it cannot be converted into an integer at all, in which case
a HardwareError is thrown.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
Returns:
int: The result of the RPC call. If the rpc did not succeed
an error is thrown instead.
"""
# Always allow mocking an RPC to override whatever the defaul behavior is
if address in self.mock_rpcs and rpc_id in self.mock_rpcs[address]:
value = self.mock_rpcs[address][rpc_id]
return value
result = self._call_rpc(address, rpc_id, bytes())
if len(result) != 4:
self.warn(u"RPC 0x%X on address %d: response had invalid length %d not equal to 4" % (rpc_id, address, len(result)))
if len(result) < 4:
raise HardwareError("Response from RPC was not long enough to parse as an integer", rpc_id=rpc_id, address=address, response_length=len(result))
if len(result) > 4:
result = result[:4]
res, = struct.unpack("<L", result)
return res | [
"def",
"rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
")",
":",
"if",
"address",
"in",
"self",
".",
"mock_rpcs",
"and",
"rpc_id",
"in",
"self",
".",
"mock_rpcs",
"[",
"address",
"]",
":",
"value",
"=",
"self",
".",
"mock_rpcs",
"[",
"address",
"]... | Call an RPC and receive the result as an integer.
If the RPC does not properly return a 32 bit integer, raise a warning
unless it cannot be converted into an integer at all, in which case
a HardwareError is thrown.
Args:
address (int): The address of the tile we want to call the RPC
on
rpc_id (int): The id of the RPC that we want to call
Returns:
int: The result of the RPC call. If the rpc did not succeed
an error is thrown instead. | [
"Call",
"an",
"RPC",
"and",
"receive",
"the",
"result",
"as",
"an",
"integer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/executor.py#L49-L83 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py | _get_swig_version | def _get_swig_version(env, swig):
"""Run the SWIG command line tool to get and return the version number"""
swig = env.subst(swig)
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
# MAYBE: out = SCons.Util.to_str (pipe.stdout.read())
out = SCons.Util.to_str(pipe.stdout.read())
match = re.search('SWIG Version\s+(\S+).*', out, re.MULTILINE)
if match:
if verbose: print("Version is:%s"%match.group(1))
return match.group(1)
else:
if verbose: print("Unable to detect version: [%s]"%out) | python | def _get_swig_version(env, swig):
"""Run the SWIG command line tool to get and return the version number"""
swig = env.subst(swig)
pipe = SCons.Action._subproc(env, SCons.Util.CLVar(swig) + ['-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
# MAYBE: out = SCons.Util.to_str (pipe.stdout.read())
out = SCons.Util.to_str(pipe.stdout.read())
match = re.search('SWIG Version\s+(\S+).*', out, re.MULTILINE)
if match:
if verbose: print("Version is:%s"%match.group(1))
return match.group(1)
else:
if verbose: print("Unable to detect version: [%s]"%out) | [
"def",
"_get_swig_version",
"(",
"env",
",",
"swig",
")",
":",
"swig",
"=",
"env",
".",
"subst",
"(",
"swig",
")",
"pipe",
"=",
"SCons",
".",
"Action",
".",
"_subproc",
"(",
"env",
",",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"swig",
")",
"+",
"... | Run the SWIG command line tool to get and return the version number | [
"Run",
"the",
"SWIG",
"command",
"line",
"tool",
"to",
"get",
"and",
"return",
"the",
"version",
"number"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py#L134-L150 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py | generate | def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _swigEmitter)
cxx_file.add_action('.i', SwigAction)
cxx_file.add_emitter('.i', _swigEmitter)
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_file.suffix['.i'] = swigSuffixEmitter
java_file.add_action('.i', SwigAction)
java_file.add_emitter('.i', _swigEmitter)
if 'SWIG' not in env:
env['SWIG'] = env.Detect(swigs) or swigs[0]
env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
env['SWIGPATH'] = []
env['SWIGINCPREFIX'] = '-I'
env['SWIGINCSUFFIX'] = ''
env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES' | python | def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _swigEmitter)
cxx_file.add_action('.i', SwigAction)
cxx_file.add_emitter('.i', _swigEmitter)
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_file.suffix['.i'] = swigSuffixEmitter
java_file.add_action('.i', SwigAction)
java_file.add_emitter('.i', _swigEmitter)
if 'SWIG' not in env:
env['SWIG'] = env.Detect(swigs) or swigs[0]
env['SWIGVERSION'] = _get_swig_version(env, env['SWIG'])
env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
env['SWIGPATH'] = []
env['SWIGINCPREFIX'] = '-I'
env['SWIGINCSUFFIX'] = ''
env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES' | [
"def",
"generate",
"(",
"env",
")",
":",
"c_file",
",",
"cxx_file",
"=",
"SCons",
".",
"Tool",
".",
"createCFileBuilders",
"(",
"env",
")",
"c_file",
".",
"suffix",
"[",
"'.i'",
"]",
"=",
"swigSuffixEmitter",
"cxx_file",
".",
"suffix",
"[",
"'.i'",
"]",
... | Add Builders and construction variables for swig to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"swig",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/swig.py#L152-L183 | train |
iotile/coretools | transport_plugins/jlink/iotile_transport_jlink/multiplexers.py | _select_ftdi_channel | def _select_ftdi_channel(channel):
"""Select multiplexer channel. Currently uses a FTDI chip via pylibftdi"""
if channel < 0 or channel > 8:
raise ArgumentError("FTDI-selected multiplexer only has channels 0-7 valid, "
"make sure you specify channel with -c channel=number", channel=channel)
from pylibftdi import BitBangDevice
bb = BitBangDevice(auto_detach=False)
bb.direction = 0b111
bb.port = channel | python | def _select_ftdi_channel(channel):
"""Select multiplexer channel. Currently uses a FTDI chip via pylibftdi"""
if channel < 0 or channel > 8:
raise ArgumentError("FTDI-selected multiplexer only has channels 0-7 valid, "
"make sure you specify channel with -c channel=number", channel=channel)
from pylibftdi import BitBangDevice
bb = BitBangDevice(auto_detach=False)
bb.direction = 0b111
bb.port = channel | [
"def",
"_select_ftdi_channel",
"(",
"channel",
")",
":",
"if",
"channel",
"<",
"0",
"or",
"channel",
">",
"8",
":",
"raise",
"ArgumentError",
"(",
"\"FTDI-selected multiplexer only has channels 0-7 valid, \"",
"\"make sure you specify channel with -c channel=number\"",
",",
... | Select multiplexer channel. Currently uses a FTDI chip via pylibftdi | [
"Select",
"multiplexer",
"channel",
".",
"Currently",
"uses",
"a",
"FTDI",
"chip",
"via",
"pylibftdi"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/jlink/iotile_transport_jlink/multiplexers.py#L5-L13 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/streamer_descriptor.py | parse_binary_descriptor | def parse_binary_descriptor(bindata, sensor_log=None):
"""Convert a binary streamer descriptor into a string descriptor.
Binary streamer descriptors are 20-byte binary structures that encode all
information needed to create a streamer. They are used to communicate
that information to an embedded device in an efficent format. This
function exists to turn such a compressed streamer description back into
an understandable string.
Args:
bindata (bytes): The binary streamer descriptor that we want to
understand.
sensor_log (SensorLog): Optional sensor_log to add this streamer to
a an underlying data store.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
You can get a useful human readable string by calling str() on the
return value.
"""
if len(bindata) != 14:
raise ArgumentError("Invalid length of binary data in streamer descriptor", length=len(bindata), expected=14, data=bindata)
dest_tile, stream_id, trigger, format_code, type_code = struct.unpack("<8sHBBBx", bindata)
dest_id = SlotIdentifier.FromEncoded(dest_tile)
selector = DataStreamSelector.FromEncoded(stream_id)
format_name = DataStreamer.KnownFormatCodes.get(format_code)
type_name = DataStreamer.KnownTypeCodes.get(type_code)
if format_name is None:
raise ArgumentError("Unknown format code", code=format_code, known_code=DataStreamer.KnownFormatCodes)
if type_name is None:
raise ArgumentError("Unknown type code", code=type_code, known_codes=DataStreamer.KnownTypeCodes)
with_other = None
if trigger & (1 << 7):
auto = False
with_other = trigger & ((1 << 7) - 1)
elif trigger == 0:
auto = False
elif trigger == 1:
auto = True
else:
raise ArgumentError("Unknown trigger type for streamer", trigger_code=trigger)
return DataStreamer(selector, dest_id, format_name, auto, type_name, with_other=with_other, sensor_log=sensor_log) | python | def parse_binary_descriptor(bindata, sensor_log=None):
"""Convert a binary streamer descriptor into a string descriptor.
Binary streamer descriptors are 20-byte binary structures that encode all
information needed to create a streamer. They are used to communicate
that information to an embedded device in an efficent format. This
function exists to turn such a compressed streamer description back into
an understandable string.
Args:
bindata (bytes): The binary streamer descriptor that we want to
understand.
sensor_log (SensorLog): Optional sensor_log to add this streamer to
a an underlying data store.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
You can get a useful human readable string by calling str() on the
return value.
"""
if len(bindata) != 14:
raise ArgumentError("Invalid length of binary data in streamer descriptor", length=len(bindata), expected=14, data=bindata)
dest_tile, stream_id, trigger, format_code, type_code = struct.unpack("<8sHBBBx", bindata)
dest_id = SlotIdentifier.FromEncoded(dest_tile)
selector = DataStreamSelector.FromEncoded(stream_id)
format_name = DataStreamer.KnownFormatCodes.get(format_code)
type_name = DataStreamer.KnownTypeCodes.get(type_code)
if format_name is None:
raise ArgumentError("Unknown format code", code=format_code, known_code=DataStreamer.KnownFormatCodes)
if type_name is None:
raise ArgumentError("Unknown type code", code=type_code, known_codes=DataStreamer.KnownTypeCodes)
with_other = None
if trigger & (1 << 7):
auto = False
with_other = trigger & ((1 << 7) - 1)
elif trigger == 0:
auto = False
elif trigger == 1:
auto = True
else:
raise ArgumentError("Unknown trigger type for streamer", trigger_code=trigger)
return DataStreamer(selector, dest_id, format_name, auto, type_name, with_other=with_other, sensor_log=sensor_log) | [
"def",
"parse_binary_descriptor",
"(",
"bindata",
",",
"sensor_log",
"=",
"None",
")",
":",
"if",
"len",
"(",
"bindata",
")",
"!=",
"14",
":",
"raise",
"ArgumentError",
"(",
"\"Invalid length of binary data in streamer descriptor\"",
",",
"length",
"=",
"len",
"("... | Convert a binary streamer descriptor into a string descriptor.
Binary streamer descriptors are 20-byte binary structures that encode all
information needed to create a streamer. They are used to communicate
that information to an embedded device in an efficent format. This
function exists to turn such a compressed streamer description back into
an understandable string.
Args:
bindata (bytes): The binary streamer descriptor that we want to
understand.
sensor_log (SensorLog): Optional sensor_log to add this streamer to
a an underlying data store.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
You can get a useful human readable string by calling str() on the
return value. | [
"Convert",
"a",
"binary",
"streamer",
"descriptor",
"into",
"a",
"string",
"descriptor",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer_descriptor.py#L16-L65 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/streamer_descriptor.py | create_binary_descriptor | def create_binary_descriptor(streamer):
"""Create a packed binary descriptor of a DataStreamer object.
Args:
streamer (DataStreamer): The streamer to create a packed descriptor for
Returns:
bytes: A packed 14-byte streamer descriptor.
"""
trigger = 0
if streamer.automatic:
trigger = 1
elif streamer.with_other is not None:
trigger = (1 << 7) | streamer.with_other
return struct.pack("<8sHBBBx", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[streamer.format], streamer.KnownTypes[streamer.report_type]) | python | def create_binary_descriptor(streamer):
"""Create a packed binary descriptor of a DataStreamer object.
Args:
streamer (DataStreamer): The streamer to create a packed descriptor for
Returns:
bytes: A packed 14-byte streamer descriptor.
"""
trigger = 0
if streamer.automatic:
trigger = 1
elif streamer.with_other is not None:
trigger = (1 << 7) | streamer.with_other
return struct.pack("<8sHBBBx", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[streamer.format], streamer.KnownTypes[streamer.report_type]) | [
"def",
"create_binary_descriptor",
"(",
"streamer",
")",
":",
"trigger",
"=",
"0",
"if",
"streamer",
".",
"automatic",
":",
"trigger",
"=",
"1",
"elif",
"streamer",
".",
"with_other",
"is",
"not",
"None",
":",
"trigger",
"=",
"(",
"1",
"<<",
"7",
")",
... | Create a packed binary descriptor of a DataStreamer object.
Args:
streamer (DataStreamer): The streamer to create a packed descriptor for
Returns:
bytes: A packed 14-byte streamer descriptor. | [
"Create",
"a",
"packed",
"binary",
"descriptor",
"of",
"a",
"DataStreamer",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer_descriptor.py#L68-L84 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/streamer_descriptor.py | parse_string_descriptor | def parse_string_descriptor(string_desc):
"""Parse a string descriptor of a streamer into a DataStreamer object.
Args:
string_desc (str): The string descriptor that we wish to parse.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
"""
if not isinstance(string_desc, str):
string_desc = str(string_desc)
if not string_desc.endswith(';'):
string_desc += ';'
parsed = get_streamer_parser().parseString(string_desc)[0]
realtime = 'realtime' in parsed
broadcast = 'broadcast' in parsed
encrypted = 'security' in parsed and parsed['security'] == 'encrypted'
signed = 'security' in parsed and parsed['security'] == 'signed'
auto = 'manual' not in parsed
with_other = None
if 'with_other' in parsed:
with_other = parsed['with_other']
auto = False
dest = SlotIdentifier.FromString('controller')
if 'explicit_tile' in parsed:
dest = parsed['explicit_tile']
selector = parsed['selector']
# Make sure all of the combination are valid
if realtime and (encrypted or signed):
raise SensorGraphSemanticError("Realtime streamers cannot be either signed or encrypted")
if broadcast and (encrypted or signed):
raise SensorGraphSemanticError("Broadcast streamers cannot be either signed or encrypted")
report_type = 'broadcast' if broadcast else 'telegram'
dest = dest
selector = selector
if realtime or broadcast:
report_format = u'individual'
elif signed:
report_format = u'signedlist_userkey'
elif encrypted:
raise SensorGraphSemanticError("Encrypted streamers are not yet supported")
else:
report_format = u'hashedlist'
return DataStreamer(selector, dest, report_format, auto, report_type=report_type, with_other=with_other) | python | def parse_string_descriptor(string_desc):
"""Parse a string descriptor of a streamer into a DataStreamer object.
Args:
string_desc (str): The string descriptor that we wish to parse.
Returns:
DataStreamer: A DataStreamer object representing the streamer.
"""
if not isinstance(string_desc, str):
string_desc = str(string_desc)
if not string_desc.endswith(';'):
string_desc += ';'
parsed = get_streamer_parser().parseString(string_desc)[0]
realtime = 'realtime' in parsed
broadcast = 'broadcast' in parsed
encrypted = 'security' in parsed and parsed['security'] == 'encrypted'
signed = 'security' in parsed and parsed['security'] == 'signed'
auto = 'manual' not in parsed
with_other = None
if 'with_other' in parsed:
with_other = parsed['with_other']
auto = False
dest = SlotIdentifier.FromString('controller')
if 'explicit_tile' in parsed:
dest = parsed['explicit_tile']
selector = parsed['selector']
# Make sure all of the combination are valid
if realtime and (encrypted or signed):
raise SensorGraphSemanticError("Realtime streamers cannot be either signed or encrypted")
if broadcast and (encrypted or signed):
raise SensorGraphSemanticError("Broadcast streamers cannot be either signed or encrypted")
report_type = 'broadcast' if broadcast else 'telegram'
dest = dest
selector = selector
if realtime or broadcast:
report_format = u'individual'
elif signed:
report_format = u'signedlist_userkey'
elif encrypted:
raise SensorGraphSemanticError("Encrypted streamers are not yet supported")
else:
report_format = u'hashedlist'
return DataStreamer(selector, dest, report_format, auto, report_type=report_type, with_other=with_other) | [
"def",
"parse_string_descriptor",
"(",
"string_desc",
")",
":",
"if",
"not",
"isinstance",
"(",
"string_desc",
",",
"str",
")",
":",
"string_desc",
"=",
"str",
"(",
"string_desc",
")",
"if",
"not",
"string_desc",
".",
"endswith",
"(",
"';'",
")",
":",
"str... | Parse a string descriptor of a streamer into a DataStreamer object.
Args:
string_desc (str): The string descriptor that we wish to parse.
Returns:
DataStreamer: A DataStreamer object representing the streamer. | [
"Parse",
"a",
"string",
"descriptor",
"of",
"a",
"streamer",
"into",
"a",
"DataStreamer",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer_descriptor.py#L87-L142 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/applelink.py | generate | def generate(env):
"""Add Builders and construction variables for applelink to an
Environment."""
link.generate(env)
env['FRAMEWORKPATHPREFIX'] = '-F'
env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}'
env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS, "", __env__)}'
env['LINKCOM'] = env['LINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -dynamiclib')
env['SHLINKCOM'] = env['SHLINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
# TODO: Work needed to generate versioned shared libraries
# Leaving this commented out, and also going to disable versioned library checking for now
# see: http://docstore.mik.ua/orelly/unix3/mac/ch05_04.htm for proper naming
#link._setup_versioned_lib_variables(env, tool = 'applelink')#, use_soname = use_soname)
#env['LINKCALLBACKS'] = link._versioned_lib_callbacks()
# override the default for loadable modules, which are different
# on OS X than dynamic shared libs. echoing what XCode does for
# pre/suffixes:
env['LDMODULEPREFIX'] = ''
env['LDMODULESUFFIX'] = ''
env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle')
env['LDMODULECOM'] = '$LDMODULE -o ${TARGET} $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' | python | def generate(env):
"""Add Builders and construction variables for applelink to an
Environment."""
link.generate(env)
env['FRAMEWORKPATHPREFIX'] = '-F'
env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}'
env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS, "", __env__)}'
env['LINKCOM'] = env['LINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -dynamiclib')
env['SHLINKCOM'] = env['SHLINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
# TODO: Work needed to generate versioned shared libraries
# Leaving this commented out, and also going to disable versioned library checking for now
# see: http://docstore.mik.ua/orelly/unix3/mac/ch05_04.htm for proper naming
#link._setup_versioned_lib_variables(env, tool = 'applelink')#, use_soname = use_soname)
#env['LINKCALLBACKS'] = link._versioned_lib_callbacks()
# override the default for loadable modules, which are different
# on OS X than dynamic shared libs. echoing what XCode does for
# pre/suffixes:
env['LDMODULEPREFIX'] = ''
env['LDMODULESUFFIX'] = ''
env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle')
env['LDMODULECOM'] = '$LDMODULE -o ${TARGET} $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS' | [
"def",
"generate",
"(",
"env",
")",
":",
"link",
".",
"generate",
"(",
"env",
")",
"env",
"[",
"'FRAMEWORKPATHPREFIX'",
"]",
"=",
"'-F'",
"env",
"[",
"'_FRAMEWORKPATH'",
"]",
"=",
"'${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, \"\", __env__)}'",
"env",
"[",
"'_FR... | Add Builders and construction variables for applelink to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"applelink",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/applelink.py#L42-L68 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | _generateGUID | def _generateGUID(slnfile, name):
"""This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation."""
m = hashlib.md5()
# Normalize the slnfile path to a Windows path (\ separators) so
# the generated file has a consistent GUID even if we generate
# it on a non-Windows platform.
m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
solution = m.hexdigest().upper()
# convert most of the signature to GUID form (discard the rest)
solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
return solution | python | def _generateGUID(slnfile, name):
"""This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation."""
m = hashlib.md5()
# Normalize the slnfile path to a Windows path (\ separators) so
# the generated file has a consistent GUID even if we generate
# it on a non-Windows platform.
m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
solution = m.hexdigest().upper()
# convert most of the signature to GUID form (discard the rest)
solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
return solution | [
"def",
"_generateGUID",
"(",
"slnfile",
",",
"name",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"bytearray",
"(",
"ntpath",
".",
"normpath",
"(",
"str",
"(",
"slnfile",
")",
")",
"+",
"str",
"(",
"name",
")",
",... | This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation. | [
"This",
"generates",
"a",
"dummy",
"GUID",
"for",
"the",
"sln",
"file",
"to",
"use",
".",
"It",
"is",
"based",
"on",
"the",
"MD5",
"signatures",
"of",
"the",
"sln",
"filename",
"plus",
"the",
"name",
"of",
"the",
"project",
".",
"It",
"basically",
"jus... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L80-L93 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | makeHierarchy | def makeHierarchy(sources):
'''Break a list of files into a hierarchy; for each value, if it is a string,
then it is a file. If it is a dictionary, it is a folder. The string is
the original path of the file.'''
hierarchy = {}
for file in sources:
path = splitFully(file)
if len(path):
dict = hierarchy
for part in path[:-1]:
if part not in dict:
dict[part] = {}
dict = dict[part]
dict[path[-1]] = file
#else:
# print 'Warning: failed to decompose path for '+str(file)
return hierarchy | python | def makeHierarchy(sources):
'''Break a list of files into a hierarchy; for each value, if it is a string,
then it is a file. If it is a dictionary, it is a folder. The string is
the original path of the file.'''
hierarchy = {}
for file in sources:
path = splitFully(file)
if len(path):
dict = hierarchy
for part in path[:-1]:
if part not in dict:
dict[part] = {}
dict = dict[part]
dict[path[-1]] = file
#else:
# print 'Warning: failed to decompose path for '+str(file)
return hierarchy | [
"def",
"makeHierarchy",
"(",
"sources",
")",
":",
"hierarchy",
"=",
"{",
"}",
"for",
"file",
"in",
"sources",
":",
"path",
"=",
"splitFully",
"(",
"file",
")",
"if",
"len",
"(",
"path",
")",
":",
"dict",
"=",
"hierarchy",
"for",
"part",
"in",
"path",... | Break a list of files into a hierarchy; for each value, if it is a string,
then it is a file. If it is a dictionary, it is a folder. The string is
the original path of the file. | [
"Break",
"a",
"list",
"of",
"files",
"into",
"a",
"hierarchy",
";",
"for",
"each",
"value",
"if",
"it",
"is",
"a",
"string",
"then",
"it",
"is",
"a",
"file",
".",
"If",
"it",
"is",
"a",
"dictionary",
"it",
"is",
"a",
"folder",
".",
"The",
"string",... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L150-L167 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | GenerateDSP | def GenerateDSP(dspfile, source, env):
"""Generates a Project file based on the version of MSVS that is being used"""
version_num = 6.0
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
if version_num >= 10.0:
g = _GenerateV10DSP(dspfile, source, env)
g.Build()
elif version_num >= 7.0:
g = _GenerateV7DSP(dspfile, source, env)
g.Build()
else:
g = _GenerateV6DSP(dspfile, source, env)
g.Build() | python | def GenerateDSP(dspfile, source, env):
"""Generates a Project file based on the version of MSVS that is being used"""
version_num = 6.0
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
if version_num >= 10.0:
g = _GenerateV10DSP(dspfile, source, env)
g.Build()
elif version_num >= 7.0:
g = _GenerateV7DSP(dspfile, source, env)
g.Build()
else:
g = _GenerateV6DSP(dspfile, source, env)
g.Build() | [
"def",
"GenerateDSP",
"(",
"dspfile",
",",
"source",
",",
"env",
")",
":",
"version_num",
"=",
"6.0",
"if",
"'MSVS_VERSION'",
"in",
"env",
":",
"version_num",
",",
"suite",
"=",
"msvs_parse_version",
"(",
"env",
"[",
"'MSVS_VERSION'",
"]",
")",
"if",
"vers... | Generates a Project file based on the version of MSVS that is being used | [
"Generates",
"a",
"Project",
"file",
"based",
"on",
"the",
"version",
"of",
"MSVS",
"that",
"is",
"being",
"used"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1675-L1689 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | solutionEmitter | def solutionEmitter(target, source, env):
"""Sets up the DSW dependencies."""
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed, we also won't have
# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.
if source[0] == target[0]:
source = []
# make sure the suffix is correct for the version of MSVS we're running.
(base, suff) = SCons.Util.splitext(str(target[0]))
suff = env.subst('$MSVSSOLUTIONSUFFIX')
target[0] = base + suff
if not source:
source = 'sln_inputs:'
if 'name' in env:
if SCons.Util.is_String(env['name']):
source = source + ' "%s"' % env['name']
else:
raise SCons.Errors.InternalError("name must be a string")
if 'variant' in env:
if SCons.Util.is_String(env['variant']):
source = source + ' "%s"' % env['variant']
elif SCons.Util.is_List(env['variant']):
for variant in env['variant']:
if SCons.Util.is_String(variant):
source = source + ' "%s"' % variant
else:
raise SCons.Errors.InternalError("name must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be specified")
if 'slnguid' in env:
if SCons.Util.is_String(env['slnguid']):
source = source + ' "%s"' % env['slnguid']
else:
raise SCons.Errors.InternalError("slnguid must be a string")
if 'projects' in env:
if SCons.Util.is_String(env['projects']):
source = source + ' "%s"' % env['projects']
elif SCons.Util.is_List(env['projects']):
for t in env['projects']:
if SCons.Util.is_String(t):
source = source + ' "%s"' % t
source = source + ' "%s"' % str(target[0])
source = [SCons.Node.Python.Value(source)]
return ([target[0]], source) | python | def solutionEmitter(target, source, env):
"""Sets up the DSW dependencies."""
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed, we also won't have
# to make the user always append env['MSVSSOLUTIONSUFFIX'] to target.
if source[0] == target[0]:
source = []
# make sure the suffix is correct for the version of MSVS we're running.
(base, suff) = SCons.Util.splitext(str(target[0]))
suff = env.subst('$MSVSSOLUTIONSUFFIX')
target[0] = base + suff
if not source:
source = 'sln_inputs:'
if 'name' in env:
if SCons.Util.is_String(env['name']):
source = source + ' "%s"' % env['name']
else:
raise SCons.Errors.InternalError("name must be a string")
if 'variant' in env:
if SCons.Util.is_String(env['variant']):
source = source + ' "%s"' % env['variant']
elif SCons.Util.is_List(env['variant']):
for variant in env['variant']:
if SCons.Util.is_String(variant):
source = source + ' "%s"' % variant
else:
raise SCons.Errors.InternalError("name must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be a string or a list of strings")
else:
raise SCons.Errors.InternalError("variant must be specified")
if 'slnguid' in env:
if SCons.Util.is_String(env['slnguid']):
source = source + ' "%s"' % env['slnguid']
else:
raise SCons.Errors.InternalError("slnguid must be a string")
if 'projects' in env:
if SCons.Util.is_String(env['projects']):
source = source + ' "%s"' % env['projects']
elif SCons.Util.is_List(env['projects']):
for t in env['projects']:
if SCons.Util.is_String(t):
source = source + ' "%s"' % t
source = source + ' "%s"' % str(target[0])
source = [SCons.Node.Python.Value(source)]
return ([target[0]], source) | [
"def",
"solutionEmitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"if",
"source",
"[",
"0",
"]",
"==",
"target",
"[",
"0",
"]",
":",
"source",
"=",
"[",
"]",
"(",
"base",
",",
"suff",
")",
"=",
"SCons",
".",
"Util",
".",
"splitext",
... | Sets up the DSW dependencies. | [
"Sets",
"up",
"the",
"DSW",
"dependencies",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1858-L1912 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | generate | def generate(env):
"""Add Builders and construction variables for Microsoft Visual
Studio project files to an Environment."""
try:
env['BUILDERS']['MSVSProject']
except KeyError:
env['BUILDERS']['MSVSProject'] = projectBuilder
try:
env['BUILDERS']['MSVSSolution']
except KeyError:
env['BUILDERS']['MSVSSolution'] = solutionBuilder
env['MSVSPROJECTCOM'] = projectAction
env['MSVSSOLUTIONCOM'] = solutionAction
if SCons.Script.call_stack:
# XXX Need to find a way to abstract this; the build engine
# shouldn't depend on anything in SCons.Script.
env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript
else:
global default_MSVS_SConscript
if default_MSVS_SConscript is None:
default_MSVS_SConscript = env.File('SConstruct')
env['MSVSSCONSCRIPT'] = default_MSVS_SConscript
env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env))
env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.get_abspath()}" -f ${MSVSSCONSCRIPT.name}'
env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS'
env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"'
# Set-up ms tools paths for default version
msvc_setup_env_once(env)
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
else:
(version_num, suite) = (7.0, None) # guess at a default
if 'MSVS' not in env:
env['MSVS'] = {}
if (version_num < 7.0):
env['MSVS']['PROJECTSUFFIX'] = '.dsp'
env['MSVS']['SOLUTIONSUFFIX'] = '.dsw'
elif (version_num < 10.0):
env['MSVS']['PROJECTSUFFIX'] = '.vcproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
else:
env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
if (version_num >= 10.0):
env['MSVSENCODING'] = 'utf-8'
else:
env['MSVSENCODING'] = 'Windows-1252'
env['GET_MSVSPROJECTSUFFIX'] = GetMSVSProjectSuffix
env['GET_MSVSSOLUTIONSUFFIX'] = GetMSVSSolutionSuffix
env['MSVSPROJECTSUFFIX'] = '${GET_MSVSPROJECTSUFFIX}'
env['MSVSSOLUTIONSUFFIX'] = '${GET_MSVSSOLUTIONSUFFIX}'
env['SCONS_HOME'] = os.environ.get('SCONS_HOME') | python | def generate(env):
"""Add Builders and construction variables for Microsoft Visual
Studio project files to an Environment."""
try:
env['BUILDERS']['MSVSProject']
except KeyError:
env['BUILDERS']['MSVSProject'] = projectBuilder
try:
env['BUILDERS']['MSVSSolution']
except KeyError:
env['BUILDERS']['MSVSSolution'] = solutionBuilder
env['MSVSPROJECTCOM'] = projectAction
env['MSVSSOLUTIONCOM'] = solutionAction
if SCons.Script.call_stack:
# XXX Need to find a way to abstract this; the build engine
# shouldn't depend on anything in SCons.Script.
env['MSVSSCONSCRIPT'] = SCons.Script.call_stack[0].sconscript
else:
global default_MSVS_SConscript
if default_MSVS_SConscript is None:
default_MSVS_SConscript = env.File('SConstruct')
env['MSVSSCONSCRIPT'] = default_MSVS_SConscript
env['MSVSSCONS'] = '"%s" -c "%s"' % (python_executable, getExecScriptMain(env))
env['MSVSSCONSFLAGS'] = '-C "${MSVSSCONSCRIPT.dir.get_abspath()}" -f ${MSVSSCONSCRIPT.name}'
env['MSVSSCONSCOM'] = '$MSVSSCONS $MSVSSCONSFLAGS'
env['MSVSBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSREBUILDCOM'] = '$MSVSSCONSCOM "$MSVSBUILDTARGET"'
env['MSVSCLEANCOM'] = '$MSVSSCONSCOM -c "$MSVSBUILDTARGET"'
# Set-up ms tools paths for default version
msvc_setup_env_once(env)
if 'MSVS_VERSION' in env:
version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
else:
(version_num, suite) = (7.0, None) # guess at a default
if 'MSVS' not in env:
env['MSVS'] = {}
if (version_num < 7.0):
env['MSVS']['PROJECTSUFFIX'] = '.dsp'
env['MSVS']['SOLUTIONSUFFIX'] = '.dsw'
elif (version_num < 10.0):
env['MSVS']['PROJECTSUFFIX'] = '.vcproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
else:
env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
if (version_num >= 10.0):
env['MSVSENCODING'] = 'utf-8'
else:
env['MSVSENCODING'] = 'Windows-1252'
env['GET_MSVSPROJECTSUFFIX'] = GetMSVSProjectSuffix
env['GET_MSVSSOLUTIONSUFFIX'] = GetMSVSSolutionSuffix
env['MSVSPROJECTSUFFIX'] = '${GET_MSVSPROJECTSUFFIX}'
env['MSVSSOLUTIONSUFFIX'] = '${GET_MSVSSOLUTIONSUFFIX}'
env['SCONS_HOME'] = os.environ.get('SCONS_HOME') | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'MSVSProject'",
"]",
"except",
"KeyError",
":",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'MSVSProject'",
"]",
"=",
"projectBuilder",
"try",
":",
"env",
"[",
"'BUILDERS'... | Add Builders and construction variables for Microsoft Visual
Studio project files to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"Microsoft",
"Visual",
"Studio",
"project",
"files",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1928-L1989 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py | _GenerateV6DSW.PrintWorkspace | def PrintWorkspace(self):
""" writes a DSW file """
name = self.name
dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path)
self.file.write(V6DSWHeader % locals()) | python | def PrintWorkspace(self):
""" writes a DSW file """
name = self.name
dspfile = os.path.relpath(self.dspfiles[0], self.dsw_folder_path)
self.file.write(V6DSWHeader % locals()) | [
"def",
"PrintWorkspace",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"name",
"dspfile",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"dspfiles",
"[",
"0",
"]",
",",
"self",
".",
"dsw_folder_path",
")",
"self",
".",
"file",
".",
"w... | writes a DSW file | [
"writes",
"a",
"DSW",
"file"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/msvs.py#L1659-L1663 | train |
iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.waiters | def waiters(self, path=None):
"""Iterate over all waiters.
This method will return the waiters in unspecified order
including the future or callback object that will be invoked
and a list containing the keys/value that are being matched.
Yields:
list, future or callable
"""
context = self._waiters
if path is None:
path = []
for key in path:
context = context[key]
if self._LEAF in context:
for future in context[self._LEAF]:
yield (path, future)
for key in context:
if key is self._LEAF:
continue
yield from self.waiters(path=path + [key]) | python | def waiters(self, path=None):
"""Iterate over all waiters.
This method will return the waiters in unspecified order
including the future or callback object that will be invoked
and a list containing the keys/value that are being matched.
Yields:
list, future or callable
"""
context = self._waiters
if path is None:
path = []
for key in path:
context = context[key]
if self._LEAF in context:
for future in context[self._LEAF]:
yield (path, future)
for key in context:
if key is self._LEAF:
continue
yield from self.waiters(path=path + [key]) | [
"def",
"waiters",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"context",
"=",
"self",
".",
"_waiters",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"path",
":",
"context",
"=",
"context",
"[",
"key",
"]",
"if",... | Iterate over all waiters.
This method will return the waiters in unspecified order
including the future or callback object that will be invoked
and a list containing the keys/value that are being matched.
Yields:
list, future or callable | [
"Iterate",
"over",
"all",
"waiters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L138-L165 | train |
iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.every_match | def every_match(self, callback, **kwargs):
"""Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be removed by a call to remove_waiter(), passing the
handle object returned by this call to identify it.
Args:
callback (callable): A callable function that will be called as
callback(message) whenever a matching message is received.
Returns:
object: An opaque handle that can be passed to remove_waiter().
This handle is the only way to remove this callback if you no
longer want it to be called.
"""
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
responder = self._add_waiter(spec, callback)
return (spec, responder) | python | def every_match(self, callback, **kwargs):
"""Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be removed by a call to remove_waiter(), passing the
handle object returned by this call to identify it.
Args:
callback (callable): A callable function that will be called as
callback(message) whenever a matching message is received.
Returns:
object: An opaque handle that can be passed to remove_waiter().
This handle is the only way to remove this callback if you no
longer want it to be called.
"""
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
responder = self._add_waiter(spec, callback)
return (spec, responder) | [
"def",
"every_match",
"(",
"self",
",",
"callback",
",",
"**",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"ArgumentError",
"(",
"\"You must specify at least one message field to wait on\"",
")",
"spec",
"=",
"MessageSpec",
"(",... | Invoke callback every time a matching message is received.
The callback will be invoked directly inside process_message so that
you can guarantee that it has been called by the time process_message
has returned.
The callback can be removed by a call to remove_waiter(), passing the
handle object returned by this call to identify it.
Args:
callback (callable): A callable function that will be called as
callback(message) whenever a matching message is received.
Returns:
object: An opaque handle that can be passed to remove_waiter().
This handle is the only way to remove this callback if you no
longer want it to be called. | [
"Invoke",
"callback",
"every",
"time",
"a",
"matching",
"message",
"is",
"received",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L167-L194 | train |
iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.remove_waiter | def remove_waiter(self, waiter_handle):
"""Remove a message callback.
This call will remove a callback previously registered using
every_match.
Args:
waiter_handle (object): The opaque handle returned by the
previous call to every_match().
"""
spec, waiter = waiter_handle
self._remove_waiter(spec, waiter) | python | def remove_waiter(self, waiter_handle):
"""Remove a message callback.
This call will remove a callback previously registered using
every_match.
Args:
waiter_handle (object): The opaque handle returned by the
previous call to every_match().
"""
spec, waiter = waiter_handle
self._remove_waiter(spec, waiter) | [
"def",
"remove_waiter",
"(",
"self",
",",
"waiter_handle",
")",
":",
"spec",
",",
"waiter",
"=",
"waiter_handle",
"self",
".",
"_remove_waiter",
"(",
"spec",
",",
"waiter",
")"
] | Remove a message callback.
This call will remove a callback previously registered using
every_match.
Args:
waiter_handle (object): The opaque handle returned by the
previous call to every_match(). | [
"Remove",
"a",
"message",
"callback",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L202-L214 | train |
iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.clear | def clear(self):
"""Clear all waiters.
This method will remove any current scheduled waiter with an
asyncio.CancelledError exception.
"""
for _, waiter in self.waiters():
if isinstance(waiter, asyncio.Future) and not waiter.done():
waiter.set_exception(asyncio.CancelledError())
self._waiters = {} | python | def clear(self):
"""Clear all waiters.
This method will remove any current scheduled waiter with an
asyncio.CancelledError exception.
"""
for _, waiter in self.waiters():
if isinstance(waiter, asyncio.Future) and not waiter.done():
waiter.set_exception(asyncio.CancelledError())
self._waiters = {} | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"_",
",",
"waiter",
"in",
"self",
".",
"waiters",
"(",
")",
":",
"if",
"isinstance",
"(",
"waiter",
",",
"asyncio",
".",
"Future",
")",
"and",
"not",
"waiter",
".",
"done",
"(",
")",
":",
"waiter",
".... | Clear all waiters.
This method will remove any current scheduled waiter with an
asyncio.CancelledError exception. | [
"Clear",
"all",
"waiters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L216-L227 | train |
iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.wait_for | def wait_for(self, timeout=None, **kwargs):
"""Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is awaited.
If no matching message is received within the specified timeout (if
given), then asyncio.TimeoutError will be raised.
This function only matches a single message and removes itself once
the message is seen or the timeout expires.
Args:
timeout (float): Optional timeout, defaults to None for no timeout.
**kwargs: Keys to match in the message with their corresponding values.
You must pass at least one keyword argument so there is something
to look for.
Returns:
awaitable: The response
"""
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
future = self._add_waiter(spec)
future.add_done_callback(lambda x: self._remove_waiter(spec, future))
return asyncio.wait_for(future, timeout=timeout) | python | def wait_for(self, timeout=None, **kwargs):
"""Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is awaited.
If no matching message is received within the specified timeout (if
given), then asyncio.TimeoutError will be raised.
This function only matches a single message and removes itself once
the message is seen or the timeout expires.
Args:
timeout (float): Optional timeout, defaults to None for no timeout.
**kwargs: Keys to match in the message with their corresponding values.
You must pass at least one keyword argument so there is something
to look for.
Returns:
awaitable: The response
"""
if len(kwargs) == 0:
raise ArgumentError("You must specify at least one message field to wait on")
spec = MessageSpec(**kwargs)
future = self._add_waiter(spec)
future.add_done_callback(lambda x: self._remove_waiter(spec, future))
return asyncio.wait_for(future, timeout=timeout) | [
"def",
"wait_for",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"==",
"0",
":",
"raise",
"ArgumentError",
"(",
"\"You must specify at least one message field to wait on\"",
")",
"spec",
"=",
"Message... | Wait for a specific matching message or timeout.
You specify the message by passing name=value keyword arguments to
this method. The first message received after this function has been
called that has all of the given keys with the given values will be
returned when this function is awaited.
If no matching message is received within the specified timeout (if
given), then asyncio.TimeoutError will be raised.
This function only matches a single message and removes itself once
the message is seen or the timeout expires.
Args:
timeout (float): Optional timeout, defaults to None for no timeout.
**kwargs: Keys to match in the message with their corresponding values.
You must pass at least one keyword argument so there is something
to look for.
Returns:
awaitable: The response | [
"Wait",
"for",
"a",
"specific",
"matching",
"message",
"or",
"timeout",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L229-L260 | train |
iotile/coretools | iotilecore/iotile/core/utilities/async_tools/operation_manager.py | OperationManager.process_message | async def process_message(self, message, wait=True):
"""Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method returns False if the message matched no waiters so it was
ignored.
Normally you want to use wait=True (the default behavior) to guarantee
that all callbacks have finished before this method returns. However,
sometimes that can cause a deadlock if those callbacks would
themselves invoke behavior that requires whatever is waiting for this
method to be alive. In that case you can pass wait=False to ensure
that the caller of this method does not block.
Args:
message (dict or object): The message that we should process
wait (bool): Whether to block until all callbacks have finished
or to return once the callbacks have been launched.
Returns:
bool: True if at least one waiter matched, otherwise False.
"""
to_check = deque([self._waiters])
ignored = True
while len(to_check) > 0:
context = to_check.popleft()
waiters = context.get(OperationManager._LEAF, [])
for waiter in waiters:
if isinstance(waiter, asyncio.Future):
waiter.set_result(message)
else:
try:
await _wait_or_launch(self._loop, waiter, message, wait)
except: #pylint:disable=bare-except;We can't let a user callback break this routine
self._logger.warning("Error calling every_match callback, callback=%s, message=%s",
waiter, message, exc_info=True)
ignored = False
for key in context:
if key is OperationManager._LEAF:
continue
message_val = _get_key(message, key)
if message_val is _MISSING:
continue
next_level = context[key]
if message_val in next_level:
to_check.append(next_level[message_val])
return not ignored | python | async def process_message(self, message, wait=True):
"""Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method returns False if the message matched no waiters so it was
ignored.
Normally you want to use wait=True (the default behavior) to guarantee
that all callbacks have finished before this method returns. However,
sometimes that can cause a deadlock if those callbacks would
themselves invoke behavior that requires whatever is waiting for this
method to be alive. In that case you can pass wait=False to ensure
that the caller of this method does not block.
Args:
message (dict or object): The message that we should process
wait (bool): Whether to block until all callbacks have finished
or to return once the callbacks have been launched.
Returns:
bool: True if at least one waiter matched, otherwise False.
"""
to_check = deque([self._waiters])
ignored = True
while len(to_check) > 0:
context = to_check.popleft()
waiters = context.get(OperationManager._LEAF, [])
for waiter in waiters:
if isinstance(waiter, asyncio.Future):
waiter.set_result(message)
else:
try:
await _wait_or_launch(self._loop, waiter, message, wait)
except: #pylint:disable=bare-except;We can't let a user callback break this routine
self._logger.warning("Error calling every_match callback, callback=%s, message=%s",
waiter, message, exc_info=True)
ignored = False
for key in context:
if key is OperationManager._LEAF:
continue
message_val = _get_key(message, key)
if message_val is _MISSING:
continue
next_level = context[key]
if message_val in next_level:
to_check.append(next_level[message_val])
return not ignored | [
"async",
"def",
"process_message",
"(",
"self",
",",
"message",
",",
"wait",
"=",
"True",
")",
":",
"to_check",
"=",
"deque",
"(",
"[",
"self",
".",
"_waiters",
"]",
")",
"ignored",
"=",
"True",
"while",
"len",
"(",
"to_check",
")",
">",
"0",
":",
... | Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method returns False if the message matched no waiters so it was
ignored.
Normally you want to use wait=True (the default behavior) to guarantee
that all callbacks have finished before this method returns. However,
sometimes that can cause a deadlock if those callbacks would
themselves invoke behavior that requires whatever is waiting for this
method to be alive. In that case you can pass wait=False to ensure
that the caller of this method does not block.
Args:
message (dict or object): The message that we should process
wait (bool): Whether to block until all callbacks have finished
or to return once the callbacks have been launched.
Returns:
bool: True if at least one waiter matched, otherwise False. | [
"Process",
"a",
"message",
"to",
"see",
"if",
"it",
"wakes",
"any",
"waiters",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/async_tools/operation_manager.py#L262-L319 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/zip.py | generate | def generate(env):
"""Add Builders and construction variables for zip to an Environment."""
try:
bld = env['BUILDERS']['Zip']
except KeyError:
bld = ZipBuilder
env['BUILDERS']['Zip'] = bld
env['ZIP'] = 'zip'
env['ZIPFLAGS'] = SCons.Util.CLVar('')
env['ZIPCOM'] = zipAction
env['ZIPCOMPRESSION'] = zipcompression
env['ZIPSUFFIX'] = '.zip'
env['ZIPROOT'] = SCons.Util.CLVar('') | python | def generate(env):
"""Add Builders and construction variables for zip to an Environment."""
try:
bld = env['BUILDERS']['Zip']
except KeyError:
bld = ZipBuilder
env['BUILDERS']['Zip'] = bld
env['ZIP'] = 'zip'
env['ZIPFLAGS'] = SCons.Util.CLVar('')
env['ZIPCOM'] = zipAction
env['ZIPCOMPRESSION'] = zipcompression
env['ZIPSUFFIX'] = '.zip'
env['ZIPROOT'] = SCons.Util.CLVar('') | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Zip'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"ZipBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Zip'",
"]",
"=",
"bld",
"env",
"[",
"'ZIP'... | Add Builders and construction variables for zip to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"zip",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/zip.py#L70-L83 | train |
iotile/coretools | iotilecore/iotile/core/scripts/virtualdev_script.py | one_line_desc | def one_line_desc(obj):
"""Get a one line description of a class."""
logger = logging.getLogger(__name__)
try:
doc = ParsedDocstring(obj.__doc__)
return doc.short_desc
except: # pylint:disable=bare-except; We don't want a misbehaving exception to break the program
logger.warning("Could not parse docstring for %s", obj, exc_info=True)
return "" | python | def one_line_desc(obj):
"""Get a one line description of a class."""
logger = logging.getLogger(__name__)
try:
doc = ParsedDocstring(obj.__doc__)
return doc.short_desc
except: # pylint:disable=bare-except; We don't want a misbehaving exception to break the program
logger.warning("Could not parse docstring for %s", obj, exc_info=True)
return "" | [
"def",
"one_line_desc",
"(",
"obj",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"doc",
"=",
"ParsedDocstring",
"(",
"obj",
".",
"__doc__",
")",
"return",
"doc",
".",
"short_desc",
"except",
":",
"logger",
".",
... | Get a one line description of a class. | [
"Get",
"a",
"one",
"line",
"description",
"of",
"a",
"class",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L16-L26 | train |
iotile/coretools | iotilecore/iotile/core/scripts/virtualdev_script.py | instantiate_device | def instantiate_device(virtual_dev, config, loop):
"""Find a virtual device by name and instantiate it
Args:
virtual_dev (string): The name of the pkg_resources entry point corresponding to
the device. It should be in group iotile.virtual_device. If virtual_dev ends
in .py, it is interpreted as a python script and loaded directly from the script.
config (dict): A dictionary with a 'device' key with the config info for configuring
this virtual device. This is optional.
Returns:
VirtualIOTileDevice: The instantiated subclass of VirtualIOTileDevice
"""
conf = {}
if 'device' in config:
conf = config['device']
# If we're given a path to a script, try to load and use that rather than search for an installed module
try:
reg = ComponentRegistry()
if virtual_dev.endswith('.py'):
_name, dev = reg.load_extension(virtual_dev, class_filter=VirtualIOTileDevice, unique=True)
else:
_name, dev = reg.load_extensions('iotile.virtual_device', name_filter=virtual_dev,
class_filter=VirtualIOTileDevice,
product_name="virtual_device", unique=True)
return dev(conf)
except ArgumentError as err:
print("ERROR: Could not load virtual device (%s): %s" % (virtual_dev, err.msg))
sys.exit(1) | python | def instantiate_device(virtual_dev, config, loop):
"""Find a virtual device by name and instantiate it
Args:
virtual_dev (string): The name of the pkg_resources entry point corresponding to
the device. It should be in group iotile.virtual_device. If virtual_dev ends
in .py, it is interpreted as a python script and loaded directly from the script.
config (dict): A dictionary with a 'device' key with the config info for configuring
this virtual device. This is optional.
Returns:
VirtualIOTileDevice: The instantiated subclass of VirtualIOTileDevice
"""
conf = {}
if 'device' in config:
conf = config['device']
# If we're given a path to a script, try to load and use that rather than search for an installed module
try:
reg = ComponentRegistry()
if virtual_dev.endswith('.py'):
_name, dev = reg.load_extension(virtual_dev, class_filter=VirtualIOTileDevice, unique=True)
else:
_name, dev = reg.load_extensions('iotile.virtual_device', name_filter=virtual_dev,
class_filter=VirtualIOTileDevice,
product_name="virtual_device", unique=True)
return dev(conf)
except ArgumentError as err:
print("ERROR: Could not load virtual device (%s): %s" % (virtual_dev, err.msg))
sys.exit(1) | [
"def",
"instantiate_device",
"(",
"virtual_dev",
",",
"config",
",",
"loop",
")",
":",
"conf",
"=",
"{",
"}",
"if",
"'device'",
"in",
"config",
":",
"conf",
"=",
"config",
"[",
"'device'",
"]",
"try",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"if... | Find a virtual device by name and instantiate it
Args:
virtual_dev (string): The name of the pkg_resources entry point corresponding to
the device. It should be in group iotile.virtual_device. If virtual_dev ends
in .py, it is interpreted as a python script and loaded directly from the script.
config (dict): A dictionary with a 'device' key with the config info for configuring
this virtual device. This is optional.
Returns:
VirtualIOTileDevice: The instantiated subclass of VirtualIOTileDevice | [
"Find",
"a",
"virtual",
"device",
"by",
"name",
"and",
"instantiate",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L165-L196 | train |
iotile/coretools | iotilecore/iotile/core/scripts/virtualdev_script.py | instantiate_interface | def instantiate_interface(virtual_iface, config, loop):
"""Find a virtual interface by name and instantiate it
Args:
virtual_iface (string): The name of the pkg_resources entry point corresponding to
the interface. It should be in group iotile.virtual_interface
config (dict): A dictionary with a 'interface' key with the config info for configuring
this virtual interface. This is optional.
Returns:
VirtualInterface: The instantiated subclass of VirtualInterface
"""
# Allow the null virtual interface for testing
if virtual_iface == 'null':
return StandardDeviceServer(None, {}, loop=loop)
conf = {}
if 'interface' in config:
conf = config['interface']
try:
reg = ComponentRegistry()
if virtual_iface.endswith('.py'):
_name, iface = reg.load_extension(virtual_iface, class_filter=AbstractDeviceServer, unique=True)
else:
_name, iface = reg.load_extensions('iotile.device_server', name_filter=virtual_iface,
class_filter=AbstractDeviceServer, unique=True)
return iface(None, conf, loop=loop)
except ArgumentError as err:
print("ERROR: Could not load device_server (%s): %s" % (virtual_iface, err.msg))
sys.exit(1) | python | def instantiate_interface(virtual_iface, config, loop):
"""Find a virtual interface by name and instantiate it
Args:
virtual_iface (string): The name of the pkg_resources entry point corresponding to
the interface. It should be in group iotile.virtual_interface
config (dict): A dictionary with a 'interface' key with the config info for configuring
this virtual interface. This is optional.
Returns:
VirtualInterface: The instantiated subclass of VirtualInterface
"""
# Allow the null virtual interface for testing
if virtual_iface == 'null':
return StandardDeviceServer(None, {}, loop=loop)
conf = {}
if 'interface' in config:
conf = config['interface']
try:
reg = ComponentRegistry()
if virtual_iface.endswith('.py'):
_name, iface = reg.load_extension(virtual_iface, class_filter=AbstractDeviceServer, unique=True)
else:
_name, iface = reg.load_extensions('iotile.device_server', name_filter=virtual_iface,
class_filter=AbstractDeviceServer, unique=True)
return iface(None, conf, loop=loop)
except ArgumentError as err:
print("ERROR: Could not load device_server (%s): %s" % (virtual_iface, err.msg))
sys.exit(1) | [
"def",
"instantiate_interface",
"(",
"virtual_iface",
",",
"config",
",",
"loop",
")",
":",
"if",
"virtual_iface",
"==",
"'null'",
":",
"return",
"StandardDeviceServer",
"(",
"None",
",",
"{",
"}",
",",
"loop",
"=",
"loop",
")",
"conf",
"=",
"{",
"}",
"i... | Find a virtual interface by name and instantiate it
Args:
virtual_iface (string): The name of the pkg_resources entry point corresponding to
the interface. It should be in group iotile.virtual_interface
config (dict): A dictionary with a 'interface' key with the config info for configuring
this virtual interface. This is optional.
Returns:
VirtualInterface: The instantiated subclass of VirtualInterface | [
"Find",
"a",
"virtual",
"interface",
"by",
"name",
"and",
"instantiate",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/scripts/virtualdev_script.py#L199-L231 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tar.py | generate | def generate(env):
"""Add Builders and construction variables for tar to an Environment."""
try:
bld = env['BUILDERS']['Tar']
except KeyError:
bld = TarBuilder
env['BUILDERS']['Tar'] = bld
env['TAR'] = env.Detect(tars) or 'gtar'
env['TARFLAGS'] = SCons.Util.CLVar('-c')
env['TARCOM'] = '$TAR $TARFLAGS -f $TARGET $SOURCES'
env['TARSUFFIX'] = '.tar' | python | def generate(env):
"""Add Builders and construction variables for tar to an Environment."""
try:
bld = env['BUILDERS']['Tar']
except KeyError:
bld = TarBuilder
env['BUILDERS']['Tar'] = bld
env['TAR'] = env.Detect(tars) or 'gtar'
env['TARFLAGS'] = SCons.Util.CLVar('-c')
env['TARCOM'] = '$TAR $TARFLAGS -f $TARGET $SOURCES'
env['TARSUFFIX'] = '.tar' | [
"def",
"generate",
"(",
"env",
")",
":",
"try",
":",
"bld",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Tar'",
"]",
"except",
"KeyError",
":",
"bld",
"=",
"TarBuilder",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'Tar'",
"]",
"=",
"bld",
"env",
"[",
"'TAR'... | Add Builders and construction variables for tar to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"tar",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/tar.py#L53-L64 | train |
iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer.register_command | def register_command(self, name, handler, validator):
"""Register a coroutine command handler.
This handler will be called whenever a command message is received
from the client, whose operation key matches ``name``. The handler
will be called as::
response_payload = await handler(cmd_payload, context)
If the coroutine returns, it will be assumed to have completed
correctly and its return value will be sent as the result of the
command. If the coroutine wishes to signal an error handling the
command, it must raise a ServerCommandError exception that contains a
string reason code for the error. This will generate an error
response to the command.
The cmd_payload is first verified using the SchemaVerifier passed in
``validator`` and handler is only called if verification succeeds. If
verification fails, a failure response to the command is returned
automatically to the client.
Args:
name (str): The unique command name that will be used to dispatch
client command messages to this handler.
handler (coroutine function): A coroutine function that will be
called whenever this command is received.
validator (SchemaVerifier): A validator object for checking the
command payload before calling this handler.
"""
self._commands[name] = (handler, validator) | python | def register_command(self, name, handler, validator):
"""Register a coroutine command handler.
This handler will be called whenever a command message is received
from the client, whose operation key matches ``name``. The handler
will be called as::
response_payload = await handler(cmd_payload, context)
If the coroutine returns, it will be assumed to have completed
correctly and its return value will be sent as the result of the
command. If the coroutine wishes to signal an error handling the
command, it must raise a ServerCommandError exception that contains a
string reason code for the error. This will generate an error
response to the command.
The cmd_payload is first verified using the SchemaVerifier passed in
``validator`` and handler is only called if verification succeeds. If
verification fails, a failure response to the command is returned
automatically to the client.
Args:
name (str): The unique command name that will be used to dispatch
client command messages to this handler.
handler (coroutine function): A coroutine function that will be
called whenever this command is received.
validator (SchemaVerifier): A validator object for checking the
command payload before calling this handler.
"""
self._commands[name] = (handler, validator) | [
"def",
"register_command",
"(",
"self",
",",
"name",
",",
"handler",
",",
"validator",
")",
":",
"self",
".",
"_commands",
"[",
"name",
"]",
"=",
"(",
"handler",
",",
"validator",
")"
] | Register a coroutine command handler.
This handler will be called whenever a command message is received
from the client, whose operation key matches ``name``. The handler
will be called as::
response_payload = await handler(cmd_payload, context)
If the coroutine returns, it will be assumed to have completed
correctly and its return value will be sent as the result of the
command. If the coroutine wishes to signal an error handling the
command, it must raise a ServerCommandError exception that contains a
string reason code for the error. This will generate an error
response to the command.
The cmd_payload is first verified using the SchemaVerifier passed in
``validator`` and handler is only called if verification succeeds. If
verification fails, a failure response to the command is returned
automatically to the client.
Args:
name (str): The unique command name that will be used to dispatch
client command messages to this handler.
handler (coroutine function): A coroutine function that will be
called whenever this command is received.
validator (SchemaVerifier): A validator object for checking the
command payload before calling this handler. | [
"Register",
"a",
"coroutine",
"command",
"handler",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L95-L125 | train |
iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer.start | async def start(self):
"""Start the websocket server.
When this method returns, the websocket server will be running and
the port property of this class will have its assigned port number.
This method should be called only once in the lifetime of the server
and must be paired with a call to stop() to cleanly release the
server's resources.
"""
if self._server_task is not None:
self._logger.debug("AsyncValidatingWSServer.start() called twice, ignoring")
return
started_signal = self._loop.create_future()
self._server_task = self._loop.add_task(self._run_server_task(started_signal))
await started_signal
if self.port is None:
self.port = started_signal.result() | python | async def start(self):
"""Start the websocket server.
When this method returns, the websocket server will be running and
the port property of this class will have its assigned port number.
This method should be called only once in the lifetime of the server
and must be paired with a call to stop() to cleanly release the
server's resources.
"""
if self._server_task is not None:
self._logger.debug("AsyncValidatingWSServer.start() called twice, ignoring")
return
started_signal = self._loop.create_future()
self._server_task = self._loop.add_task(self._run_server_task(started_signal))
await started_signal
if self.port is None:
self.port = started_signal.result() | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server_task",
"is",
"not",
"None",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"AsyncValidatingWSServer.start() called twice, ignoring\"",
")",
"return",
"started_signal",
"=",
"self",
".... | Start the websocket server.
When this method returns, the websocket server will be running and
the port property of this class will have its assigned port number.
This method should be called only once in the lifetime of the server
and must be paired with a call to stop() to cleanly release the
server's resources. | [
"Start",
"the",
"websocket",
"server",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L127-L148 | train |
iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer._run_server_task | async def _run_server_task(self, started_signal):
"""Create a BackgroundTask to manage the server.
This allows subclasess to attach their server related tasks as
subtasks that are properly cleaned up when this parent task is
stopped and not require them all to overload start() and stop()
to perform this action.
"""
try:
server = await websockets.serve(self._manage_connection, self.host, self.port)
port = server.sockets[0].getsockname()[1]
started_signal.set_result(port)
except Exception as err:
self._logger.exception("Error starting server on host %s, port %s", self.host, self.port)
started_signal.set_exception(err)
return
try:
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
self._logger.info("Stopping server due to stop() command")
finally:
server.close()
await server.wait_closed()
self._logger.debug("Server stopped, exiting task") | python | async def _run_server_task(self, started_signal):
"""Create a BackgroundTask to manage the server.
This allows subclasess to attach their server related tasks as
subtasks that are properly cleaned up when this parent task is
stopped and not require them all to overload start() and stop()
to perform this action.
"""
try:
server = await websockets.serve(self._manage_connection, self.host, self.port)
port = server.sockets[0].getsockname()[1]
started_signal.set_result(port)
except Exception as err:
self._logger.exception("Error starting server on host %s, port %s", self.host, self.port)
started_signal.set_exception(err)
return
try:
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
self._logger.info("Stopping server due to stop() command")
finally:
server.close()
await server.wait_closed()
self._logger.debug("Server stopped, exiting task") | [
"async",
"def",
"_run_server_task",
"(",
"self",
",",
"started_signal",
")",
":",
"try",
":",
"server",
"=",
"await",
"websockets",
".",
"serve",
"(",
"self",
".",
"_manage_connection",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"port",
"="... | Create a BackgroundTask to manage the server.
This allows subclasess to attach their server related tasks as
subtasks that are properly cleaned up when this parent task is
stopped and not require them all to overload start() and stop()
to perform this action. | [
"Create",
"a",
"BackgroundTask",
"to",
"manage",
"the",
"server",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L150-L177 | train |
iotile/coretools | transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py | AsyncValidatingWSServer.send_event | async def send_event(self, con, name, payload):
"""Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the client has
connected and passed to self.prepare_conn(connection).
Args:
con (websockets.Connection): The connection to use to send
the event.
name (str): The name of the event to send.
payload (object): The msgpack-serializable object so send
as the event's payload.
"""
message = dict(type="event", name=name, payload=payload)
encoded = pack(message)
await con.send(encoded) | python | async def send_event(self, con, name, payload):
"""Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the client has
connected and passed to self.prepare_conn(connection).
Args:
con (websockets.Connection): The connection to use to send
the event.
name (str): The name of the event to send.
payload (object): The msgpack-serializable object so send
as the event's payload.
"""
message = dict(type="event", name=name, payload=payload)
encoded = pack(message)
await con.send(encoded) | [
"async",
"def",
"send_event",
"(",
"self",
",",
"con",
",",
"name",
",",
"payload",
")",
":",
"message",
"=",
"dict",
"(",
"type",
"=",
"\"event\"",
",",
"name",
"=",
"name",
",",
"payload",
"=",
"payload",
")",
"encoded",
"=",
"pack",
"(",
"message"... | Send an event to a client connection.
This method will push an event message to the client with the given
name and payload. You need to have access to the the ``connection``
object for the client, which is only available once the client has
connected and passed to self.prepare_conn(connection).
Args:
con (websockets.Connection): The connection to use to send
the event.
name (str): The name of the event to send.
payload (object): The msgpack-serializable object so send
as the event's payload. | [
"Send",
"an",
"event",
"to",
"a",
"client",
"connection",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/websocket/iotile_transport_websocket/generic/async_server.py#L191-L209 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | DviPdfPsFunction | def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None):
"""A builder for DVI files that sets the TEXPICTS environment
variable before running dvi2ps or dvipdf."""
try:
abspath = source[0].attributes.path
except AttributeError :
abspath = ''
saved_env = SCons.Scanner.LaTeX.modify_env_var(env, 'TEXPICTS', abspath)
result = XXXDviAction(target, source, env)
if saved_env is _null:
try:
del env['ENV']['TEXPICTS']
except KeyError:
pass # was never set
else:
env['ENV']['TEXPICTS'] = saved_env
return result | python | def DviPdfPsFunction(XXXDviAction, target = None, source= None, env=None):
"""A builder for DVI files that sets the TEXPICTS environment
variable before running dvi2ps or dvipdf."""
try:
abspath = source[0].attributes.path
except AttributeError :
abspath = ''
saved_env = SCons.Scanner.LaTeX.modify_env_var(env, 'TEXPICTS', abspath)
result = XXXDviAction(target, source, env)
if saved_env is _null:
try:
del env['ENV']['TEXPICTS']
except KeyError:
pass # was never set
else:
env['ENV']['TEXPICTS'] = saved_env
return result | [
"def",
"DviPdfPsFunction",
"(",
"XXXDviAction",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"try",
":",
"abspath",
"=",
"source",
"[",
"0",
"]",
".",
"attributes",
".",
"path",
"except",
"AttributeError",
... | A builder for DVI files that sets the TEXPICTS environment
variable before running dvi2ps or dvipdf. | [
"A",
"builder",
"for",
"DVI",
"files",
"that",
"sets",
"the",
"TEXPICTS",
"environment",
"variable",
"before",
"running",
"dvi2ps",
"or",
"dvipdf",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L43-L64 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | PDFEmitter | def PDFEmitter(target, source, env):
"""Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file.
"""
def strip_suffixes(n):
return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log']
source = [src for src in source if strip_suffixes(src)]
return (target, source) | python | def PDFEmitter(target, source, env):
"""Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file.
"""
def strip_suffixes(n):
return not SCons.Util.splitext(str(n))[1] in ['.aux', '.log']
source = [src for src in source if strip_suffixes(src)]
return (target, source) | [
"def",
"PDFEmitter",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"def",
"strip_suffixes",
"(",
"n",
")",
":",
"return",
"not",
"SCons",
".",
"Util",
".",
"splitext",
"(",
"str",
"(",
"n",
")",
")",
"[",
"1",
"]",
"in",
"[",
"'.aux'",
",",... | Strips any .aux or .log files from the input source list.
These are created by the TeX Builder that in all likelihood was
used to generate the .dvi file we're using as input, and we only
care about the .dvi file. | [
"Strips",
"any",
".",
"aux",
"or",
".",
"log",
"files",
"from",
"the",
"input",
"source",
"list",
".",
"These",
"are",
"created",
"by",
"the",
"TeX",
"Builder",
"that",
"in",
"all",
"likelihood",
"was",
"used",
"to",
"generate",
"the",
".",
"dvi",
"fil... | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L82-L91 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py | generate | def generate(env):
"""Add Builders and construction variables for dvipdf to an Environment."""
global PDFAction
if PDFAction is None:
PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR')
global DVIPDFAction
if DVIPDFAction is None:
DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.dvi', DVIPDFAction)
bld.add_emitter('.dvi', PDFEmitter)
env['DVIPDF'] = 'dvipdf'
env['DVIPDFFLAGS'] = SCons.Util.CLVar('')
env['DVIPDFCOM'] = 'cd ${TARGET.dir} && $DVIPDF $DVIPDFFLAGS ${SOURCE.file} ${TARGET.file}'
# Deprecated synonym.
env['PDFCOM'] = ['$DVIPDFCOM'] | python | def generate(env):
"""Add Builders and construction variables for dvipdf to an Environment."""
global PDFAction
if PDFAction is None:
PDFAction = SCons.Action.Action('$DVIPDFCOM', '$DVIPDFCOMSTR')
global DVIPDFAction
if DVIPDFAction is None:
DVIPDFAction = SCons.Action.Action(DviPdfFunction, strfunction = DviPdfStrFunction)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.dvi', DVIPDFAction)
bld.add_emitter('.dvi', PDFEmitter)
env['DVIPDF'] = 'dvipdf'
env['DVIPDFFLAGS'] = SCons.Util.CLVar('')
env['DVIPDFCOM'] = 'cd ${TARGET.dir} && $DVIPDF $DVIPDFFLAGS ${SOURCE.file} ${TARGET.file}'
# Deprecated synonym.
env['PDFCOM'] = ['$DVIPDFCOM'] | [
"def",
"generate",
"(",
"env",
")",
":",
"global",
"PDFAction",
"if",
"PDFAction",
"is",
"None",
":",
"PDFAction",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$DVIPDFCOM'",
",",
"'$DVIPDFCOMSTR'",
")",
"global",
"DVIPDFAction",
"if",
"DVIPDFAction",
"... | Add Builders and construction variables for dvipdf to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"dvipdf",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L93-L115 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/sim/stop_conditions.py | TimeBasedStopCondition.FromString | def FromString(cls, desc):
"""Parse this stop condition from a string representation.
The string needs to match:
run_time number [seconds|minutes|hours|days|months|years]
Args:
desc (str): The description
Returns:
TimeBasedStopCondition
"""
parse_exp = Literal(u'run_time').suppress() + time_interval(u'interval')
try:
data = parse_exp.parseString(desc)
return TimeBasedStopCondition(data[u'interval'][0])
except ParseException:
raise ArgumentError(u"Could not parse time based stop condition") | python | def FromString(cls, desc):
"""Parse this stop condition from a string representation.
The string needs to match:
run_time number [seconds|minutes|hours|days|months|years]
Args:
desc (str): The description
Returns:
TimeBasedStopCondition
"""
parse_exp = Literal(u'run_time').suppress() + time_interval(u'interval')
try:
data = parse_exp.parseString(desc)
return TimeBasedStopCondition(data[u'interval'][0])
except ParseException:
raise ArgumentError(u"Could not parse time based stop condition") | [
"def",
"FromString",
"(",
"cls",
",",
"desc",
")",
":",
"parse_exp",
"=",
"Literal",
"(",
"u'run_time'",
")",
".",
"suppress",
"(",
")",
"+",
"time_interval",
"(",
"u'interval'",
")",
"try",
":",
"data",
"=",
"parse_exp",
".",
"parseString",
"(",
"desc",... | Parse this stop condition from a string representation.
The string needs to match:
run_time number [seconds|minutes|hours|days|months|years]
Args:
desc (str): The description
Returns:
TimeBasedStopCondition | [
"Parse",
"this",
"stop",
"condition",
"from",
"a",
"string",
"representation",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/sim/stop_conditions.py#L95-L114 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | collectintargz | def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is changed
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the source list for.
sources = [s for s in sources if s not in target]
# find the .spec file for rpm and add it since it is not necessarily found
# by the FindSourceFiles function.
sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
# sort to keep sources from changing order across builds
sources.sort()
# as the source contains the url of the source package this rpm package
# is built from, we extract the target name
tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
try:
tarball = env['SOURCE_URL'].split('/')[-1]
except KeyError as e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
PACKAGEROOT=env['PACKAGEROOT'], )
return (target, tarball) | python | def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is changed
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the source list for.
sources = [s for s in sources if s not in target]
# find the .spec file for rpm and add it since it is not necessarily found
# by the FindSourceFiles function.
sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
# sort to keep sources from changing order across builds
sources.sort()
# as the source contains the url of the source package this rpm package
# is built from, we extract the target name
tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
try:
tarball = env['SOURCE_URL'].split('/')[-1]
except KeyError as e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
PACKAGEROOT=env['PACKAGEROOT'], )
return (target, tarball) | [
"def",
"collectintargz",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"sources",
"=",
"env",
".",
"FindSourceFiles",
"(",
")",
"sources",
"=",
"[",
"s",
"for",
"s",
"in",
"sources",
"if",
"s",
"not",
"in",
"target",
"]",
"sources",
".",
"exten... | Puts all source files into a tar.gz file. | [
"Puts",
"all",
"source",
"files",
"into",
"a",
"tar",
".",
"gz",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L86-L112 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile | def build_specfile(target, source, env):
""" Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes.
"""
file = open(target[0].get_abspath(), 'w')
try:
file.write( build_specfile_header(env) )
file.write( build_specfile_sections(env) )
file.write( build_specfile_filesection(env, source) )
file.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
except KeyError as e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] ) | python | def build_specfile(target, source, env):
""" Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes.
"""
file = open(target[0].get_abspath(), 'w')
try:
file.write( build_specfile_header(env) )
file.write( build_specfile_sections(env) )
file.write( build_specfile_filesection(env, source) )
file.close()
# call a user specified function
if 'CHANGE_SPECFILE' in env:
env['CHANGE_SPECFILE'](target, source)
except KeyError as e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] ) | [
"def",
"build_specfile",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"file",
"=",
"open",
"(",
"target",
"[",
"0",
"]",
".",
"get_abspath",
"(",
")",
",",
"'w'",
")",
"try",
":",
"file",
".",
"write",
"(",
"build_specfile_header",
"(",
"env",... | Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes. | [
"Builds",
"a",
"RPM",
"specfile",
"from",
"a",
"dictionary",
"with",
"string",
"metadata",
"and",
"by",
"analyzing",
"a",
"tree",
"of",
"nodes",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L125-L142 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile_sections | def build_specfile_sections(spec):
""" Builds the sections of a rpm specfile.
"""
str = ""
mandatory_sections = {
'DESCRIPTION' : '\n%%description\n%s\n\n', }
str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
optional_sections = {
'DESCRIPTION_' : '%%description -l %s\n%s\n\n',
'CHANGELOG' : '%%changelog\n%s\n\n',
'X_RPM_PREINSTALL' : '%%pre\n%s\n\n',
'X_RPM_POSTINSTALL' : '%%post\n%s\n\n',
'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n',
'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n',
'X_RPM_VERIFY' : '%%verify\n%s\n\n',
# These are for internal use but could possibly be overridden
'X_RPM_PREP' : '%%prep\n%s\n\n',
'X_RPM_BUILD' : '%%build\n%s\n\n',
'X_RPM_INSTALL' : '%%install\n%s\n\n',
'X_RPM_CLEAN' : '%%clean\n%s\n\n',
}
# Default prep, build, install and clean rules
# TODO: optimize those build steps, to not compile the project a second time
if 'X_RPM_PREP' not in spec:
spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q'
if 'X_RPM_BUILD' not in spec:
spec['X_RPM_BUILD'] = '[ ! -e "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && mkdir "$RPM_BUILD_ROOT"'
if 'X_RPM_INSTALL' not in spec:
spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"'
if 'X_RPM_CLEAN' not in spec:
spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"'
str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec )
return str | python | def build_specfile_sections(spec):
""" Builds the sections of a rpm specfile.
"""
str = ""
mandatory_sections = {
'DESCRIPTION' : '\n%%description\n%s\n\n', }
str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
optional_sections = {
'DESCRIPTION_' : '%%description -l %s\n%s\n\n',
'CHANGELOG' : '%%changelog\n%s\n\n',
'X_RPM_PREINSTALL' : '%%pre\n%s\n\n',
'X_RPM_POSTINSTALL' : '%%post\n%s\n\n',
'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n',
'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n',
'X_RPM_VERIFY' : '%%verify\n%s\n\n',
# These are for internal use but could possibly be overridden
'X_RPM_PREP' : '%%prep\n%s\n\n',
'X_RPM_BUILD' : '%%build\n%s\n\n',
'X_RPM_INSTALL' : '%%install\n%s\n\n',
'X_RPM_CLEAN' : '%%clean\n%s\n\n',
}
# Default prep, build, install and clean rules
# TODO: optimize those build steps, to not compile the project a second time
if 'X_RPM_PREP' not in spec:
spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q'
if 'X_RPM_BUILD' not in spec:
spec['X_RPM_BUILD'] = '[ ! -e "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && mkdir "$RPM_BUILD_ROOT"'
if 'X_RPM_INSTALL' not in spec:
spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"'
if 'X_RPM_CLEAN' not in spec:
spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"'
str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec )
return str | [
"def",
"build_specfile_sections",
"(",
"spec",
")",
":",
"str",
"=",
"\"\"",
"mandatory_sections",
"=",
"{",
"'DESCRIPTION'",
":",
"'\\n%%description\\n%s\\n\\n'",
",",
"}",
"str",
"=",
"str",
"+",
"SimpleTagCompiler",
"(",
"mandatory_sections",
")",
".",
"compile... | Builds the sections of a rpm specfile. | [
"Builds",
"the",
"sections",
"of",
"a",
"rpm",
"specfile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L148-L190 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile_header | def build_specfile_header(spec):
""" Builds all sections but the %file of a rpm specfile
"""
str = ""
# first the mandatory sections
mandatory_header_fields = {
'NAME' : '%%define name %s\nName: %%{name}\n',
'VERSION' : '%%define version %s\nVersion: %%{version}\n',
'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
'X_RPM_GROUP' : 'Group: %s\n',
'SUMMARY' : 'Summary: %s\n',
'LICENSE' : 'License: %s\n', }
str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )
# now the optional tags
optional_header_fields = {
'VENDOR' : 'Vendor: %s\n',
'X_RPM_URL' : 'Url: %s\n',
'SOURCE_URL' : 'Source: %s\n',
'SUMMARY_' : 'Summary(%s): %s\n',
'X_RPM_DISTRIBUTION' : 'Distribution: %s\n',
'X_RPM_ICON' : 'Icon: %s\n',
'X_RPM_PACKAGER' : 'Packager: %s\n',
'X_RPM_GROUP_' : 'Group(%s): %s\n',
'X_RPM_REQUIRES' : 'Requires: %s\n',
'X_RPM_PROVIDES' : 'Provides: %s\n',
'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',
'X_RPM_SERIAL' : 'Serial: %s\n',
'X_RPM_EPOCH' : 'Epoch: %s\n',
'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n',
'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n',
'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
'X_RPM_PREFIX' : 'Prefix: %s\n',
# internal use
'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', }
# fill in default values:
# Adding a BuildRequires renders the .rpm unbuildable under System, which
# are not managed by rpm, since the database to resolve this dependency is
# missing (take Gentoo as an example)
# if not s.has_key('x_rpm_BuildRequires'):
# s['x_rpm_BuildRequires'] = 'scons'
if 'X_RPM_BUILDROOT' not in spec:
spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'
str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
return str | python | def build_specfile_header(spec):
""" Builds all sections but the %file of a rpm specfile
"""
str = ""
# first the mandatory sections
mandatory_header_fields = {
'NAME' : '%%define name %s\nName: %%{name}\n',
'VERSION' : '%%define version %s\nVersion: %%{version}\n',
'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
'X_RPM_GROUP' : 'Group: %s\n',
'SUMMARY' : 'Summary: %s\n',
'LICENSE' : 'License: %s\n', }
str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )
# now the optional tags
optional_header_fields = {
'VENDOR' : 'Vendor: %s\n',
'X_RPM_URL' : 'Url: %s\n',
'SOURCE_URL' : 'Source: %s\n',
'SUMMARY_' : 'Summary(%s): %s\n',
'X_RPM_DISTRIBUTION' : 'Distribution: %s\n',
'X_RPM_ICON' : 'Icon: %s\n',
'X_RPM_PACKAGER' : 'Packager: %s\n',
'X_RPM_GROUP_' : 'Group(%s): %s\n',
'X_RPM_REQUIRES' : 'Requires: %s\n',
'X_RPM_PROVIDES' : 'Provides: %s\n',
'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',
'X_RPM_SERIAL' : 'Serial: %s\n',
'X_RPM_EPOCH' : 'Epoch: %s\n',
'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n',
'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n',
'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
'X_RPM_PREFIX' : 'Prefix: %s\n',
# internal use
'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', }
# fill in default values:
# Adding a BuildRequires renders the .rpm unbuildable under System, which
# are not managed by rpm, since the database to resolve this dependency is
# missing (take Gentoo as an example)
# if not s.has_key('x_rpm_BuildRequires'):
# s['x_rpm_BuildRequires'] = 'scons'
if 'X_RPM_BUILDROOT' not in spec:
spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'
str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
return str | [
"def",
"build_specfile_header",
"(",
"spec",
")",
":",
"str",
"=",
"\"\"",
"mandatory_header_fields",
"=",
"{",
"'NAME'",
":",
"'%%define name %s\\nName: %%{name}\\n'",
",",
"'VERSION'",
":",
"'%%define version %s\\nVersion: %%{version}\\n'",
",",
"'PACKAGEVERSION'",
":",
... | Builds all sections but the %file of a rpm specfile | [
"Builds",
"all",
"sections",
"but",
"the",
"%file",
"of",
"a",
"rpm",
"specfile"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L192-L245 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | build_specfile_filesection | def build_specfile_filesection(spec, files):
""" builds the %file section of the specfile
"""
str = '%files\n'
if 'X_RPM_DEFATTR' not in spec:
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' : '%%config %s',
'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
'PACKAGING_DOC' : '%%doc %s',
'PACKAGING_UNIX_ATTR' : '%%attr %s',
'PACKAGING_LANG_' : '%%lang(%s) %s',
'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
'PACKAGING_X_RPM_DIR' : '%%dir %s',
'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
for file in files:
# build the tagset
tags = {}
for k in list(supported_tags.keys()):
try:
v = file.GetTag(k)
if v:
tags[k] = v
except AttributeError:
pass
# compile the tagset
str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
str = str + ' '
str = str + file.GetTag('PACKAGING_INSTALL_LOCATION')
str = str + '\n\n'
return str | python | def build_specfile_filesection(spec, files):
""" builds the %file section of the specfile
"""
str = '%files\n'
if 'X_RPM_DEFATTR' not in spec:
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' : '%%config %s',
'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
'PACKAGING_DOC' : '%%doc %s',
'PACKAGING_UNIX_ATTR' : '%%attr %s',
'PACKAGING_LANG_' : '%%lang(%s) %s',
'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
'PACKAGING_X_RPM_DIR' : '%%dir %s',
'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
for file in files:
# build the tagset
tags = {}
for k in list(supported_tags.keys()):
try:
v = file.GetTag(k)
if v:
tags[k] = v
except AttributeError:
pass
# compile the tagset
str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
str = str + ' '
str = str + file.GetTag('PACKAGING_INSTALL_LOCATION')
str = str + '\n\n'
return str | [
"def",
"build_specfile_filesection",
"(",
"spec",
",",
"files",
")",
":",
"str",
"=",
"'%files\\n'",
"if",
"'X_RPM_DEFATTR'",
"not",
"in",
"spec",
":",
"spec",
"[",
"'X_RPM_DEFATTR'",
"]",
"=",
"'(-,root,root)'",
"str",
"=",
"str",
"+",
"'%%defattr %s\\n'",
"%... | builds the %file section of the specfile | [
"builds",
"the",
"%file",
"section",
"of",
"the",
"specfile"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L250-L289 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py | SimpleTagCompiler.compile | def compile(self, values):
""" Compiles the tagset and returns a str containing the result
"""
def is_international(tag):
return tag.endswith('_')
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
replacements = list(self.tagset.items())
str = ""
domestic = [t for t in replacements if not is_international(t[0])]
for key, replacement in domestic:
try:
str = str + replacement % values[key]
except KeyError as e:
if self.mandatory:
raise e
international = [t for t in replacements if is_international(t[0])]
for key, replacement in international:
try:
x = [t for t in values.items() if strip_country_code(t[0]) == key]
int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
for v in int_values_for_key:
str = str + replacement % v
except KeyError as e:
if self.mandatory:
raise e
return str | python | def compile(self, values):
""" Compiles the tagset and returns a str containing the result
"""
def is_international(tag):
return tag.endswith('_')
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
replacements = list(self.tagset.items())
str = ""
domestic = [t for t in replacements if not is_international(t[0])]
for key, replacement in domestic:
try:
str = str + replacement % values[key]
except KeyError as e:
if self.mandatory:
raise e
international = [t for t in replacements if is_international(t[0])]
for key, replacement in international:
try:
x = [t for t in values.items() if strip_country_code(t[0]) == key]
int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
for v in int_values_for_key:
str = str + replacement % v
except KeyError as e:
if self.mandatory:
raise e
return str | [
"def",
"compile",
"(",
"self",
",",
"values",
")",
":",
"def",
"is_international",
"(",
"tag",
")",
":",
"return",
"tag",
".",
"endswith",
"(",
"'_'",
")",
"def",
"get_country_code",
"(",
"tag",
")",
":",
"return",
"tag",
"[",
"-",
"2",
":",
"]",
"... | Compiles the tagset and returns a str containing the result | [
"Compiles",
"the",
"tagset",
"and",
"returns",
"a",
"str",
"containing",
"the",
"result"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/packaging/rpm.py#L309-L343 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifl.py | generate | def generate(env):
"""Add Builders and construction variables for ifl to an Environment."""
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['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)
env['FORTRAN'] = 'ifl'
env['SHFORTRAN'] = '$FORTRAN'
env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' | python | def generate(env):
"""Add Builders and construction variables for ifl to an Environment."""
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if 'FORTRANFILESUFFIXES' not in env:
env['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)
env['FORTRAN'] = 'ifl'
env['SHFORTRAN'] = '$FORTRAN'
env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' | [
"def",
"generate",
"(",
"env",
")",
":",
"fscan",
"=",
"FortranScan",
"(",
"\"FORTRANPATH\"",
")",
"SCons",
".",
"Tool",
".",
"SourceFileScanner",
".",
"add_scanner",
"(",
"'.i'",
",",
"fscan",
")",
"SCons",
".",
"Tool",
".",
"SourceFileScanner",
".",
"add... | Add Builders and construction variables for ifl to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"ifl",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifl.py#L40-L63 | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/bcc32.py | generate | def generate(env):
findIt('bcc32', env)
"""Add Builders and construction variables for bcc to an
Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ['.c', '.cpp']:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['CC'] = 'bcc32'
env['CCFLAGS'] = SCons.Util.CLVar('')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '$CC -q $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '$SHCC -WD $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
env['SHOBJSUFFIX'] = '.dll'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0
env['CFILESUFFIX'] = '.cpp' | python | def generate(env):
findIt('bcc32', env)
"""Add Builders and construction variables for bcc to an
Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ['.c', '.cpp']:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['CC'] = 'bcc32'
env['CCFLAGS'] = SCons.Util.CLVar('')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '$CC -q $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '$SHCC -WD $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
env['SHOBJSUFFIX'] = '.dll'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0
env['CFILESUFFIX'] = '.cpp' | [
"def",
"generate",
"(",
"env",
")",
":",
"findIt",
"(",
"'bcc32'",
",",
"env",
")",
"static_obj",
",",
"shared_obj",
"=",
"SCons",
".",
"Tool",
".",
"createObjBuilders",
"(",
"env",
")",
"for",
"suffix",
"in",
"[",
"'.c'",
",",
"'.cpp'",
"]",
":",
"s... | Add Builders and construction variables for bcc to an
Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"bcc",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/bcc32.py#L47-L72 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | require | def require(builder_name):
"""Find an advertised autobuilder and return it
This function searches through all installed distributions to find
if any advertise an entry point with group 'iotile.autobuild' and
name equal to builder_name. The first one that is found is returned.
This function raises a BuildError if it cannot find the required
autobuild function
Args:
builder_name (string): The name of the builder to find
Returns:
callable: the autobuilder function found in the search
"""
reg = ComponentRegistry()
for _name, autobuild_func in reg.load_extensions('iotile.autobuild', name_filter=builder_name):
return autobuild_func
raise BuildError('Cannot find required autobuilder, make sure the distribution providing it is installed',
name=builder_name) | python | def require(builder_name):
"""Find an advertised autobuilder and return it
This function searches through all installed distributions to find
if any advertise an entry point with group 'iotile.autobuild' and
name equal to builder_name. The first one that is found is returned.
This function raises a BuildError if it cannot find the required
autobuild function
Args:
builder_name (string): The name of the builder to find
Returns:
callable: the autobuilder function found in the search
"""
reg = ComponentRegistry()
for _name, autobuild_func in reg.load_extensions('iotile.autobuild', name_filter=builder_name):
return autobuild_func
raise BuildError('Cannot find required autobuilder, make sure the distribution providing it is installed',
name=builder_name) | [
"def",
"require",
"(",
"builder_name",
")",
":",
"reg",
"=",
"ComponentRegistry",
"(",
")",
"for",
"_name",
",",
"autobuild_func",
"in",
"reg",
".",
"load_extensions",
"(",
"'iotile.autobuild'",
",",
"name_filter",
"=",
"builder_name",
")",
":",
"return",
"aut... | Find an advertised autobuilder and return it
This function searches through all installed distributions to find
if any advertise an entry point with group 'iotile.autobuild' and
name equal to builder_name. The first one that is found is returned.
This function raises a BuildError if it cannot find the required
autobuild function
Args:
builder_name (string): The name of the builder to find
Returns:
callable: the autobuilder function found in the search | [
"Find",
"an",
"advertised",
"autobuilder",
"and",
"return",
"it"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L32-L54 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_onlycopy | def autobuild_onlycopy():
"""Autobuild a project that does not require building firmware, pcb or documentation
"""
try:
# Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
Alias('release', os.path.join('build', 'output'))
Default(['release'])
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | python | def autobuild_onlycopy():
"""Autobuild a project that does not require building firmware, pcb or documentation
"""
try:
# Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
Alias('release', os.path.join('build', 'output'))
Default(['release'])
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | [
"def",
"autobuild_onlycopy",
"(",
")",
":",
"try",
":",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"autobuild_release",
"(",
"family",
")",
"Alias",
"(",
"'release'",
",",
"os",
".",
"path",
".",
"join",
"(",
"'build'"... | Autobuild a project that does not require building firmware, pcb or documentation | [
"Autobuild",
"a",
"project",
"that",
"does",
"not",
"require",
"building",
"firmware",
"pcb",
"or",
"documentation"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L89-L101 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_docproject | def autobuild_docproject():
"""Autobuild a project that only contains documentation"""
try:
#Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
autobuild_documentation(family.tile)
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | python | def autobuild_docproject():
"""Autobuild a project that only contains documentation"""
try:
#Build only release information
family = utilities.get_family('module_settings.json')
autobuild_release(family)
autobuild_documentation(family.tile)
except unit_test.IOTileException as e:
print(e.format())
Exit(1) | [
"def",
"autobuild_docproject",
"(",
")",
":",
"try",
":",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"autobuild_release",
"(",
"family",
")",
"autobuild_documentation",
"(",
"family",
".",
"tile",
")",
"except",
"unit_test",... | Autobuild a project that only contains documentation | [
"Autobuild",
"a",
"project",
"that",
"only",
"contains",
"documentation"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L104-L114 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_arm_program | def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True):
"""
Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those.
"""
try:
#Build for all targets
family = utilities.get_family('module_settings.json')
family.for_all_targets(family.tile.short_name, lambda x: arm.build_program(family.tile, elfname, x, patch=patch))
#Build all unit tests
unit_test.build_units(os.path.join('firmware','test'), family.targets(family.tile.short_name))
Alias('release', os.path.join('build', 'output'))
Alias('test', os.path.join('build', 'test', 'output'))
Default(['release', 'test'])
autobuild_release(family)
if os.path.exists('doc'):
autobuild_documentation(family.tile)
except IOTileException as e:
print(e.format())
sys.exit(1) | python | def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True):
"""
Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those.
"""
try:
#Build for all targets
family = utilities.get_family('module_settings.json')
family.for_all_targets(family.tile.short_name, lambda x: arm.build_program(family.tile, elfname, x, patch=patch))
#Build all unit tests
unit_test.build_units(os.path.join('firmware','test'), family.targets(family.tile.short_name))
Alias('release', os.path.join('build', 'output'))
Alias('test', os.path.join('build', 'test', 'output'))
Default(['release', 'test'])
autobuild_release(family)
if os.path.exists('doc'):
autobuild_documentation(family.tile)
except IOTileException as e:
print(e.format())
sys.exit(1) | [
"def",
"autobuild_arm_program",
"(",
"elfname",
",",
"test_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'firmware'",
",",
"'test'",
")",
",",
"patch",
"=",
"True",
")",
":",
"try",
":",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_set... | Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those. | [
"Build",
"the",
"an",
"ARM",
"module",
"for",
"all",
"targets",
"and",
"build",
"all",
"unit",
"tests",
".",
"If",
"pcb",
"files",
"are",
"given",
"also",
"build",
"those",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L152-L176 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_doxygen | def autobuild_doxygen(tile):
"""Generate documentation for firmware in this module using doxygen"""
iotile = IOTile('.')
doxydir = os.path.join('build', 'doc')
doxyfile = os.path.join(doxydir, 'doxygen.txt')
outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
env['IOTILE'] = iotile
# There is no /dev/null on Windows
if platform.system() == 'Windows':
action = 'doxygen %s > NUL' % doxyfile
else:
action = 'doxygen %s > /dev/null' % doxyfile
Alias('doxygen', doxydir)
env.Clean(outfile, doxydir)
inputfile = doxygen_source_path()
env.Command(doxyfile, inputfile, action=env.Action(lambda target, source, env: generate_doxygen_file(str(target[0]), iotile), "Creating Doxygen Config File"))
env.Command(outfile, doxyfile, action=env.Action(action, "Building Firmware Documentation")) | python | def autobuild_doxygen(tile):
"""Generate documentation for firmware in this module using doxygen"""
iotile = IOTile('.')
doxydir = os.path.join('build', 'doc')
doxyfile = os.path.join(doxydir, 'doxygen.txt')
outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
env['IOTILE'] = iotile
# There is no /dev/null on Windows
if platform.system() == 'Windows':
action = 'doxygen %s > NUL' % doxyfile
else:
action = 'doxygen %s > /dev/null' % doxyfile
Alias('doxygen', doxydir)
env.Clean(outfile, doxydir)
inputfile = doxygen_source_path()
env.Command(doxyfile, inputfile, action=env.Action(lambda target, source, env: generate_doxygen_file(str(target[0]), iotile), "Creating Doxygen Config File"))
env.Command(outfile, doxyfile, action=env.Action(action, "Building Firmware Documentation")) | [
"def",
"autobuild_doxygen",
"(",
"tile",
")",
":",
"iotile",
"=",
"IOTile",
"(",
"'.'",
")",
"doxydir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'build'",
",",
"'doc'",
")",
"doxyfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"doxydir",
",",
"'... | Generate documentation for firmware in this module using doxygen | [
"Generate",
"documentation",
"for",
"firmware",
"in",
"this",
"module",
"using",
"doxygen"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L178-L202 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_documentation | def autobuild_documentation(tile):
"""Generate documentation for this module using a combination of sphinx and breathe"""
docdir = os.path.join('#doc')
docfile = os.path.join(docdir, 'conf.py')
outdir = os.path.join('build', 'output', 'doc', tile.unique_id)
outfile = os.path.join(outdir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
# Only build doxygen documentation if we have C firmware to build from
if os.path.exists('firmware'):
autobuild_doxygen(tile)
env.Depends(outfile, 'doxygen')
# There is no /dev/null on Windows
# Also disable color output on Windows since it seems to leave powershell
# in a weird state.
if platform.system() == 'Windows':
action = 'sphinx-build --no-color -b html %s %s > NUL' % (docdir[1:], outdir)
else:
action = 'sphinx-build -b html %s %s > /dev/null' % (docdir[1:], outdir)
env.Command(outfile, docfile, action=env.Action(action, "Building Component Documentation"))
Alias('documentation', outdir)
env.Clean(outfile, outdir) | python | def autobuild_documentation(tile):
"""Generate documentation for this module using a combination of sphinx and breathe"""
docdir = os.path.join('#doc')
docfile = os.path.join(docdir, 'conf.py')
outdir = os.path.join('build', 'output', 'doc', tile.unique_id)
outfile = os.path.join(outdir, '%s.timestamp' % tile.unique_id)
env = Environment(ENV=os.environ, tools=[])
# Only build doxygen documentation if we have C firmware to build from
if os.path.exists('firmware'):
autobuild_doxygen(tile)
env.Depends(outfile, 'doxygen')
# There is no /dev/null on Windows
# Also disable color output on Windows since it seems to leave powershell
# in a weird state.
if platform.system() == 'Windows':
action = 'sphinx-build --no-color -b html %s %s > NUL' % (docdir[1:], outdir)
else:
action = 'sphinx-build -b html %s %s > /dev/null' % (docdir[1:], outdir)
env.Command(outfile, docfile, action=env.Action(action, "Building Component Documentation"))
Alias('documentation', outdir)
env.Clean(outfile, outdir) | [
"def",
"autobuild_documentation",
"(",
"tile",
")",
":",
"docdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'#doc'",
")",
"docfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"docdir",
",",
"'conf.py'",
")",
"outdir",
"=",
"os",
".",
"path",
".",
... | Generate documentation for this module using a combination of sphinx and breathe | [
"Generate",
"documentation",
"for",
"this",
"module",
"using",
"a",
"combination",
"of",
"sphinx",
"and",
"breathe"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L205-L230 | train |
iotile/coretools | iotilebuild/iotile/build/config/site_scons/autobuild.py | autobuild_bootstrap_file | def autobuild_bootstrap_file(file_name, image_list):
"""Combine multiple firmware images into a single bootstrap hex file.
The files listed in image_list must be products of either this tile or any
dependency tile and should correspond exactly with the base name listed on
the products section of the module_settings.json file of the corresponding
tile. They must be listed as firmware_image type products.
This function keeps a global map of all of the intermediate files that it
has had to create so that we don't try to build them multiple times.
Args:
file_name(str): Full name of the output bootstrap hex file.
image_list(list of str): List of files that will be combined into a
single hex file that will be used to flash a chip.
"""
family = utilities.get_family('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
env = Environment(tools=[])
output_dir = target.build_dirs()['output']
build_dir = target.build_dirs()['build']
build_output_name = os.path.join(build_dir, file_name)
full_output_name = os.path.join(output_dir, file_name)
processed_input_images = []
for image_name in image_list:
image_info = resolver.find_unique('firmware_image', image_name)
image_path = image_info.full_path
hex_path = arm.ensure_image_is_hex(image_path)
processed_input_images.append(hex_path)
env.Command(build_output_name, processed_input_images,
action=Action(arm.merge_hex_executables,
"Merging %d hex files into $TARGET" % len(processed_input_images)))
env.Command(full_output_name, build_output_name, Copy("$TARGET", "$SOURCE")) | python | def autobuild_bootstrap_file(file_name, image_list):
"""Combine multiple firmware images into a single bootstrap hex file.
The files listed in image_list must be products of either this tile or any
dependency tile and should correspond exactly with the base name listed on
the products section of the module_settings.json file of the corresponding
tile. They must be listed as firmware_image type products.
This function keeps a global map of all of the intermediate files that it
has had to create so that we don't try to build them multiple times.
Args:
file_name(str): Full name of the output bootstrap hex file.
image_list(list of str): List of files that will be combined into a
single hex file that will be used to flash a chip.
"""
family = utilities.get_family('module_settings.json')
target = family.platform_independent_target()
resolver = ProductResolver.Create()
env = Environment(tools=[])
output_dir = target.build_dirs()['output']
build_dir = target.build_dirs()['build']
build_output_name = os.path.join(build_dir, file_name)
full_output_name = os.path.join(output_dir, file_name)
processed_input_images = []
for image_name in image_list:
image_info = resolver.find_unique('firmware_image', image_name)
image_path = image_info.full_path
hex_path = arm.ensure_image_is_hex(image_path)
processed_input_images.append(hex_path)
env.Command(build_output_name, processed_input_images,
action=Action(arm.merge_hex_executables,
"Merging %d hex files into $TARGET" % len(processed_input_images)))
env.Command(full_output_name, build_output_name, Copy("$TARGET", "$SOURCE")) | [
"def",
"autobuild_bootstrap_file",
"(",
"file_name",
",",
"image_list",
")",
":",
"family",
"=",
"utilities",
".",
"get_family",
"(",
"'module_settings.json'",
")",
"target",
"=",
"family",
".",
"platform_independent_target",
"(",
")",
"resolver",
"=",
"ProductResol... | Combine multiple firmware images into a single bootstrap hex file.
The files listed in image_list must be products of either this tile or any
dependency tile and should correspond exactly with the base name listed on
the products section of the module_settings.json file of the corresponding
tile. They must be listed as firmware_image type products.
This function keeps a global map of all of the intermediate files that it
has had to create so that we don't try to build them multiple times.
Args:
file_name(str): Full name of the output bootstrap hex file.
image_list(list of str): List of files that will be combined into a
single hex file that will be used to flash a chip. | [
"Combine",
"multiple",
"firmware",
"images",
"into",
"a",
"single",
"bootstrap",
"hex",
"file",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/autobuild.py#L262-L303 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/scope.py | Scope.add_identifier | def add_identifier(self, name, obj):
"""Add a known identifier resolution.
Args:
name (str): The name of the identifier
obj (object): The object that is should resolve to
"""
name = str(name)
self._known_identifiers[name] = obj | python | def add_identifier(self, name, obj):
"""Add a known identifier resolution.
Args:
name (str): The name of the identifier
obj (object): The object that is should resolve to
"""
name = str(name)
self._known_identifiers[name] = obj | [
"def",
"add_identifier",
"(",
"self",
",",
"name",
",",
"obj",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"self",
".",
"_known_identifiers",
"[",
"name",
"]",
"=",
"obj"
] | Add a known identifier resolution.
Args:
name (str): The name of the identifier
obj (object): The object that is should resolve to | [
"Add",
"a",
"known",
"identifier",
"resolution",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/scopes/scope.py#L47-L56 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/scope.py | Scope.resolve_identifier | def resolve_identifier(self, name, expected_type=None):
"""Resolve an identifier to an object.
There is a single namespace for identifiers so the user also should
pass an expected type that will be checked against what the identifier
actually resolves to so that there are no surprises.
Args:
name (str): The name that we want to resolve
expected_type (type): The type of object that we expect to receive.
This is an optional parameter. If None is passed, no type checking
is performed.
Returns:
object: The resolved object
"""
name = str(name)
if name in self._known_identifiers:
obj = self._known_identifiers[name]
if expected_type is not None and not isinstance(obj, expected_type):
raise UnresolvedIdentifierError(u"Identifier resolved to an object of an unexpected type", name=name, expected_type=expected_type.__name__, resolved_type=obj.__class__.__name__)
return obj
if self.parent is not None:
try:
return self.parent.resolve_identifier(name)
except UnresolvedIdentifierError:
pass
raise UnresolvedIdentifierError(u"Could not resolve identifier", name=name, scope=self.name) | python | def resolve_identifier(self, name, expected_type=None):
"""Resolve an identifier to an object.
There is a single namespace for identifiers so the user also should
pass an expected type that will be checked against what the identifier
actually resolves to so that there are no surprises.
Args:
name (str): The name that we want to resolve
expected_type (type): The type of object that we expect to receive.
This is an optional parameter. If None is passed, no type checking
is performed.
Returns:
object: The resolved object
"""
name = str(name)
if name in self._known_identifiers:
obj = self._known_identifiers[name]
if expected_type is not None and not isinstance(obj, expected_type):
raise UnresolvedIdentifierError(u"Identifier resolved to an object of an unexpected type", name=name, expected_type=expected_type.__name__, resolved_type=obj.__class__.__name__)
return obj
if self.parent is not None:
try:
return self.parent.resolve_identifier(name)
except UnresolvedIdentifierError:
pass
raise UnresolvedIdentifierError(u"Could not resolve identifier", name=name, scope=self.name) | [
"def",
"resolve_identifier",
"(",
"self",
",",
"name",
",",
"expected_type",
"=",
"None",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"_known_identifiers",
":",
"obj",
"=",
"self",
".",
"_known_identifiers",
"[",
"nam... | Resolve an identifier to an object.
There is a single namespace for identifiers so the user also should
pass an expected type that will be checked against what the identifier
actually resolves to so that there are no surprises.
Args:
name (str): The name that we want to resolve
expected_type (type): The type of object that we expect to receive.
This is an optional parameter. If None is passed, no type checking
is performed.
Returns:
object: The resolved object | [
"Resolve",
"an",
"identifier",
"to",
"an",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/parser/scopes/scope.py#L58-L90 | train |
iotile/coretools | iotilecore/iotile/core/hw/reports/signed_list_format.py | SignedListReport.FromReadings | def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None,
report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0):
"""Generate an instance of the report format from a list of readings and a uuid.
The signed list report is created using the passed readings and signed using the specified method
and AuthProvider. If no auth provider is specified, the report is signed using the default authorization
chain.
Args:
uuid (int): The uuid of the deviec that this report came from
readings (list): A list of IOTileReading objects containing the data in the report
root_key (int): The key that should be used to sign the report (must be supported
by an auth_provider)
signer (AuthProvider): An optional preconfigured AuthProvider that should be used to sign this
report. If no AuthProvider is provided, the default ChainedAuthProvider is used.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report.
"""
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
report_len = 20 + 16*len(readings) + 24
len_low = report_len & 0xFF
len_high = report_len >> 8
unique_readings = [x.reading_id for x in readings if x.reading_id != IOTileReading.InvalidReadingID]
if len(unique_readings) > 0:
lowest_id = min(unique_readings)
highest_id = max(unique_readings)
header = struct.pack("<BBHLLLBBH", cls.ReportType, len_low, len_high, uuid, report_id,
sent_timestamp, root_key, streamer, selector)
header = bytearray(header)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id,
reading.raw_time, reading.value)
packed_readings += bytearray(packed_reading)
footer_stats = struct.pack("<LL", lowest_id, highest_id)
if signer is None:
signer = ChainedAuthProvider()
# If we are supposed to encrypt this report, do the encryption
if root_key != signer.NoKey:
enc_data = packed_readings
try:
result = signer.encrypt_report(uuid, root_key, enc_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not encrypt report because no AuthProvider supported "
"the requested encryption method for the requested device",
device_id=uuid, root_key=root_key)
signed_data = header + result['data'] + footer_stats
else:
signed_data = header + packed_readings + footer_stats
try:
signature = signer.sign_report(uuid, root_key, signed_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not sign report because no AuthProvider supported the requested "
"signature method for the requested device", device_id=uuid, root_key=root_key)
footer = struct.pack("16s", bytes(signature['signature'][:16]))
footer = bytearray(footer)
data = signed_data + footer
return SignedListReport(data) | python | def FromReadings(cls, uuid, readings, root_key=AuthProvider.NoKey, signer=None,
report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0, sent_timestamp=0):
"""Generate an instance of the report format from a list of readings and a uuid.
The signed list report is created using the passed readings and signed using the specified method
and AuthProvider. If no auth provider is specified, the report is signed using the default authorization
chain.
Args:
uuid (int): The uuid of the deviec that this report came from
readings (list): A list of IOTileReading objects containing the data in the report
root_key (int): The key that should be used to sign the report (must be supported
by an auth_provider)
signer (AuthProvider): An optional preconfigured AuthProvider that should be used to sign this
report. If no AuthProvider is provided, the default ChainedAuthProvider is used.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report.
"""
lowest_id = IOTileReading.InvalidReadingID
highest_id = IOTileReading.InvalidReadingID
report_len = 20 + 16*len(readings) + 24
len_low = report_len & 0xFF
len_high = report_len >> 8
unique_readings = [x.reading_id for x in readings if x.reading_id != IOTileReading.InvalidReadingID]
if len(unique_readings) > 0:
lowest_id = min(unique_readings)
highest_id = max(unique_readings)
header = struct.pack("<BBHLLLBBH", cls.ReportType, len_low, len_high, uuid, report_id,
sent_timestamp, root_key, streamer, selector)
header = bytearray(header)
packed_readings = bytearray()
for reading in readings:
packed_reading = struct.pack("<HHLLL", reading.stream, 0, reading.reading_id,
reading.raw_time, reading.value)
packed_readings += bytearray(packed_reading)
footer_stats = struct.pack("<LL", lowest_id, highest_id)
if signer is None:
signer = ChainedAuthProvider()
# If we are supposed to encrypt this report, do the encryption
if root_key != signer.NoKey:
enc_data = packed_readings
try:
result = signer.encrypt_report(uuid, root_key, enc_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not encrypt report because no AuthProvider supported "
"the requested encryption method for the requested device",
device_id=uuid, root_key=root_key)
signed_data = header + result['data'] + footer_stats
else:
signed_data = header + packed_readings + footer_stats
try:
signature = signer.sign_report(uuid, root_key, signed_data, report_id=report_id,
sent_timestamp=sent_timestamp)
except NotFoundError:
raise ExternalError("Could not sign report because no AuthProvider supported the requested "
"signature method for the requested device", device_id=uuid, root_key=root_key)
footer = struct.pack("16s", bytes(signature['signature'][:16]))
footer = bytearray(footer)
data = signed_data + footer
return SignedListReport(data) | [
"def",
"FromReadings",
"(",
"cls",
",",
"uuid",
",",
"readings",
",",
"root_key",
"=",
"AuthProvider",
".",
"NoKey",
",",
"signer",
"=",
"None",
",",
"report_id",
"=",
"IOTileReading",
".",
"InvalidReadingID",
",",
"selector",
"=",
"0xFFFF",
",",
"streamer",... | Generate an instance of the report format from a list of readings and a uuid.
The signed list report is created using the passed readings and signed using the specified method
and AuthProvider. If no auth provider is specified, the report is signed using the default authorization
chain.
Args:
uuid (int): The uuid of the deviec that this report came from
readings (list): A list of IOTileReading objects containing the data in the report
root_key (int): The key that should be used to sign the report (must be supported
by an auth_provider)
signer (AuthProvider): An optional preconfigured AuthProvider that should be used to sign this
report. If no AuthProvider is provided, the default ChainedAuthProvider is used.
report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.
Note that you can specify anything you want for the report id but for actual IOTile devices
the report id will always be greater than the id of all of the readings contained in the report
since devices generate ids sequentially.
selector (int): The streamer selector of this report. This can be anything but if the report came from
a device, it would correspond with the query the device used to pick readings to go into the report.
streamer (int): The streamer id that this reading was sent from.
sent_timestamp (int): The device's uptime that sent this report. | [
"Generate",
"an",
"instance",
"of",
"the",
"report",
"format",
"from",
"a",
"list",
"of",
"readings",
"and",
"a",
"uuid",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/signed_list_format.py#L44-L124 | train |
iotile/coretools | iotilecore/iotile/core/hw/reports/signed_list_format.py | SignedListReport.decode | def decode(self):
"""Decode this report into a list of readings
"""
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) | len_low
self.origin = device_id
self.report_id = report_id
self.sent_timestamp = sent_timestamp
self.origin_streamer = origin_streamer
self.streamer_selector = streamer_selector
self.signature_flags = signature_flags
assert len(self.raw_report) == length
remaining = self.raw_report[20:]
assert len(remaining) >= 24
readings = remaining[:-24]
footer = remaining[-24:]
lowest_id, highest_id, signature = unpack("<LL16s", footer)
signature = bytearray(signature)
self.lowest_id = lowest_id
self.highest_id = highest_id
self.signature = signature
signed_data = self.raw_report[:-16]
signer = ChainedAuthProvider()
if signature_flags == AuthProvider.NoKey:
self.encrypted = False
else:
self.encrypted = True
try:
verification = signer.verify_report(device_id, signature_flags, signed_data, signature,
report_id=report_id, sent_timestamp=sent_timestamp)
self.verified = verification['verified']
except NotFoundError:
self.verified = False
# If we were not able to verify the report, do not try to parse or decrypt it since we
# can't guarantee who it came from.
if not self.verified:
return [], []
# If the report is encrypted, try to decrypt it before parsing the readings
if self.encrypted:
try:
result = signer.decrypt_report(device_id, signature_flags, readings,
report_id=report_id, sent_timestamp=sent_timestamp)
readings = result['data']
except NotFoundError:
return [], []
# Now parse all of the readings
# Make sure this report has an integer number of readings
assert (len(readings) % 16) == 0
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
return parsed_readings, [] | python | def decode(self):
"""Decode this report into a list of readings
"""
fmt, len_low, len_high, device_id, report_id, sent_timestamp, signature_flags, \
origin_streamer, streamer_selector = unpack("<BBHLLLBBH", self.raw_report[:20])
assert fmt == 1
length = (len_high << 8) | len_low
self.origin = device_id
self.report_id = report_id
self.sent_timestamp = sent_timestamp
self.origin_streamer = origin_streamer
self.streamer_selector = streamer_selector
self.signature_flags = signature_flags
assert len(self.raw_report) == length
remaining = self.raw_report[20:]
assert len(remaining) >= 24
readings = remaining[:-24]
footer = remaining[-24:]
lowest_id, highest_id, signature = unpack("<LL16s", footer)
signature = bytearray(signature)
self.lowest_id = lowest_id
self.highest_id = highest_id
self.signature = signature
signed_data = self.raw_report[:-16]
signer = ChainedAuthProvider()
if signature_flags == AuthProvider.NoKey:
self.encrypted = False
else:
self.encrypted = True
try:
verification = signer.verify_report(device_id, signature_flags, signed_data, signature,
report_id=report_id, sent_timestamp=sent_timestamp)
self.verified = verification['verified']
except NotFoundError:
self.verified = False
# If we were not able to verify the report, do not try to parse or decrypt it since we
# can't guarantee who it came from.
if not self.verified:
return [], []
# If the report is encrypted, try to decrypt it before parsing the readings
if self.encrypted:
try:
result = signer.decrypt_report(device_id, signature_flags, readings,
report_id=report_id, sent_timestamp=sent_timestamp)
readings = result['data']
except NotFoundError:
return [], []
# Now parse all of the readings
# Make sure this report has an integer number of readings
assert (len(readings) % 16) == 0
time_base = self.received_time - datetime.timedelta(seconds=sent_timestamp)
parsed_readings = []
for i in range(0, len(readings), 16):
reading = readings[i:i+16]
stream, _, reading_id, timestamp, value = unpack("<HHLLL", reading)
parsed = IOTileReading(timestamp, stream, value, time_base=time_base, reading_id=reading_id)
parsed_readings.append(parsed)
return parsed_readings, [] | [
"def",
"decode",
"(",
"self",
")",
":",
"fmt",
",",
"len_low",
",",
"len_high",
",",
"device_id",
",",
"report_id",
",",
"sent_timestamp",
",",
"signature_flags",
",",
"origin_streamer",
",",
"streamer_selector",
"=",
"unpack",
"(",
"\"<BBHLLLBBH\"",
",",
"sel... | Decode this report into a list of readings | [
"Decode",
"this",
"report",
"into",
"a",
"list",
"of",
"readings"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/signed_list_format.py#L126-L200 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/model.py | DeviceModel._add_property | def _add_property(self, name, default_value):
"""Add a device property with a given default value.
Args:
name (str): The name of the property to add
default_value (int, bool): The value of the property
"""
name = str(name)
self._properties[name] = default_value | python | def _add_property(self, name, default_value):
"""Add a device property with a given default value.
Args:
name (str): The name of the property to add
default_value (int, bool): The value of the property
"""
name = str(name)
self._properties[name] = default_value | [
"def",
"_add_property",
"(",
"self",
",",
"name",
",",
"default_value",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"self",
".",
"_properties",
"[",
"name",
"]",
"=",
"default_value"
] | Add a device property with a given default value.
Args:
name (str): The name of the property to add
default_value (int, bool): The value of the property | [
"Add",
"a",
"device",
"property",
"with",
"a",
"given",
"default",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/model.py#L28-L37 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/model.py | DeviceModel.set | def set(self, name, value):
"""Set a device model property.
Args:
name (str): The name of the property to set
value (int, bool): The value of the property to set
"""
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
self._properties[name] = value | python | def set(self, name, value):
"""Set a device model property.
Args:
name (str): The name of the property to set
value (int, bool): The value of the property to set
"""
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
self._properties[name] = value | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_properties",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown property in DeviceModel\"",
",",
"name",
"=",
"nam... | Set a device model property.
Args:
name (str): The name of the property to set
value (int, bool): The value of the property to set | [
"Set",
"a",
"device",
"model",
"property",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/model.py#L39-L51 | train |
iotile/coretools | iotilesensorgraph/iotile/sg/model.py | DeviceModel.get | def get(self, name):
"""Get a device model property.
Args:
name (str): The name of the property to get
"""
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
return self._properties[name] | python | def get(self, name):
"""Get a device model property.
Args:
name (str): The name of the property to get
"""
name = str(name)
if name not in self._properties:
raise ArgumentError("Unknown property in DeviceModel", name=name)
return self._properties[name] | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"not",
"in",
"self",
".",
"_properties",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown property in DeviceModel\"",
",",
"name",
"=",
"name",
")",
"retu... | Get a device model property.
Args:
name (str): The name of the property to get | [
"Get",
"a",
"device",
"model",
"property",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/model.py#L53-L64 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | _convert_to_bytes | def _convert_to_bytes(type_name, value):
"""Convert a typed value to a binary array"""
int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'}
type_name = type_name.lower()
if type_name not in int_types and type_name not in ['string', 'binary']:
raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name)
if type_name == 'string':
#value should be passed as a string
bytevalue = bytes(value)
elif type_name == 'binary':
bytevalue = bytes(value)
else:
bytevalue = struct.pack("<%s" % int_types[type_name], value)
return bytevalue | python | def _convert_to_bytes(type_name, value):
"""Convert a typed value to a binary array"""
int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'}
type_name = type_name.lower()
if type_name not in int_types and type_name not in ['string', 'binary']:
raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name)
if type_name == 'string':
#value should be passed as a string
bytevalue = bytes(value)
elif type_name == 'binary':
bytevalue = bytes(value)
else:
bytevalue = struct.pack("<%s" % int_types[type_name], value)
return bytevalue | [
"def",
"_convert_to_bytes",
"(",
"type_name",
",",
"value",
")",
":",
"int_types",
"=",
"{",
"'uint8_t'",
":",
"'B'",
",",
"'int8_t'",
":",
"'b'",
",",
"'uint16_t'",
":",
"'H'",
",",
"'int16_t'",
":",
"'h'",
",",
"'uint32_t'",
":",
"'L'",
",",
"'int32_t'... | Convert a typed value to a binary array | [
"Convert",
"a",
"typed",
"value",
"to",
"a",
"binary",
"array"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L378-L396 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigEntry.dump | def dump(self):
"""Serialize this object."""
return {
'target': str(self.target),
'data': base64.b64encode(self.data).decode('utf-8'),
'var_id': self.var_id,
'valid': self.valid
} | python | def dump(self):
"""Serialize this object."""
return {
'target': str(self.target),
'data': base64.b64encode(self.data).decode('utf-8'),
'var_id': self.var_id,
'valid': self.valid
} | [
"def",
"dump",
"(",
"self",
")",
":",
"return",
"{",
"'target'",
":",
"str",
"(",
"self",
".",
"target",
")",
",",
"'data'",
":",
"base64",
".",
"b64encode",
"(",
"self",
".",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"'var_id'",
":",
... | Serialize this object. | [
"Serialize",
"this",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L39-L47 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigEntry.generate_rpcs | def generate_rpcs(self, address):
"""Generate the RPCs needed to stream this config variable to a tile.
Args:
address (int): The address of the tile that we should stream to.
Returns:
list of tuples: A list of argument tuples for each RPC.
These tuples can be passed to EmulatedDevice.rpc to actually make
the RPCs.
"""
rpc_list = []
for offset in range(2, len(self.data), 16):
rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16])
rpc_list.append(rpc)
return rpc_list | python | def generate_rpcs(self, address):
"""Generate the RPCs needed to stream this config variable to a tile.
Args:
address (int): The address of the tile that we should stream to.
Returns:
list of tuples: A list of argument tuples for each RPC.
These tuples can be passed to EmulatedDevice.rpc to actually make
the RPCs.
"""
rpc_list = []
for offset in range(2, len(self.data), 16):
rpc = (address, rpcs.SET_CONFIG_VARIABLE, self.var_id, offset - 2, self.data[offset:offset + 16])
rpc_list.append(rpc)
return rpc_list | [
"def",
"generate_rpcs",
"(",
"self",
",",
"address",
")",
":",
"rpc_list",
"=",
"[",
"]",
"for",
"offset",
"in",
"range",
"(",
"2",
",",
"len",
"(",
"self",
".",
"data",
")",
",",
"16",
")",
":",
"rpc",
"=",
"(",
"address",
",",
"rpcs",
".",
"S... | Generate the RPCs needed to stream this config variable to a tile.
Args:
address (int): The address of the tile that we should stream to.
Returns:
list of tuples: A list of argument tuples for each RPC.
These tuples can be passed to EmulatedDevice.rpc to actually make
the RPCs. | [
"Generate",
"the",
"RPCs",
"needed",
"to",
"stream",
"this",
"config",
"variable",
"to",
"a",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L49-L68 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigEntry.Restore | def Restore(cls, state):
"""Unserialize this object."""
target = SlotIdentifier.FromString(state.get('target'))
data = base64.b64decode(state.get('data'))
var_id = state.get('var_id')
valid = state.get('valid')
return ConfigEntry(target, var_id, data, valid) | python | def Restore(cls, state):
"""Unserialize this object."""
target = SlotIdentifier.FromString(state.get('target'))
data = base64.b64decode(state.get('data'))
var_id = state.get('var_id')
valid = state.get('valid')
return ConfigEntry(target, var_id, data, valid) | [
"def",
"Restore",
"(",
"cls",
",",
"state",
")",
":",
"target",
"=",
"SlotIdentifier",
".",
"FromString",
"(",
"state",
".",
"get",
"(",
"'target'",
")",
")",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"state",
".",
"get",
"(",
"'data'",
")",
")",... | Unserialize this object. | [
"Unserialize",
"this",
"object",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L71-L79 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.compact | def compact(self):
"""Remove all invalid config entries."""
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
to_remove.append(i)
saved_length += entry.data_space()
for i in reversed(to_remove):
del self.entries[i]
self.data_index -= saved_length | python | def compact(self):
"""Remove all invalid config entries."""
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
to_remove.append(i)
saved_length += entry.data_space()
for i in reversed(to_remove):
del self.entries[i]
self.data_index -= saved_length | [
"def",
"compact",
"(",
"self",
")",
":",
"saved_length",
"=",
"0",
"to_remove",
"=",
"[",
"]",
"for",
"i",
",",
"entry",
"in",
"enumerate",
"(",
"self",
".",
"entries",
")",
":",
"if",
"not",
"entry",
".",
"valid",
":",
"to_remove",
".",
"append",
... | Remove all invalid config entries. | [
"Remove",
"all",
"invalid",
"config",
"entries",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L109-L122 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.start_entry | def start_entry(self, target, var_id):
"""Begin a new config database entry.
If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
Returns:
int: An error code from the global Errors enum.
"""
self.in_progress = ConfigEntry(target, var_id, b'')
if self.data_size - self.data_index < self.in_progress.data_space():
return Error.DESTINATION_BUFFER_TOO_SMALL
self.in_progress.data += struct.pack("<H", var_id)
self.data_index += self.in_progress.data_space()
return Error.NO_ERROR | python | def start_entry(self, target, var_id):
"""Begin a new config database entry.
If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
Returns:
int: An error code from the global Errors enum.
"""
self.in_progress = ConfigEntry(target, var_id, b'')
if self.data_size - self.data_index < self.in_progress.data_space():
return Error.DESTINATION_BUFFER_TOO_SMALL
self.in_progress.data += struct.pack("<H", var_id)
self.data_index += self.in_progress.data_space()
return Error.NO_ERROR | [
"def",
"start_entry",
"(",
"self",
",",
"target",
",",
"var_id",
")",
":",
"self",
".",
"in_progress",
"=",
"ConfigEntry",
"(",
"target",
",",
"var_id",
",",
"b''",
")",
"if",
"self",
".",
"data_size",
"-",
"self",
".",
"data_index",
"<",
"self",
".",
... | Begin a new config database entry.
If there is a current entry in progress, it is aborted but the
data was already committed to persistent storage so that space
is wasted.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
Returns:
int: An error code from the global Errors enum. | [
"Begin",
"a",
"new",
"config",
"database",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L131-L154 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.add_data | def add_data(self, data):
"""Add data to the currently in progress entry.
Args:
data (bytes): The data that we want to add.
Returns:
int: An error code
"""
if self.data_size - self.data_index < len(data):
return Error.DESTINATION_BUFFER_TOO_SMALL
if self.in_progress is not None:
self.in_progress.data += data
return Error.NO_ERROR | python | def add_data(self, data):
"""Add data to the currently in progress entry.
Args:
data (bytes): The data that we want to add.
Returns:
int: An error code
"""
if self.data_size - self.data_index < len(data):
return Error.DESTINATION_BUFFER_TOO_SMALL
if self.in_progress is not None:
self.in_progress.data += data
return Error.NO_ERROR | [
"def",
"add_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"data_size",
"-",
"self",
".",
"data_index",
"<",
"len",
"(",
"data",
")",
":",
"return",
"Error",
".",
"DESTINATION_BUFFER_TOO_SMALL",
"if",
"self",
".",
"in_progress",
"is",
"not... | Add data to the currently in progress entry.
Args:
data (bytes): The data that we want to add.
Returns:
int: An error code | [
"Add",
"data",
"to",
"the",
"currently",
"in",
"progress",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L156-L172 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.end_entry | def end_entry(self):
"""Finish a previously started config database entry.
This commits the currently in progress entry. The expected flow is
that start_entry() is called followed by 1 or more calls to add_data()
followed by a single call to end_entry().
Returns:
int: An error code
"""
# Matching current firmware behavior
if self.in_progress is None:
return Error.NO_ERROR
# Make sure there was actually data stored
if self.in_progress.data_space() == 2:
return Error.INPUT_BUFFER_WRONG_SIZE
# Invalidate all previous copies of this config variable so we
# can properly compact.
for entry in self.entries:
if entry.target == self.in_progress.target and entry.var_id == self.in_progress.var_id:
entry.valid = False
self.entries.append(self.in_progress)
self.data_index += self.in_progress.data_space() - 2 # Add in the rest of the entry size (we added two bytes at start_entry())
self.in_progress = None
return Error.NO_ERROR | python | def end_entry(self):
"""Finish a previously started config database entry.
This commits the currently in progress entry. The expected flow is
that start_entry() is called followed by 1 or more calls to add_data()
followed by a single call to end_entry().
Returns:
int: An error code
"""
# Matching current firmware behavior
if self.in_progress is None:
return Error.NO_ERROR
# Make sure there was actually data stored
if self.in_progress.data_space() == 2:
return Error.INPUT_BUFFER_WRONG_SIZE
# Invalidate all previous copies of this config variable so we
# can properly compact.
for entry in self.entries:
if entry.target == self.in_progress.target and entry.var_id == self.in_progress.var_id:
entry.valid = False
self.entries.append(self.in_progress)
self.data_index += self.in_progress.data_space() - 2 # Add in the rest of the entry size (we added two bytes at start_entry())
self.in_progress = None
return Error.NO_ERROR | [
"def",
"end_entry",
"(",
"self",
")",
":",
"if",
"self",
".",
"in_progress",
"is",
"None",
":",
"return",
"Error",
".",
"NO_ERROR",
"if",
"self",
".",
"in_progress",
".",
"data_space",
"(",
")",
"==",
"2",
":",
"return",
"Error",
".",
"INPUT_BUFFER_WRONG... | Finish a previously started config database entry.
This commits the currently in progress entry. The expected flow is
that start_entry() is called followed by 1 or more calls to add_data()
followed by a single call to end_entry().
Returns:
int: An error code | [
"Finish",
"a",
"previously",
"started",
"config",
"database",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L174-L203 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.stream_matching | def stream_matching(self, address, name):
"""Return the RPCs needed to stream matching config variables to the given tile.
This function will return a list of tuples suitable for passing to
EmulatedDevice.deferred_rpc.
Args:
address (int): The address of the tile that we wish to stream to
name (str or bytes): The 6 character name of the target tile.
Returns:
list of tuple: The list of RPCs to send to stream these variables to a tile.
"""
matching = [x for x in self.entries if x.valid and x.target.matches(address, name)]
rpc_list = []
for var in matching:
rpc_list.extend(var.generate_rpcs(address))
return rpc_list | python | def stream_matching(self, address, name):
"""Return the RPCs needed to stream matching config variables to the given tile.
This function will return a list of tuples suitable for passing to
EmulatedDevice.deferred_rpc.
Args:
address (int): The address of the tile that we wish to stream to
name (str or bytes): The 6 character name of the target tile.
Returns:
list of tuple: The list of RPCs to send to stream these variables to a tile.
"""
matching = [x for x in self.entries if x.valid and x.target.matches(address, name)]
rpc_list = []
for var in matching:
rpc_list.extend(var.generate_rpcs(address))
return rpc_list | [
"def",
"stream_matching",
"(",
"self",
",",
"address",
",",
"name",
")",
":",
"matching",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"entries",
"if",
"x",
".",
"valid",
"and",
"x",
".",
"target",
".",
"matches",
"(",
"address",
",",
"name",
")",... | Return the RPCs needed to stream matching config variables to the given tile.
This function will return a list of tuples suitable for passing to
EmulatedDevice.deferred_rpc.
Args:
address (int): The address of the tile that we wish to stream to
name (str or bytes): The 6 character name of the target tile.
Returns:
list of tuple: The list of RPCs to send to stream these variables to a tile. | [
"Return",
"the",
"RPCs",
"needed",
"to",
"stream",
"matching",
"config",
"variables",
"to",
"the",
"given",
"tile",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L205-L225 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabase.add_direct | def add_direct(self, target, var_id, var_type, data):
"""Directly add a config variable.
This method is meant to be called from emulation scenarios that
want to directly set config database entries from python.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
var_type (str): The config variable type
data (bytes or int or str): The data that will be encoded according
to var_type.
"""
data = struct.pack("<H", var_id) + _convert_to_bytes(var_type, data)
if self.data_size - self.data_index < len(data):
raise DataError("Not enough space for data in new conig entry", needed_space=len(data), actual_space=(self.data_size - self.data_index))
new_entry = ConfigEntry(target, var_id, data)
for entry in self.entries:
if entry.target == new_entry.target and entry.var_id == new_entry.var_id:
entry.valid = False
self.entries.append(new_entry)
self.data_index += new_entry.data_space() | python | def add_direct(self, target, var_id, var_type, data):
"""Directly add a config variable.
This method is meant to be called from emulation scenarios that
want to directly set config database entries from python.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
var_type (str): The config variable type
data (bytes or int or str): The data that will be encoded according
to var_type.
"""
data = struct.pack("<H", var_id) + _convert_to_bytes(var_type, data)
if self.data_size - self.data_index < len(data):
raise DataError("Not enough space for data in new conig entry", needed_space=len(data), actual_space=(self.data_size - self.data_index))
new_entry = ConfigEntry(target, var_id, data)
for entry in self.entries:
if entry.target == new_entry.target and entry.var_id == new_entry.var_id:
entry.valid = False
self.entries.append(new_entry)
self.data_index += new_entry.data_space() | [
"def",
"add_direct",
"(",
"self",
",",
"target",
",",
"var_id",
",",
"var_type",
",",
"data",
")",
":",
"data",
"=",
"struct",
".",
"pack",
"(",
"\"<H\"",
",",
"var_id",
")",
"+",
"_convert_to_bytes",
"(",
"var_type",
",",
"data",
")",
"if",
"self",
... | Directly add a config variable.
This method is meant to be called from emulation scenarios that
want to directly set config database entries from python.
Args:
target (SlotIdentifer): The target slot for this config variable.
var_id (int): The config variable ID
var_type (str): The config variable type
data (bytes or int or str): The data that will be encoded according
to var_type. | [
"Directly",
"add",
"a",
"config",
"variable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L227-L253 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.start_config_var_entry | def start_config_var_entry(self, var_id, encoded_selector):
"""Start a new config variable entry."""
selector = SlotIdentifier.FromEncoded(encoded_selector)
err = self.config_database.start_entry(selector, var_id)
return [err] | python | def start_config_var_entry(self, var_id, encoded_selector):
"""Start a new config variable entry."""
selector = SlotIdentifier.FromEncoded(encoded_selector)
err = self.config_database.start_entry(selector, var_id)
return [err] | [
"def",
"start_config_var_entry",
"(",
"self",
",",
"var_id",
",",
"encoded_selector",
")",
":",
"selector",
"=",
"SlotIdentifier",
".",
"FromEncoded",
"(",
"encoded_selector",
")",
"err",
"=",
"self",
".",
"config_database",
".",
"start_entry",
"(",
"selector",
... | Start a new config variable entry. | [
"Start",
"a",
"new",
"config",
"variable",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L277-L283 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.get_config_var_entry | def get_config_var_entry(self, index):
"""Get the metadata from the selected config variable entry."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0]
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, 0, 0, 0, b'\0'*8, 0, 0]
offset = sum(x.data_space() for x in self.config_database.entries[:index - 1])
return [Error.NO_ERROR, self.config_database.ENTRY_MAGIC, offset, entry.data_space(), entry.target.encode(), 0xFF, 0] | python | def get_config_var_entry(self, index):
"""Get the metadata from the selected config variable entry."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, b'\0'*8, 0, 0]
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, 0, 0, 0, b'\0'*8, 0, 0]
offset = sum(x.data_space() for x in self.config_database.entries[:index - 1])
return [Error.NO_ERROR, self.config_database.ENTRY_MAGIC, offset, entry.data_space(), entry.target.encode(), 0xFF, 0] | [
"def",
"get_config_var_entry",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"config_database",
".",
"entries",
")",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
"0",
",",
"0"... | Get the metadata from the selected config variable entry. | [
"Get",
"the",
"metadata",
"from",
"the",
"selected",
"config",
"variable",
"entry",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L300-L311 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.get_config_var_data | def get_config_var_data(self, index, offset):
"""Get a chunk of data for a config variable."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
if offset >= len(entry.data):
return [Error.INVALID_ARRAY_KEY, b'']
data_chunk = entry.data[offset:offset + 16]
return [Error.NO_ERROR, data_chunk] | python | def get_config_var_data(self, index, offset):
"""Get a chunk of data for a config variable."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
if offset >= len(entry.data):
return [Error.INVALID_ARRAY_KEY, b'']
data_chunk = entry.data[offset:offset + 16]
return [Error.NO_ERROR, data_chunk] | [
"def",
"get_config_var_data",
"(",
"self",
",",
"index",
",",
"offset",
")",
":",
"if",
"index",
"==",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"config_database",
".",
"entries",
")",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
... | Get a chunk of data for a config variable. | [
"Get",
"a",
"chunk",
"of",
"data",
"for",
"a",
"config",
"variable",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L327-L341 | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/config_database.py | ConfigDatabaseMixin.invalidate_config_var_entry | def invalidate_config_var_entry(self, index):
"""Mark a config variable as invalid."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
entry.valid = False
return [Error.NO_ERROR] | python | def invalidate_config_var_entry(self, index):
"""Mark a config variable as invalid."""
if index == 0 or index > len(self.config_database.entries):
return [Error.INVALID_ARRAY_KEY, b'']
entry = self.config_database.entries[index - 1]
if not entry.valid:
return [ConfigDatabaseError.OBSOLETE_ENTRY, b'']
entry.valid = False
return [Error.NO_ERROR] | [
"def",
"invalidate_config_var_entry",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"config_database",
".",
"entries",
")",
":",
"return",
"[",
"Error",
".",
"INVALID_ARRAY_KEY",
",",
"b''",
"... | Mark a config variable as invalid. | [
"Mark",
"a",
"config",
"variable",
"as",
"invalid",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/config_database.py#L344-L355 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.