id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
23,400
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
sconsign_dir
def sconsign_dir(node): """Return the .sconsign file info for this directory, creating it first if necessary.""" if not node._sconsign: import SCons.SConsign node._sconsign = SCons.SConsign.ForDirectory(node) return node._sconsign
python
def sconsign_dir(node): if not node._sconsign: import SCons.SConsign node._sconsign = SCons.SConsign.ForDirectory(node) return node._sconsign
[ "def", "sconsign_dir", "(", "node", ")", ":", "if", "not", "node", ".", "_sconsign", ":", "import", "SCons", ".", "SConsign", "node", ".", "_sconsign", "=", "SCons", ".", "SConsign", ".", "ForDirectory", "(", "node", ")", "return", "node", ".", "_sconsig...
Return the .sconsign file info for this directory, creating it first if necessary.
[ "Return", "the", ".", "sconsign", "file", "info", "for", "this", "directory", "creating", "it", "first", "if", "necessary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L65-L71
23,401
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
EntryProxy.__get_base_path
def __get_base_path(self): """Return the file's directory and file name, with the suffix stripped.""" entry = self.get() return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(entry.get_path())[0], entry.name + "_base")
python
def __get_base_path(self): entry = self.get() return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(entry.get_path())[0], entry.name + "_base")
[ "def", "__get_base_path", "(", "self", ")", ":", "entry", "=", "self", ".", "get", "(", ")", "return", "SCons", ".", "Subst", ".", "SpecialAttrWrapper", "(", "SCons", ".", "Util", ".", "splitext", "(", "entry", ".", "get_path", "(", ")", ")", "[", "0...
Return the file's directory and file name, with the suffix stripped.
[ "Return", "the", "file", "s", "directory", "and", "file", "name", "with", "the", "suffix", "stripped", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L447-L452
23,402
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
EntryProxy.__get_windows_path
def __get_windows_path(self): """Return the path with \ as the path separator, regardless of platform.""" if OS_SEP == '\\': return self else: entry = self.get() r = entry.get_path().replace(OS_SEP, '\\') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows")
python
def __get_windows_path(self): if OS_SEP == '\\': return self else: entry = self.get() r = entry.get_path().replace(OS_SEP, '\\') return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows")
[ "def", "__get_windows_path", "(", "self", ")", ":", "if", "OS_SEP", "==", "'\\\\'", ":", "return", "self", "else", ":", "entry", "=", "self", ".", "get", "(", ")", "r", "=", "entry", ".", "get_path", "(", ")", ".", "replace", "(", "OS_SEP", ",", "'...
Return the path with \ as the path separator, regardless of platform.
[ "Return", "the", "path", "with", "\\", "as", "the", "path", "separator", "regardless", "of", "platform", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L464-L472
23,403
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.must_be_same
def must_be_same(self, klass): """ This node, which already existed, is being looked up as the specified klass. Raise an exception if it isn't. """ if isinstance(self, klass) or klass is Entry: return raise TypeError("Tried to lookup %s '%s' as a %s." %\ (self.__class__.__name__, self.get_internal_path(), klass.__name__))
python
def must_be_same(self, klass): if isinstance(self, klass) or klass is Entry: return raise TypeError("Tried to lookup %s '%s' as a %s." %\ (self.__class__.__name__, self.get_internal_path(), klass.__name__))
[ "def", "must_be_same", "(", "self", ",", "klass", ")", ":", "if", "isinstance", "(", "self", ",", "klass", ")", "or", "klass", "is", "Entry", ":", "return", "raise", "TypeError", "(", "\"Tried to lookup %s '%s' as a %s.\"", "%", "(", "self", ".", "__class__"...
This node, which already existed, is being looked up as the specified klass. Raise an exception if it isn't.
[ "This", "node", "which", "already", "existed", "is", "being", "looked", "up", "as", "the", "specified", "klass", ".", "Raise", "an", "exception", "if", "it", "isn", "t", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L593-L601
23,404
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.srcnode
def srcnode(self): """If this node is in a build path, return the node corresponding to its source file. Otherwise, return ourself. """ srcdir_list = self.dir.srcdir_list() if srcdir_list: srcnode = srcdir_list[0].Entry(self.name) srcnode.must_be_same(self.__class__) return srcnode return self
python
def srcnode(self): srcdir_list = self.dir.srcdir_list() if srcdir_list: srcnode = srcdir_list[0].Entry(self.name) srcnode.must_be_same(self.__class__) return srcnode return self
[ "def", "srcnode", "(", "self", ")", ":", "srcdir_list", "=", "self", ".", "dir", ".", "srcdir_list", "(", ")", "if", "srcdir_list", ":", "srcnode", "=", "srcdir_list", "[", "0", "]", ".", "Entry", "(", "self", ".", "name", ")", "srcnode", ".", "must_...
If this node is in a build path, return the node corresponding to its source file. Otherwise, return ourself.
[ "If", "this", "node", "is", "in", "a", "build", "path", "return", "the", "node", "corresponding", "to", "its", "source", "file", ".", "Otherwise", "return", "ourself", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L733-L743
23,405
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.get_path
def get_path(self, dir=None): """Return path relative to the current working directory of the Node.FS.Base object that owns us.""" if not dir: dir = self.fs.getcwd() if self == dir: return '.' path_elems = self.get_path_elements() pathname = '' try: i = path_elems.index(dir) except ValueError: for p in path_elems[:-1]: pathname += p.dirname else: for p in path_elems[i+1:-1]: pathname += p.dirname return pathname + path_elems[-1].name
python
def get_path(self, dir=None): if not dir: dir = self.fs.getcwd() if self == dir: return '.' path_elems = self.get_path_elements() pathname = '' try: i = path_elems.index(dir) except ValueError: for p in path_elems[:-1]: pathname += p.dirname else: for p in path_elems[i+1:-1]: pathname += p.dirname return pathname + path_elems[-1].name
[ "def", "get_path", "(", "self", ",", "dir", "=", "None", ")", ":", "if", "not", "dir", ":", "dir", "=", "self", ".", "fs", ".", "getcwd", "(", ")", "if", "self", "==", "dir", ":", "return", "'.'", "path_elems", "=", "self", ".", "get_path_elements"...
Return path relative to the current working directory of the Node.FS.Base object that owns us.
[ "Return", "path", "relative", "to", "the", "current", "working", "directory", "of", "the", "Node", ".", "FS", ".", "Base", "object", "that", "owns", "us", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L745-L761
23,406
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.set_src_builder
def set_src_builder(self, builder): """Set the source code builder for this node.""" self.sbuilder = builder if not self.has_builder(): self.builder_set(builder)
python
def set_src_builder(self, builder): self.sbuilder = builder if not self.has_builder(): self.builder_set(builder)
[ "def", "set_src_builder", "(", "self", ",", "builder", ")", ":", "self", ".", "sbuilder", "=", "builder", "if", "not", "self", ".", "has_builder", "(", ")", ":", "self", ".", "builder_set", "(", "builder", ")" ]
Set the source code builder for this node.
[ "Set", "the", "source", "code", "builder", "for", "this", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L763-L767
23,407
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.src_builder
def src_builder(self): """Fetch the source code builder for this node. If there isn't one, we cache the source code builder specified for the directory (which in turn will cache the value from its parent directory, and so on up to the file system root). """ try: scb = self.sbuilder except AttributeError: scb = self.dir.src_builder() self.sbuilder = scb return scb
python
def src_builder(self): try: scb = self.sbuilder except AttributeError: scb = self.dir.src_builder() self.sbuilder = scb return scb
[ "def", "src_builder", "(", "self", ")", ":", "try", ":", "scb", "=", "self", ".", "sbuilder", "except", "AttributeError", ":", "scb", "=", "self", ".", "dir", ".", "src_builder", "(", ")", "self", ".", "sbuilder", "=", "scb", "return", "scb" ]
Fetch the source code builder for this node. If there isn't one, we cache the source code builder specified for the directory (which in turn will cache the value from its parent directory, and so on up to the file system root).
[ "Fetch", "the", "source", "code", "builder", "for", "this", "node", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L769-L781
23,408
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.Rfindalldirs
def Rfindalldirs(self, pathlist): """ Return all of the directories for a given path list, including corresponding "backing" directories in any repositories. The Node lookups are relative to this Node (typically a directory), so memoizing result saves cycles from looking up the same path for each target in a given directory. """ try: memo_dict = self._memo['Rfindalldirs'] except KeyError: memo_dict = {} self._memo['Rfindalldirs'] = memo_dict else: try: return memo_dict[pathlist] except KeyError: pass create_dir_relative_to_self = self.Dir result = [] for path in pathlist: if isinstance(path, SCons.Node.Node): result.append(path) else: dir = create_dir_relative_to_self(path) result.extend(dir.get_all_rdirs()) memo_dict[pathlist] = result return result
python
def Rfindalldirs(self, pathlist): try: memo_dict = self._memo['Rfindalldirs'] except KeyError: memo_dict = {} self._memo['Rfindalldirs'] = memo_dict else: try: return memo_dict[pathlist] except KeyError: pass create_dir_relative_to_self = self.Dir result = [] for path in pathlist: if isinstance(path, SCons.Node.Node): result.append(path) else: dir = create_dir_relative_to_self(path) result.extend(dir.get_all_rdirs()) memo_dict[pathlist] = result return result
[ "def", "Rfindalldirs", "(", "self", ",", "pathlist", ")", ":", "try", ":", "memo_dict", "=", "self", ".", "_memo", "[", "'Rfindalldirs'", "]", "except", "KeyError", ":", "memo_dict", "=", "{", "}", "self", ".", "_memo", "[", "'Rfindalldirs'", "]", "=", ...
Return all of the directories for a given path list, including corresponding "backing" directories in any repositories. The Node lookups are relative to this Node (typically a directory), so memoizing result saves cycles from looking up the same path for each target in a given directory.
[ "Return", "all", "of", "the", "directories", "for", "a", "given", "path", "list", "including", "corresponding", "backing", "directories", "in", "any", "repositories", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L836-L867
23,409
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Base.RDirs
def RDirs(self, pathlist): """Search for a list of directories in the Repository list.""" cwd = self.cwd or self.fs._cwd return cwd.Rfindalldirs(pathlist)
python
def RDirs(self, pathlist): cwd = self.cwd or self.fs._cwd return cwd.Rfindalldirs(pathlist)
[ "def", "RDirs", "(", "self", ",", "pathlist", ")", ":", "cwd", "=", "self", ".", "cwd", "or", "self", ".", "fs", ".", "_cwd", "return", "cwd", ".", "Rfindalldirs", "(", "pathlist", ")" ]
Search for a list of directories in the Repository list.
[ "Search", "for", "a", "list", "of", "directories", "in", "the", "Repository", "list", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L869-L872
23,410
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Entry.rfile
def rfile(self): """We're a generic Entry, but the caller is actually looking for a File at this point, so morph into one.""" self.__class__ = File self._morph() self.clear() return File.rfile(self)
python
def rfile(self): self.__class__ = File self._morph() self.clear() return File.rfile(self)
[ "def", "rfile", "(", "self", ")", ":", "self", ".", "__class__", "=", "File", "self", ".", "_morph", "(", ")", "self", ".", "clear", "(", ")", "return", "File", ".", "rfile", "(", "self", ")" ]
We're a generic Entry, but the caller is actually looking for a File at this point, so morph into one.
[ "We", "re", "a", "generic", "Entry", "but", "the", "caller", "is", "actually", "looking", "for", "a", "File", "at", "this", "point", "so", "morph", "into", "one", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L973-L979
23,411
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Entry.get_text_contents
def get_text_contents(self): """Fetch the decoded text contents of a Unicode encoded Entry. Since this should return the text contents from the file system, we check to see into what sort of subclass we should morph this Entry.""" try: self = self.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_text_contents() in emitters and # the like (e.g. in qt.py) don't have to disambiguate by # hand or catch the exception. return '' else: return self.get_text_contents()
python
def get_text_contents(self): try: self = self.disambiguate(must_exist=1) except SCons.Errors.UserError: # There was nothing on disk with which to disambiguate # this entry. Leave it as an Entry, but return a null # string so calls to get_text_contents() in emitters and # the like (e.g. in qt.py) don't have to disambiguate by # hand or catch the exception. return '' else: return self.get_text_contents()
[ "def", "get_text_contents", "(", "self", ")", ":", "try", ":", "self", "=", "self", ".", "disambiguate", "(", "must_exist", "=", "1", ")", "except", "SCons", ".", "Errors", ".", "UserError", ":", "# There was nothing on disk with which to disambiguate", "# this en...
Fetch the decoded text contents of a Unicode encoded Entry. Since this should return the text contents from the file system, we check to see into what sort of subclass we should morph this Entry.
[ "Fetch", "the", "decoded", "text", "contents", "of", "a", "Unicode", "encoded", "Entry", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L989-L1005
23,412
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Entry.must_be_same
def must_be_same(self, klass): """Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.""" if self.__class__ is not klass: self.__class__ = klass self._morph() self.clear()
python
def must_be_same(self, klass): if self.__class__ is not klass: self.__class__ = klass self._morph() self.clear()
[ "def", "must_be_same", "(", "self", ",", "klass", ")", ":", "if", "self", ".", "__class__", "is", "not", "klass", ":", "self", ".", "__class__", "=", "klass", "self", ".", "_morph", "(", ")", "self", ".", "clear", "(", ")" ]
Called to make sure a Node is a Dir. Since we're an Entry, we can morph into one.
[ "Called", "to", "make", "sure", "a", "Node", "is", "a", "Dir", ".", "Since", "we", "re", "an", "Entry", "we", "can", "morph", "into", "one", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1007-L1013
23,413
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FS.chdir
def chdir(self, dir, change_os_dir=0): """Change the current working directory for lookups. If change_os_dir is true, we will also change the "real" cwd to match. """ curr=self._cwd try: if dir is not None: self._cwd = dir if change_os_dir: os.chdir(dir.get_abspath()) except OSError: self._cwd = curr raise
python
def chdir(self, dir, change_os_dir=0): curr=self._cwd try: if dir is not None: self._cwd = dir if change_os_dir: os.chdir(dir.get_abspath()) except OSError: self._cwd = curr raise
[ "def", "chdir", "(", "self", ",", "dir", ",", "change_os_dir", "=", "0", ")", ":", "curr", "=", "self", ".", "_cwd", "try", ":", "if", "dir", "is", "not", "None", ":", "self", ".", "_cwd", "=", "dir", "if", "change_os_dir", ":", "os", ".", "chdir...
Change the current working directory for lookups. If change_os_dir is true, we will also change the "real" cwd to match.
[ "Change", "the", "current", "working", "directory", "for", "lookups", ".", "If", "change_os_dir", "is", "true", "we", "will", "also", "change", "the", "real", "cwd", "to", "match", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1168-L1181
23,414
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FS.get_root
def get_root(self, drive): """ Returns the root directory for the specified drive, creating it if necessary. """ drive = _my_normcase(drive) try: return self.Root[drive] except KeyError: root = RootDir(drive, self) self.Root[drive] = root if not drive: self.Root[self.defaultDrive] = root elif drive == self.defaultDrive: self.Root[''] = root return root
python
def get_root(self, drive): drive = _my_normcase(drive) try: return self.Root[drive] except KeyError: root = RootDir(drive, self) self.Root[drive] = root if not drive: self.Root[self.defaultDrive] = root elif drive == self.defaultDrive: self.Root[''] = root return root
[ "def", "get_root", "(", "self", ",", "drive", ")", ":", "drive", "=", "_my_normcase", "(", "drive", ")", "try", ":", "return", "self", ".", "Root", "[", "drive", "]", "except", "KeyError", ":", "root", "=", "RootDir", "(", "drive", ",", "self", ")", ...
Returns the root directory for the specified drive, creating it if necessary.
[ "Returns", "the", "root", "directory", "for", "the", "specified", "drive", "creating", "it", "if", "necessary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1183-L1198
23,415
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FS._lookup
def _lookup(self, p, directory, fsclass, create=1): """ The generic entry point for Node lookup with user-supplied data. This translates arbitrary input into a canonical Node.FS object of the specified fsclass. The general approach for strings is to turn it into a fully normalized absolute path and then call the root directory's lookup_abs() method for the heavy lifting. If the path name begins with '#', it is unconditionally interpreted relative to the top-level directory of this FS. '#' is treated as a synonym for the top-level SConstruct directory, much like '~' is treated as a synonym for the user's home directory in a UNIX shell. So both '#foo' and '#/foo' refer to the 'foo' subdirectory underneath the top-level SConstruct directory. If the path name is relative, then the path is looked up relative to the specified directory, or the current directory (self._cwd, typically the SConscript directory) if the specified directory is None. """ if isinstance(p, Base): # It's already a Node.FS object. Make sure it's the right # class and return. p.must_be_same(fsclass) return p # str(p) in case it's something like a proxy object p = str(p) if not os_sep_is_slash: p = p.replace(OS_SEP, '/') if p[0:1] == '#': # There was an initial '#', so we strip it and override # whatever directory they may have specified with the # top-level SConstruct directory. p = p[1:] directory = self.Top # There might be a drive letter following the # '#'. Although it is not described in the SCons man page, # the regression test suite explicitly tests for that # syntax. It seems to mean the following thing: # # Assuming the the SCons top dir is in C:/xxx/yyy, # '#X:/toto' means X:/xxx/yyy/toto. # # i.e. it assumes that the X: drive has a directory # structure similar to the one found on drive C:. if do_splitdrive: drive, p = _my_splitdrive(p) if drive: root = self.get_root(drive) else: root = directory.root else: root = directory.root # We can only strip trailing after splitting the drive # since the drive might the UNC '//' prefix. p = p.strip('/') needs_normpath = needs_normpath_match(p) # The path is relative to the top-level SCons directory. if p in ('', '.'): p = directory.get_labspath() else: p = directory.get_labspath() + '/' + p else: if do_splitdrive: drive, p = _my_splitdrive(p) if drive and not p: # This causes a naked drive letter to be treated # as a synonym for the root directory on that # drive. p = '/' else: drive = '' # We can only strip trailing '/' since the drive might the # UNC '//' prefix. if p != '/': p = p.rstrip('/') needs_normpath = needs_normpath_match(p) if p[0:1] == '/': # Absolute path root = self.get_root(drive) else: # This is a relative lookup or to the current directory # (the path name is not absolute). Add the string to the # appropriate directory lookup path, after which the whole # thing gets normalized. if directory: if not isinstance(directory, Dir): directory = self.Dir(directory) else: directory = self._cwd if p in ('', '.'): p = directory.get_labspath() else: p = directory.get_labspath() + '/' + p if drive: root = self.get_root(drive) else: root = directory.root if needs_normpath is not None: # Normalize a pathname. Will return the same result for # equivalent paths. # # We take advantage of the fact that we have an absolute # path here for sure. In addition, we know that the # components of lookup path are separated by slashes at # this point. Because of this, this code is about 2X # faster than calling os.path.normpath() followed by # replacing os.sep with '/' again. ins = p.split('/')[1:] outs = [] for d in ins: if d == '..': try: outs.pop() except IndexError: pass elif d not in ('', '.'): outs.append(d) p = '/' + '/'.join(outs) return root._lookup_abs(p, fsclass, create)
python
def _lookup(self, p, directory, fsclass, create=1): if isinstance(p, Base): # It's already a Node.FS object. Make sure it's the right # class and return. p.must_be_same(fsclass) return p # str(p) in case it's something like a proxy object p = str(p) if not os_sep_is_slash: p = p.replace(OS_SEP, '/') if p[0:1] == '#': # There was an initial '#', so we strip it and override # whatever directory they may have specified with the # top-level SConstruct directory. p = p[1:] directory = self.Top # There might be a drive letter following the # '#'. Although it is not described in the SCons man page, # the regression test suite explicitly tests for that # syntax. It seems to mean the following thing: # # Assuming the the SCons top dir is in C:/xxx/yyy, # '#X:/toto' means X:/xxx/yyy/toto. # # i.e. it assumes that the X: drive has a directory # structure similar to the one found on drive C:. if do_splitdrive: drive, p = _my_splitdrive(p) if drive: root = self.get_root(drive) else: root = directory.root else: root = directory.root # We can only strip trailing after splitting the drive # since the drive might the UNC '//' prefix. p = p.strip('/') needs_normpath = needs_normpath_match(p) # The path is relative to the top-level SCons directory. if p in ('', '.'): p = directory.get_labspath() else: p = directory.get_labspath() + '/' + p else: if do_splitdrive: drive, p = _my_splitdrive(p) if drive and not p: # This causes a naked drive letter to be treated # as a synonym for the root directory on that # drive. p = '/' else: drive = '' # We can only strip trailing '/' since the drive might the # UNC '//' prefix. if p != '/': p = p.rstrip('/') needs_normpath = needs_normpath_match(p) if p[0:1] == '/': # Absolute path root = self.get_root(drive) else: # This is a relative lookup or to the current directory # (the path name is not absolute). Add the string to the # appropriate directory lookup path, after which the whole # thing gets normalized. if directory: if not isinstance(directory, Dir): directory = self.Dir(directory) else: directory = self._cwd if p in ('', '.'): p = directory.get_labspath() else: p = directory.get_labspath() + '/' + p if drive: root = self.get_root(drive) else: root = directory.root if needs_normpath is not None: # Normalize a pathname. Will return the same result for # equivalent paths. # # We take advantage of the fact that we have an absolute # path here for sure. In addition, we know that the # components of lookup path are separated by slashes at # this point. Because of this, this code is about 2X # faster than calling os.path.normpath() followed by # replacing os.sep with '/' again. ins = p.split('/')[1:] outs = [] for d in ins: if d == '..': try: outs.pop() except IndexError: pass elif d not in ('', '.'): outs.append(d) p = '/' + '/'.join(outs) return root._lookup_abs(p, fsclass, create)
[ "def", "_lookup", "(", "self", ",", "p", ",", "directory", ",", "fsclass", ",", "create", "=", "1", ")", ":", "if", "isinstance", "(", "p", ",", "Base", ")", ":", "# It's already a Node.FS object. Make sure it's the right", "# class and return.", "p", ".", "m...
The generic entry point for Node lookup with user-supplied data. This translates arbitrary input into a canonical Node.FS object of the specified fsclass. The general approach for strings is to turn it into a fully normalized absolute path and then call the root directory's lookup_abs() method for the heavy lifting. If the path name begins with '#', it is unconditionally interpreted relative to the top-level directory of this FS. '#' is treated as a synonym for the top-level SConstruct directory, much like '~' is treated as a synonym for the user's home directory in a UNIX shell. So both '#foo' and '#/foo' refer to the 'foo' subdirectory underneath the top-level SConstruct directory. If the path name is relative, then the path is looked up relative to the specified directory, or the current directory (self._cwd, typically the SConscript directory) if the specified directory is None.
[ "The", "generic", "entry", "point", "for", "Node", "lookup", "with", "user", "-", "supplied", "data", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1200-L1334
23,416
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FS.VariantDir
def VariantDir(self, variant_dir, src_dir, duplicate=1): """Link the supplied variant directory to the source directory for purposes of building files.""" if not isinstance(src_dir, SCons.Node.Node): src_dir = self.Dir(src_dir) if not isinstance(variant_dir, SCons.Node.Node): variant_dir = self.Dir(variant_dir) if src_dir.is_under(variant_dir): raise SCons.Errors.UserError("Source directory cannot be under variant directory.") if variant_dir.srcdir: if variant_dir.srcdir == src_dir: return # We already did this. raise SCons.Errors.UserError("'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir)) variant_dir.link(src_dir, duplicate)
python
def VariantDir(self, variant_dir, src_dir, duplicate=1): if not isinstance(src_dir, SCons.Node.Node): src_dir = self.Dir(src_dir) if not isinstance(variant_dir, SCons.Node.Node): variant_dir = self.Dir(variant_dir) if src_dir.is_under(variant_dir): raise SCons.Errors.UserError("Source directory cannot be under variant directory.") if variant_dir.srcdir: if variant_dir.srcdir == src_dir: return # We already did this. raise SCons.Errors.UserError("'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir)) variant_dir.link(src_dir, duplicate)
[ "def", "VariantDir", "(", "self", ",", "variant_dir", ",", "src_dir", ",", "duplicate", "=", "1", ")", ":", "if", "not", "isinstance", "(", "src_dir", ",", "SCons", ".", "Node", ".", "Node", ")", ":", "src_dir", "=", "self", ".", "Dir", "(", "src_dir...
Link the supplied variant directory to the source directory for purposes of building files.
[ "Link", "the", "supplied", "variant", "directory", "to", "the", "source", "directory", "for", "purposes", "of", "building", "files", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1369-L1383
23,417
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FS.Repository
def Repository(self, *dirs): """Specify Repository directories to search.""" for d in dirs: if not isinstance(d, SCons.Node.Node): d = self.Dir(d) self.Top.addRepository(d)
python
def Repository(self, *dirs): for d in dirs: if not isinstance(d, SCons.Node.Node): d = self.Dir(d) self.Top.addRepository(d)
[ "def", "Repository", "(", "self", ",", "*", "dirs", ")", ":", "for", "d", "in", "dirs", ":", "if", "not", "isinstance", "(", "d", ",", "SCons", ".", "Node", ".", "Node", ")", ":", "d", "=", "self", ".", "Dir", "(", "d", ")", "self", ".", "Top...
Specify Repository directories to search.
[ "Specify", "Repository", "directories", "to", "search", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1385-L1390
23,418
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FS.variant_dir_target_climb
def variant_dir_target_climb(self, orig, dir, tail): """Create targets in corresponding variant directories Climb the directory tree, and look up path names relative to any linked variant directories we find. Even though this loops and walks up the tree, we don't memoize the return value because this is really only used to process the command-line targets. """ targets = [] message = None fmt = "building associated VariantDir targets: %s" start_dir = dir while dir: for bd in dir.variant_dirs: if start_dir.is_under(bd): # If already in the build-dir location, don't reflect return [orig], fmt % str(orig) p = os.path.join(bd._path, *tail) targets.append(self.Entry(p)) tail = [dir.name] + tail dir = dir.up() if targets: message = fmt % ' '.join(map(str, targets)) return targets, message
python
def variant_dir_target_climb(self, orig, dir, tail): targets = [] message = None fmt = "building associated VariantDir targets: %s" start_dir = dir while dir: for bd in dir.variant_dirs: if start_dir.is_under(bd): # If already in the build-dir location, don't reflect return [orig], fmt % str(orig) p = os.path.join(bd._path, *tail) targets.append(self.Entry(p)) tail = [dir.name] + tail dir = dir.up() if targets: message = fmt % ' '.join(map(str, targets)) return targets, message
[ "def", "variant_dir_target_climb", "(", "self", ",", "orig", ",", "dir", ",", "tail", ")", ":", "targets", "=", "[", "]", "message", "=", "None", "fmt", "=", "\"building associated VariantDir targets: %s\"", "start_dir", "=", "dir", "while", "dir", ":", "for",...
Create targets in corresponding variant directories Climb the directory tree, and look up path names relative to any linked variant directories we find. Even though this loops and walks up the tree, we don't memoize the return value because this is really only used to process the command-line targets.
[ "Create", "targets", "in", "corresponding", "variant", "directories" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1421-L1446
23,419
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.Dir
def Dir(self, name, create=True): """ Looks up or creates a directory node named 'name' relative to this directory. """ return self.fs.Dir(name, self, create)
python
def Dir(self, name, create=True): return self.fs.Dir(name, self, create)
[ "def", "Dir", "(", "self", ",", "name", ",", "create", "=", "True", ")", ":", "return", "self", ".", "fs", ".", "Dir", "(", "name", ",", "self", ",", "create", ")" ]
Looks up or creates a directory node named 'name' relative to this directory.
[ "Looks", "up", "or", "creates", "a", "directory", "node", "named", "name", "relative", "to", "this", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1611-L1616
23,420
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.link
def link(self, srcdir, duplicate): """Set this directory as the variant directory for the supplied source directory.""" self.srcdir = srcdir self.duplicate = duplicate self.__clearRepositoryCache(duplicate) srcdir.variant_dirs.append(self)
python
def link(self, srcdir, duplicate): self.srcdir = srcdir self.duplicate = duplicate self.__clearRepositoryCache(duplicate) srcdir.variant_dirs.append(self)
[ "def", "link", "(", "self", ",", "srcdir", ",", "duplicate", ")", ":", "self", ".", "srcdir", "=", "srcdir", "self", ".", "duplicate", "=", "duplicate", "self", ".", "__clearRepositoryCache", "(", "duplicate", ")", "srcdir", ".", "variant_dirs", ".", "appe...
Set this directory as the variant directory for the supplied source directory.
[ "Set", "this", "directory", "as", "the", "variant", "directory", "for", "the", "supplied", "source", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1625-L1631
23,421
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.getRepositories
def getRepositories(self): """Returns a list of repositories for this directory. """ if self.srcdir and not self.duplicate: return self.srcdir.get_all_rdirs() + self.repositories return self.repositories
python
def getRepositories(self): if self.srcdir and not self.duplicate: return self.srcdir.get_all_rdirs() + self.repositories return self.repositories
[ "def", "getRepositories", "(", "self", ")", ":", "if", "self", ".", "srcdir", "and", "not", "self", ".", "duplicate", ":", "return", "self", ".", "srcdir", ".", "get_all_rdirs", "(", ")", "+", "self", ".", "repositories", "return", "self", ".", "reposito...
Returns a list of repositories for this directory.
[ "Returns", "a", "list", "of", "repositories", "for", "this", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1633-L1638
23,422
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.rel_path
def rel_path(self, other): """Return a path to "other" relative to this directory. """ # This complicated and expensive method, which constructs relative # paths between arbitrary Node.FS objects, is no longer used # by SCons itself. It was introduced to store dependency paths # in .sconsign files relative to the target, but that ended up # being significantly inefficient. # # We're continuing to support the method because some SConstruct # files out there started using it when it was available, and # we're all about backwards compatibility.. try: memo_dict = self._memo['rel_path'] except KeyError: memo_dict = {} self._memo['rel_path'] = memo_dict else: try: return memo_dict[other] except KeyError: pass if self is other: result = '.' elif not other in self._path_elements: try: other_dir = other.get_dir() except AttributeError: result = str(other) else: if other_dir is None: result = other.name else: dir_rel_path = self.rel_path(other_dir) if dir_rel_path == '.': result = other.name else: result = dir_rel_path + OS_SEP + other.name else: i = self._path_elements.index(other) + 1 path_elems = ['..'] * (len(self._path_elements) - i) \ + [n.name for n in other._path_elements[i:]] result = OS_SEP.join(path_elems) memo_dict[other] = result return result
python
def rel_path(self, other): # This complicated and expensive method, which constructs relative # paths between arbitrary Node.FS objects, is no longer used # by SCons itself. It was introduced to store dependency paths # in .sconsign files relative to the target, but that ended up # being significantly inefficient. # # We're continuing to support the method because some SConstruct # files out there started using it when it was available, and # we're all about backwards compatibility.. try: memo_dict = self._memo['rel_path'] except KeyError: memo_dict = {} self._memo['rel_path'] = memo_dict else: try: return memo_dict[other] except KeyError: pass if self is other: result = '.' elif not other in self._path_elements: try: other_dir = other.get_dir() except AttributeError: result = str(other) else: if other_dir is None: result = other.name else: dir_rel_path = self.rel_path(other_dir) if dir_rel_path == '.': result = other.name else: result = dir_rel_path + OS_SEP + other.name else: i = self._path_elements.index(other) + 1 path_elems = ['..'] * (len(self._path_elements) - i) \ + [n.name for n in other._path_elements[i:]] result = OS_SEP.join(path_elems) memo_dict[other] = result return result
[ "def", "rel_path", "(", "self", ",", "other", ")", ":", "# This complicated and expensive method, which constructs relative", "# paths between arbitrary Node.FS objects, is no longer used", "# by SCons itself. It was introduced to store dependency paths", "# in .sconsign files relative to the...
Return a path to "other" relative to this directory.
[ "Return", "a", "path", "to", "other", "relative", "to", "this", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1676-L1728
23,423
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.get_found_includes
def get_found_includes(self, env, scanner, path): """Return this directory's implicit dependencies. We don't bother caching the results because the scan typically shouldn't be requested more than once (as opposed to scanning .h file contents, which can be requested as many times as the files is #included by other files). """ if not scanner: return [] # Clear cached info for this Dir. If we already visited this # directory on our walk down the tree (because we didn't know at # that point it was being used as the source for another Node) # then we may have calculated build signature before realizing # we had to scan the disk. Now that we have to, though, we need # to invalidate the old calculated signature so that any node # dependent on our directory structure gets one that includes # info about everything on disk. self.clear() return scanner(self, env, path)
python
def get_found_includes(self, env, scanner, path): if not scanner: return [] # Clear cached info for this Dir. If we already visited this # directory on our walk down the tree (because we didn't know at # that point it was being used as the source for another Node) # then we may have calculated build signature before realizing # we had to scan the disk. Now that we have to, though, we need # to invalidate the old calculated signature so that any node # dependent on our directory structure gets one that includes # info about everything on disk. self.clear() return scanner(self, env, path)
[ "def", "get_found_includes", "(", "self", ",", "env", ",", "scanner", ",", "path", ")", ":", "if", "not", "scanner", ":", "return", "[", "]", "# Clear cached info for this Dir. If we already visited this", "# directory on our walk down the tree (because we didn't know at", ...
Return this directory's implicit dependencies. We don't bother caching the results because the scan typically shouldn't be requested more than once (as opposed to scanning .h file contents, which can be requested as many times as the files is #included by other files).
[ "Return", "this", "directory", "s", "implicit", "dependencies", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1738-L1757
23,424
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.build
def build(self, **kw): """A null "builder" for directories.""" global MkdirBuilder if self.builder is not MkdirBuilder: SCons.Node.Node.build(self, **kw)
python
def build(self, **kw): global MkdirBuilder if self.builder is not MkdirBuilder: SCons.Node.Node.build(self, **kw)
[ "def", "build", "(", "self", ",", "*", "*", "kw", ")", ":", "global", "MkdirBuilder", "if", "self", ".", "builder", "is", "not", "MkdirBuilder", ":", "SCons", ".", "Node", ".", "Node", ".", "build", "(", "self", ",", "*", "*", "kw", ")" ]
A null "builder" for directories.
[ "A", "null", "builder", "for", "directories", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1766-L1770
23,425
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir._create
def _create(self): """Create this directory, silently and without worrying about whether the builder is the default or not.""" listDirs = [] parent = self while parent: if parent.exists(): break listDirs.append(parent) p = parent.up() if p is None: # Don't use while: - else: for this condition because # if so, then parent is None and has no .path attribute. raise SCons.Errors.StopError(parent._path) parent = p listDirs.reverse() for dirnode in listDirs: try: # Don't call dirnode.build(), call the base Node method # directly because we definitely *must* create this # directory. The dirnode.build() method will suppress # the build if it's the default builder. SCons.Node.Node.build(dirnode) dirnode.get_executor().nullify() # The build() action may or may not have actually # created the directory, depending on whether the -n # option was used or not. Delete the _exists and # _rexists attributes so they can be reevaluated. dirnode.clear() except OSError: pass
python
def _create(self): listDirs = [] parent = self while parent: if parent.exists(): break listDirs.append(parent) p = parent.up() if p is None: # Don't use while: - else: for this condition because # if so, then parent is None and has no .path attribute. raise SCons.Errors.StopError(parent._path) parent = p listDirs.reverse() for dirnode in listDirs: try: # Don't call dirnode.build(), call the base Node method # directly because we definitely *must* create this # directory. The dirnode.build() method will suppress # the build if it's the default builder. SCons.Node.Node.build(dirnode) dirnode.get_executor().nullify() # The build() action may or may not have actually # created the directory, depending on whether the -n # option was used or not. Delete the _exists and # _rexists attributes so they can be reevaluated. dirnode.clear() except OSError: pass
[ "def", "_create", "(", "self", ")", ":", "listDirs", "=", "[", "]", "parent", "=", "self", "while", "parent", ":", "if", "parent", ".", "exists", "(", ")", ":", "break", "listDirs", ".", "append", "(", "parent", ")", "p", "=", "parent", ".", "up", ...
Create this directory, silently and without worrying about whether the builder is the default or not.
[ "Create", "this", "directory", "silently", "and", "without", "worrying", "about", "whether", "the", "builder", "is", "the", "default", "or", "not", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1776-L1806
23,426
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.is_up_to_date
def is_up_to_date(self): """If any child is not up-to-date, then this directory isn't, either.""" if self.builder is not MkdirBuilder and not self.exists(): return 0 up_to_date = SCons.Node.up_to_date for kid in self.children(): if kid.get_state() > up_to_date: return 0 return 1
python
def is_up_to_date(self): if self.builder is not MkdirBuilder and not self.exists(): return 0 up_to_date = SCons.Node.up_to_date for kid in self.children(): if kid.get_state() > up_to_date: return 0 return 1
[ "def", "is_up_to_date", "(", "self", ")", ":", "if", "self", ".", "builder", "is", "not", "MkdirBuilder", "and", "not", "self", ".", "exists", "(", ")", ":", "return", "0", "up_to_date", "=", "SCons", ".", "Node", ".", "up_to_date", "for", "kid", "in",...
If any child is not up-to-date, then this directory isn't, either.
[ "If", "any", "child", "is", "not", "up", "-", "to", "-", "date", "then", "this", "directory", "isn", "t", "either", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1843-L1852
23,427
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.get_timestamp
def get_timestamp(self): """Return the latest timestamp from among our children""" stamp = 0 for kid in self.children(): if kid.get_timestamp() > stamp: stamp = kid.get_timestamp() return stamp
python
def get_timestamp(self): stamp = 0 for kid in self.children(): if kid.get_timestamp() > stamp: stamp = kid.get_timestamp() return stamp
[ "def", "get_timestamp", "(", "self", ")", ":", "stamp", "=", "0", "for", "kid", "in", "self", ".", "children", "(", ")", ":", "if", "kid", ".", "get_timestamp", "(", ")", ">", "stamp", ":", "stamp", "=", "kid", ".", "get_timestamp", "(", ")", "retu...
Return the latest timestamp from among our children
[ "Return", "the", "latest", "timestamp", "from", "among", "our", "children" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1876-L1882
23,428
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir.walk
def walk(self, func, arg): """ Walk this directory tree by calling the specified function for each directory in the tree. This behaves like the os.path.walk() function, but for in-memory Node.FS.Dir objects. The function takes the same arguments as the functions passed to os.path.walk(): func(arg, dirname, fnames) Except that "dirname" will actually be the directory *Node*, not the string. The '.' and '..' entries are excluded from fnames. The fnames list may be modified in-place to filter the subdirectories visited or otherwise impose a specific order. The "arg" argument is always passed to func() and may be used in any way (or ignored, passing None is common). """ entries = self.entries names = list(entries.keys()) names.remove('.') names.remove('..') func(arg, self, names) for dirname in [n for n in names if isinstance(entries[n], Dir)]: entries[dirname].walk(func, arg)
python
def walk(self, func, arg): entries = self.entries names = list(entries.keys()) names.remove('.') names.remove('..') func(arg, self, names) for dirname in [n for n in names if isinstance(entries[n], Dir)]: entries[dirname].walk(func, arg)
[ "def", "walk", "(", "self", ",", "func", ",", "arg", ")", ":", "entries", "=", "self", ".", "entries", "names", "=", "list", "(", "entries", ".", "keys", "(", ")", ")", "names", ".", "remove", "(", "'.'", ")", "names", ".", "remove", "(", "'..'",...
Walk this directory tree by calling the specified function for each directory in the tree. This behaves like the os.path.walk() function, but for in-memory Node.FS.Dir objects. The function takes the same arguments as the functions passed to os.path.walk(): func(arg, dirname, fnames) Except that "dirname" will actually be the directory *Node*, not the string. The '.' and '..' entries are excluded from fnames. The fnames list may be modified in-place to filter the subdirectories visited or otherwise impose a specific order. The "arg" argument is always passed to func() and may be used in any way (or ignored, passing None is common).
[ "Walk", "this", "directory", "tree", "by", "calling", "the", "specified", "function", "for", "each", "directory", "in", "the", "tree", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2074-L2098
23,429
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
Dir._glob1
def _glob1(self, pattern, ondisk=True, source=False, strings=False): """ Globs for and returns a list of entry names matching a single pattern in this directory. This searches any repositories and source directories for corresponding entries and returns a Node (or string) relative to the current directory if an entry is found anywhere. TODO: handle pattern with no wildcard """ search_dir_list = self.get_all_rdirs() for srcdir in self.srcdir_list(): search_dir_list.extend(srcdir.get_all_rdirs()) selfEntry = self.Entry names = [] for dir in search_dir_list: # We use the .name attribute from the Node because the keys of # the dir.entries dictionary are normalized (that is, all upper # case) on case-insensitive systems like Windows. node_names = [ v.name for k, v in dir.entries.items() if k not in ('.', '..') ] names.extend(node_names) if not strings: # Make sure the working directory (self) actually has # entries for all Nodes in repositories or variant dirs. for name in node_names: selfEntry(name) if ondisk: try: disk_names = os.listdir(dir._abspath) except os.error: continue names.extend(disk_names) if not strings: # We're going to return corresponding Nodes in # the local directory, so we need to make sure # those Nodes exist. We only want to create # Nodes for the entries that will match the # specified pattern, though, which means we # need to filter the list here, even though # the overall list will also be filtered later, # after we exit this loop. if pattern[0] != '.': disk_names = [x for x in disk_names if x[0] != '.'] disk_names = fnmatch.filter(disk_names, pattern) dirEntry = dir.Entry for name in disk_names: # Add './' before disk filename so that '#' at # beginning of filename isn't interpreted. name = './' + name node = dirEntry(name).disambiguate() n = selfEntry(name) if n.__class__ != node.__class__: n.__class__ = node.__class__ n._morph() names = set(names) if pattern[0] != '.': names = [x for x in names if x[0] != '.'] names = fnmatch.filter(names, pattern) if strings: return names return [self.entries[_my_normcase(n)] for n in names]
python
def _glob1(self, pattern, ondisk=True, source=False, strings=False): search_dir_list = self.get_all_rdirs() for srcdir in self.srcdir_list(): search_dir_list.extend(srcdir.get_all_rdirs()) selfEntry = self.Entry names = [] for dir in search_dir_list: # We use the .name attribute from the Node because the keys of # the dir.entries dictionary are normalized (that is, all upper # case) on case-insensitive systems like Windows. node_names = [ v.name for k, v in dir.entries.items() if k not in ('.', '..') ] names.extend(node_names) if not strings: # Make sure the working directory (self) actually has # entries for all Nodes in repositories or variant dirs. for name in node_names: selfEntry(name) if ondisk: try: disk_names = os.listdir(dir._abspath) except os.error: continue names.extend(disk_names) if not strings: # We're going to return corresponding Nodes in # the local directory, so we need to make sure # those Nodes exist. We only want to create # Nodes for the entries that will match the # specified pattern, though, which means we # need to filter the list here, even though # the overall list will also be filtered later, # after we exit this loop. if pattern[0] != '.': disk_names = [x for x in disk_names if x[0] != '.'] disk_names = fnmatch.filter(disk_names, pattern) dirEntry = dir.Entry for name in disk_names: # Add './' before disk filename so that '#' at # beginning of filename isn't interpreted. name = './' + name node = dirEntry(name).disambiguate() n = selfEntry(name) if n.__class__ != node.__class__: n.__class__ = node.__class__ n._morph() names = set(names) if pattern[0] != '.': names = [x for x in names if x[0] != '.'] names = fnmatch.filter(names, pattern) if strings: return names return [self.entries[_my_normcase(n)] for n in names]
[ "def", "_glob1", "(", "self", ",", "pattern", ",", "ondisk", "=", "True", ",", "source", "=", "False", ",", "strings", "=", "False", ")", ":", "search_dir_list", "=", "self", ".", "get_all_rdirs", "(", ")", "for", "srcdir", "in", "self", ".", "srcdir_l...
Globs for and returns a list of entry names matching a single pattern in this directory. This searches any repositories and source directories for corresponding entries and returns a Node (or string) relative to the current directory if an entry is found anywhere. TODO: handle pattern with no wildcard
[ "Globs", "for", "and", "returns", "a", "list", "of", "entry", "names", "matching", "a", "single", "pattern", "in", "this", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2160-L2225
23,430
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FileBuildInfo.convert_to_sconsign
def convert_to_sconsign(self): """ Converts this FileBuildInfo object for writing to a .sconsign file This replaces each Node in our various dependency lists with its usual string representation: relative to the top-level SConstruct directory, or an absolute path if it's outside. """ if os_sep_is_slash: node_to_str = str else: def node_to_str(n): try: s = n.get_internal_path() except AttributeError: s = str(n) else: s = s.replace(OS_SEP, '/') return s for attr in ['bsources', 'bdepends', 'bimplicit']: try: val = getattr(self, attr) except AttributeError: pass else: setattr(self, attr, list(map(node_to_str, val)))
python
def convert_to_sconsign(self): if os_sep_is_slash: node_to_str = str else: def node_to_str(n): try: s = n.get_internal_path() except AttributeError: s = str(n) else: s = s.replace(OS_SEP, '/') return s for attr in ['bsources', 'bdepends', 'bimplicit']: try: val = getattr(self, attr) except AttributeError: pass else: setattr(self, attr, list(map(node_to_str, val)))
[ "def", "convert_to_sconsign", "(", "self", ")", ":", "if", "os_sep_is_slash", ":", "node_to_str", "=", "str", "else", ":", "def", "node_to_str", "(", "n", ")", ":", "try", ":", "s", "=", "n", ".", "get_internal_path", "(", ")", "except", "AttributeError", ...
Converts this FileBuildInfo object for writing to a .sconsign file This replaces each Node in our various dependency lists with its usual string representation: relative to the top-level SConstruct directory, or an absolute path if it's outside.
[ "Converts", "this", "FileBuildInfo", "object", "for", "writing", "to", "a", ".", "sconsign", "file" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2469-L2494
23,431
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FileBuildInfo.prepare_dependencies
def prepare_dependencies(self): """ Prepares a FileBuildInfo object for explaining what changed The bsources, bdepends and bimplicit lists have all been stored on disk as paths relative to the top-level SConstruct directory. Convert the strings to actual Nodes (for use by the --debug=explain code and --implicit-cache). """ attrs = [ ('bsources', 'bsourcesigs'), ('bdepends', 'bdependsigs'), ('bimplicit', 'bimplicitsigs'), ] for (nattr, sattr) in attrs: try: strings = getattr(self, nattr) nodeinfos = getattr(self, sattr) except AttributeError: continue if strings is None or nodeinfos is None: continue nodes = [] for s, ni in zip(strings, nodeinfos): if not isinstance(s, SCons.Node.Node): s = ni.str_to_node(s) nodes.append(s) setattr(self, nattr, nodes)
python
def prepare_dependencies(self): attrs = [ ('bsources', 'bsourcesigs'), ('bdepends', 'bdependsigs'), ('bimplicit', 'bimplicitsigs'), ] for (nattr, sattr) in attrs: try: strings = getattr(self, nattr) nodeinfos = getattr(self, sattr) except AttributeError: continue if strings is None or nodeinfos is None: continue nodes = [] for s, ni in zip(strings, nodeinfos): if not isinstance(s, SCons.Node.Node): s = ni.str_to_node(s) nodes.append(s) setattr(self, nattr, nodes)
[ "def", "prepare_dependencies", "(", "self", ")", ":", "attrs", "=", "[", "(", "'bsources'", ",", "'bsourcesigs'", ")", ",", "(", "'bdepends'", ",", "'bdependsigs'", ")", ",", "(", "'bimplicit'", ",", "'bimplicitsigs'", ")", ",", "]", "for", "(", "nattr", ...
Prepares a FileBuildInfo object for explaining what changed The bsources, bdepends and bimplicit lists have all been stored on disk as paths relative to the top-level SConstruct directory. Convert the strings to actual Nodes (for use by the --debug=explain code and --implicit-cache).
[ "Prepares", "a", "FileBuildInfo", "object", "for", "explaining", "what", "changed" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2505-L2532
23,432
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.Dir
def Dir(self, name, create=True): """Create a directory node named 'name' relative to the directory of this file.""" return self.dir.Dir(name, create=create)
python
def Dir(self, name, create=True): return self.dir.Dir(name, create=create)
[ "def", "Dir", "(", "self", ",", "name", ",", "create", "=", "True", ")", ":", "return", "self", ".", "dir", ".", "Dir", "(", "name", ",", "create", "=", "create", ")" ]
Create a directory node named 'name' relative to the directory of this file.
[ "Create", "a", "directory", "node", "named", "name", "relative", "to", "the", "directory", "of", "this", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2585-L2588
23,433
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File._morph
def _morph(self): """Turn a file system node into a File object.""" self.scanner_paths = {} if not hasattr(self, '_local'): self._local = 0 if not hasattr(self, 'released_target_info'): self.released_target_info = False self.store_info = 1 self._func_exists = 4 self._func_get_contents = 3 # Initialize this Node's decider function to decide_source() because # every file is a source file until it has a Builder attached... self.changed_since_last_build = 4 # If there was already a Builder set on this entry, then # we need to make sure we call the target-decider function, # not the source-decider. Reaching in and doing this by hand # is a little bogus. We'd prefer to handle this by adding # an Entry.builder_set() method that disambiguates like the # other methods, but that starts running into problems with the # fragile way we initialize Dir Nodes with their Mkdir builders, # yet still allow them to be overridden by the user. Since it's # not clear right now how to fix that, stick with what works # until it becomes clear... if self.has_builder(): self.changed_since_last_build = 5
python
def _morph(self): self.scanner_paths = {} if not hasattr(self, '_local'): self._local = 0 if not hasattr(self, 'released_target_info'): self.released_target_info = False self.store_info = 1 self._func_exists = 4 self._func_get_contents = 3 # Initialize this Node's decider function to decide_source() because # every file is a source file until it has a Builder attached... self.changed_since_last_build = 4 # If there was already a Builder set on this entry, then # we need to make sure we call the target-decider function, # not the source-decider. Reaching in and doing this by hand # is a little bogus. We'd prefer to handle this by adding # an Entry.builder_set() method that disambiguates like the # other methods, but that starts running into problems with the # fragile way we initialize Dir Nodes with their Mkdir builders, # yet still allow them to be overridden by the user. Since it's # not clear right now how to fix that, stick with what works # until it becomes clear... if self.has_builder(): self.changed_since_last_build = 5
[ "def", "_morph", "(", "self", ")", ":", "self", ".", "scanner_paths", "=", "{", "}", "if", "not", "hasattr", "(", "self", ",", "'_local'", ")", ":", "self", ".", "_local", "=", "0", "if", "not", "hasattr", "(", "self", ",", "'released_target_info'", ...
Turn a file system node into a File object.
[ "Turn", "a", "file", "system", "node", "into", "a", "File", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2600-L2627
23,434
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_text_contents
def get_text_contents(self): """ This attempts to figure out what the encoding of the text is based upon the BOM bytes, and then decodes the contents so that it's a valid python string. """ contents = self.get_contents() # The behavior of various decode() methods and functions # w.r.t. the initial BOM bytes is different for different # encodings and/or Python versions. ('utf-8' does not strip # them, but has a 'utf-8-sig' which does; 'utf-16' seems to # strip them; etc.) Just sidestep all the complication by # explicitly stripping the BOM before we decode(). if contents[:len(codecs.BOM_UTF8)] == codecs.BOM_UTF8: return contents[len(codecs.BOM_UTF8):].decode('utf-8') if contents[:len(codecs.BOM_UTF16_LE)] == codecs.BOM_UTF16_LE: return contents[len(codecs.BOM_UTF16_LE):].decode('utf-16-le') if contents[:len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: return contents[len(codecs.BOM_UTF16_BE):].decode('utf-16-be') try: return contents.decode('utf-8') except UnicodeDecodeError as e: try: return contents.decode('latin-1') except UnicodeDecodeError as e: return contents.decode('utf-8', error='backslashreplace')
python
def get_text_contents(self): contents = self.get_contents() # The behavior of various decode() methods and functions # w.r.t. the initial BOM bytes is different for different # encodings and/or Python versions. ('utf-8' does not strip # them, but has a 'utf-8-sig' which does; 'utf-16' seems to # strip them; etc.) Just sidestep all the complication by # explicitly stripping the BOM before we decode(). if contents[:len(codecs.BOM_UTF8)] == codecs.BOM_UTF8: return contents[len(codecs.BOM_UTF8):].decode('utf-8') if contents[:len(codecs.BOM_UTF16_LE)] == codecs.BOM_UTF16_LE: return contents[len(codecs.BOM_UTF16_LE):].decode('utf-16-le') if contents[:len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE: return contents[len(codecs.BOM_UTF16_BE):].decode('utf-16-be') try: return contents.decode('utf-8') except UnicodeDecodeError as e: try: return contents.decode('latin-1') except UnicodeDecodeError as e: return contents.decode('utf-8', error='backslashreplace')
[ "def", "get_text_contents", "(", "self", ")", ":", "contents", "=", "self", ".", "get_contents", "(", ")", "# The behavior of various decode() methods and functions", "# w.r.t. the initial BOM bytes is different for different", "# encodings and/or Python versions. ('utf-8' does not st...
This attempts to figure out what the encoding of the text is based upon the BOM bytes, and then decodes the contents so that it's a valid python string.
[ "This", "attempts", "to", "figure", "out", "what", "the", "encoding", "of", "the", "text", "is", "based", "upon", "the", "BOM", "bytes", "and", "then", "decodes", "the", "contents", "so", "that", "it", "s", "a", "valid", "python", "string", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2635-L2660
23,435
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_content_hash
def get_content_hash(self): """ Compute and return the MD5 hash for this file. """ if not self.rexists(): return SCons.Util.MD5signature('') fname = self.rfile().get_abspath() try: cs = SCons.Util.MD5filesignature(fname, chunksize=SCons.Node.FS.File.md5_chunksize*1024) except EnvironmentError as e: if not e.filename: e.filename = fname raise return cs
python
def get_content_hash(self): if not self.rexists(): return SCons.Util.MD5signature('') fname = self.rfile().get_abspath() try: cs = SCons.Util.MD5filesignature(fname, chunksize=SCons.Node.FS.File.md5_chunksize*1024) except EnvironmentError as e: if not e.filename: e.filename = fname raise return cs
[ "def", "get_content_hash", "(", "self", ")", ":", "if", "not", "self", ".", "rexists", "(", ")", ":", "return", "SCons", ".", "Util", ".", "MD5signature", "(", "''", ")", "fname", "=", "self", ".", "rfile", "(", ")", ".", "get_abspath", "(", ")", "...
Compute and return the MD5 hash for this file.
[ "Compute", "and", "return", "the", "MD5", "hash", "for", "this", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2663-L2677
23,436
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_found_includes
def get_found_includes(self, env, scanner, path): """Return the included implicit dependencies in this file. Cache results so we only scan the file once per path regardless of how many times this information is requested. """ memo_key = (id(env), id(scanner), path) try: memo_dict = self._memo['get_found_includes'] except KeyError: memo_dict = {} self._memo['get_found_includes'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass if scanner: result = [n.disambiguate() for n in scanner(self, env, path)] else: result = [] memo_dict[memo_key] = result return result
python
def get_found_includes(self, env, scanner, path): memo_key = (id(env), id(scanner), path) try: memo_dict = self._memo['get_found_includes'] except KeyError: memo_dict = {} self._memo['get_found_includes'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass if scanner: result = [n.disambiguate() for n in scanner(self, env, path)] else: result = [] memo_dict[memo_key] = result return result
[ "def", "get_found_includes", "(", "self", ",", "env", ",", "scanner", ",", "path", ")", ":", "memo_key", "=", "(", "id", "(", "env", ")", ",", "id", "(", "scanner", ")", ",", "path", ")", "try", ":", "memo_dict", "=", "self", ".", "_memo", "[", "...
Return the included implicit dependencies in this file. Cache results so we only scan the file once per path regardless of how many times this information is requested.
[ "Return", "the", "included", "implicit", "dependencies", "in", "this", "file", ".", "Cache", "results", "so", "we", "only", "scan", "the", "file", "once", "per", "path", "regardless", "of", "how", "many", "times", "this", "information", "is", "requested", "....
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2864-L2888
23,437
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.push_to_cache
def push_to_cache(self): """Try to push the node into a cache """ # This should get called before the Nodes' .built() method is # called, which would clear the build signature if the file has # a source scanner. # # We have to clear the local memoized values *before* we push # the node to cache so that the memoization of the self.exists() # return value doesn't interfere. if self.nocache: return self.clear_memoized_values() if self.exists(): self.get_build_env().get_CacheDir().push(self)
python
def push_to_cache(self): # This should get called before the Nodes' .built() method is # called, which would clear the build signature if the file has # a source scanner. # # We have to clear the local memoized values *before* we push # the node to cache so that the memoization of the self.exists() # return value doesn't interfere. if self.nocache: return self.clear_memoized_values() if self.exists(): self.get_build_env().get_CacheDir().push(self)
[ "def", "push_to_cache", "(", "self", ")", ":", "# This should get called before the Nodes' .built() method is", "# called, which would clear the build signature if the file has", "# a source scanner.", "#", "# We have to clear the local memoized values *before* we push", "# the node to cache s...
Try to push the node into a cache
[ "Try", "to", "push", "the", "node", "into", "a", "cache" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2895-L2909
23,438
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.retrieve_from_cache
def retrieve_from_cache(self): """Try to retrieve the node's content from a cache This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Returns true if the node was successfully retrieved. """ if self.nocache: return None if not self.is_derived(): return None return self.get_build_env().get_CacheDir().retrieve(self)
python
def retrieve_from_cache(self): if self.nocache: return None if not self.is_derived(): return None return self.get_build_env().get_CacheDir().retrieve(self)
[ "def", "retrieve_from_cache", "(", "self", ")", ":", "if", "self", ".", "nocache", ":", "return", "None", "if", "not", "self", ".", "is_derived", "(", ")", ":", "return", "None", "return", "self", ".", "get_build_env", "(", ")", ".", "get_CacheDir", "(",...
Try to retrieve the node's content from a cache This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built(). Returns true if the node was successfully retrieved.
[ "Try", "to", "retrieve", "the", "node", "s", "content", "from", "a", "cache" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2911-L2924
23,439
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.release_target_info
def release_target_info(self): """Called just after this node has been marked up-to-date or was built completely. This is where we try to release as many target node infos as possible for clean builds and update runs, in order to minimize the overall memory consumption. We'd like to remove a lot more attributes like self.sources and self.sources_set, but they might get used in a next build step. For example, during configuration the source files for a built E{*}.o file are used to figure out which linker to use for the resulting Program (gcc vs. g++)! That's why we check for the 'keep_targetinfo' attribute, config Nodes and the Interactive mode just don't allow an early release of most variables. In the same manner, we can't simply remove the self.attributes here. The smart linking relies on the shared flag, and some parts of the java Tool use it to transport information about nodes... @see: built() and Node.release_target_info() """ if (self.released_target_info or SCons.Node.interactive): return if not hasattr(self.attributes, 'keep_targetinfo'): # Cache some required values, before releasing # stuff like env, executor and builder... self.changed(allowcache=True) self.get_contents_sig() self.get_build_env() # Now purge unneeded stuff to free memory... self.executor = None self._memo.pop('rfile', None) self.prerequisites = None # Cleanup lists, but only if they're empty if not len(self.ignore_set): self.ignore_set = None if not len(self.implicit_set): self.implicit_set = None if not len(self.depends_set): self.depends_set = None if not len(self.ignore): self.ignore = None if not len(self.depends): self.depends = None # Mark this node as done, we only have to release # the memory once... self.released_target_info = True
python
def release_target_info(self): if (self.released_target_info or SCons.Node.interactive): return if not hasattr(self.attributes, 'keep_targetinfo'): # Cache some required values, before releasing # stuff like env, executor and builder... self.changed(allowcache=True) self.get_contents_sig() self.get_build_env() # Now purge unneeded stuff to free memory... self.executor = None self._memo.pop('rfile', None) self.prerequisites = None # Cleanup lists, but only if they're empty if not len(self.ignore_set): self.ignore_set = None if not len(self.implicit_set): self.implicit_set = None if not len(self.depends_set): self.depends_set = None if not len(self.ignore): self.ignore = None if not len(self.depends): self.depends = None # Mark this node as done, we only have to release # the memory once... self.released_target_info = True
[ "def", "release_target_info", "(", "self", ")", ":", "if", "(", "self", ".", "released_target_info", "or", "SCons", ".", "Node", ".", "interactive", ")", ":", "return", "if", "not", "hasattr", "(", "self", ".", "attributes", ",", "'keep_targetinfo'", ")", ...
Called just after this node has been marked up-to-date or was built completely. This is where we try to release as many target node infos as possible for clean builds and update runs, in order to minimize the overall memory consumption. We'd like to remove a lot more attributes like self.sources and self.sources_set, but they might get used in a next build step. For example, during configuration the source files for a built E{*}.o file are used to figure out which linker to use for the resulting Program (gcc vs. g++)! That's why we check for the 'keep_targetinfo' attribute, config Nodes and the Interactive mode just don't allow an early release of most variables. In the same manner, we can't simply remove the self.attributes here. The smart linking relies on the shared flag, and some parts of the java Tool use it to transport information about nodes... @see: built() and Node.release_target_info()
[ "Called", "just", "after", "this", "node", "has", "been", "marked", "up", "-", "to", "-", "date", "or", "was", "built", "completely", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L2949-L2999
23,440
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.has_src_builder
def has_src_builder(self): """Return whether this Node has a source builder or not. If this Node doesn't have an explicit source code builder, this is where we figure out, on the fly, if there's a transparent source code builder for it. Note that if we found a source builder, we also set the self.builder attribute, so that all of the methods that actually *build* this file don't have to do anything different. """ try: scb = self.sbuilder except AttributeError: scb = self.sbuilder = self.find_src_builder() return scb is not None
python
def has_src_builder(self): try: scb = self.sbuilder except AttributeError: scb = self.sbuilder = self.find_src_builder() return scb is not None
[ "def", "has_src_builder", "(", "self", ")", ":", "try", ":", "scb", "=", "self", ".", "sbuilder", "except", "AttributeError", ":", "scb", "=", "self", ".", "sbuilder", "=", "self", ".", "find_src_builder", "(", ")", "return", "scb", "is", "not", "None" ]
Return whether this Node has a source builder or not. If this Node doesn't have an explicit source code builder, this is where we figure out, on the fly, if there's a transparent source code builder for it. Note that if we found a source builder, we also set the self.builder attribute, so that all of the methods that actually *build* this file don't have to do anything different.
[ "Return", "whether", "this", "Node", "has", "a", "source", "builder", "or", "not", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3016-L3031
23,441
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.alter_targets
def alter_targets(self): """Return any corresponding targets in a variant directory. """ if self.is_derived(): return [], None return self.fs.variant_dir_target_climb(self, self.dir, [self.name])
python
def alter_targets(self): if self.is_derived(): return [], None return self.fs.variant_dir_target_climb(self, self.dir, [self.name])
[ "def", "alter_targets", "(", "self", ")", ":", "if", "self", ".", "is_derived", "(", ")", ":", "return", "[", "]", ",", "None", "return", "self", ".", "fs", ".", "variant_dir_target_climb", "(", "self", ",", "self", ".", "dir", ",", "[", "self", ".",...
Return any corresponding targets in a variant directory.
[ "Return", "any", "corresponding", "targets", "in", "a", "variant", "directory", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3033-L3038
23,442
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.prepare
def prepare(self): """Prepare for this file to be created.""" SCons.Node.Node.prepare(self) if self.get_state() != SCons.Node.up_to_date: if self.exists(): if self.is_derived() and not self.precious: self._rmv_existing() else: try: self._createDir() except SCons.Errors.StopError as drive: raise SCons.Errors.StopError("No drive `{}' for target `{}'.".format(drive, self))
python
def prepare(self): SCons.Node.Node.prepare(self) if self.get_state() != SCons.Node.up_to_date: if self.exists(): if self.is_derived() and not self.precious: self._rmv_existing() else: try: self._createDir() except SCons.Errors.StopError as drive: raise SCons.Errors.StopError("No drive `{}' for target `{}'.".format(drive, self))
[ "def", "prepare", "(", "self", ")", ":", "SCons", ".", "Node", ".", "Node", ".", "prepare", "(", "self", ")", "if", "self", ".", "get_state", "(", ")", "!=", "SCons", ".", "Node", ".", "up_to_date", ":", "if", "self", ".", "exists", "(", ")", ":"...
Prepare for this file to be created.
[ "Prepare", "for", "this", "file", "to", "be", "created", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3056-L3068
23,443
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.remove
def remove(self): """Remove this file.""" if self.exists() or self.islink(): self.fs.unlink(self.get_internal_path()) return 1 return None
python
def remove(self): if self.exists() or self.islink(): self.fs.unlink(self.get_internal_path()) return 1 return None
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "exists", "(", ")", "or", "self", ".", "islink", "(", ")", ":", "self", ".", "fs", ".", "unlink", "(", "self", ".", "get_internal_path", "(", ")", ")", "return", "1", "return", "None" ]
Remove this file.
[ "Remove", "this", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3074-L3079
23,444
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_max_drift_csig
def get_max_drift_csig(self): """ Returns the content signature currently stored for this node if it's been unmodified longer than the max_drift value, or the max_drift value is 0. Returns None otherwise. """ old = self.get_stored_info() mtime = self.get_timestamp() max_drift = self.fs.max_drift if max_drift > 0: if (time.time() - mtime) > max_drift: try: n = old.ninfo if n.timestamp and n.csig and n.timestamp == mtime: return n.csig except AttributeError: pass elif max_drift == 0: try: return old.ninfo.csig except AttributeError: pass return None
python
def get_max_drift_csig(self): old = self.get_stored_info() mtime = self.get_timestamp() max_drift = self.fs.max_drift if max_drift > 0: if (time.time() - mtime) > max_drift: try: n = old.ninfo if n.timestamp and n.csig and n.timestamp == mtime: return n.csig except AttributeError: pass elif max_drift == 0: try: return old.ninfo.csig except AttributeError: pass return None
[ "def", "get_max_drift_csig", "(", "self", ")", ":", "old", "=", "self", ".", "get_stored_info", "(", ")", "mtime", "=", "self", ".", "get_timestamp", "(", ")", "max_drift", "=", "self", ".", "fs", ".", "max_drift", "if", "max_drift", ">", "0", ":", "if...
Returns the content signature currently stored for this node if it's been unmodified longer than the max_drift value, or the max_drift value is 0. Returns None otherwise.
[ "Returns", "the", "content", "signature", "currently", "stored", "for", "this", "node", "if", "it", "s", "been", "unmodified", "longer", "than", "the", "max_drift", "value", "or", "the", "max_drift", "value", "is", "0", ".", "Returns", "None", "otherwise", "...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3110-L3134
23,445
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.built
def built(self): """Called just after this File node is successfully built. Just like for 'release_target_info' we try to release some more target node attributes in order to minimize the overall memory consumption. @see: release_target_info """ SCons.Node.Node.built(self) if (not SCons.Node.interactive and not hasattr(self.attributes, 'keep_targetinfo')): # Ensure that the build infos get computed and cached... SCons.Node.store_info_map[self.store_info](self) # ... then release some more variables. self._specific_sources = False self._labspath = None self._save_str() self.cwd = None self.scanner_paths = None
python
def built(self): SCons.Node.Node.built(self) if (not SCons.Node.interactive and not hasattr(self.attributes, 'keep_targetinfo')): # Ensure that the build infos get computed and cached... SCons.Node.store_info_map[self.store_info](self) # ... then release some more variables. self._specific_sources = False self._labspath = None self._save_str() self.cwd = None self.scanner_paths = None
[ "def", "built", "(", "self", ")", ":", "SCons", ".", "Node", ".", "Node", ".", "built", "(", "self", ")", "if", "(", "not", "SCons", ".", "Node", ".", "interactive", "and", "not", "hasattr", "(", "self", ".", "attributes", ",", "'keep_targetinfo'", "...
Called just after this File node is successfully built. Just like for 'release_target_info' we try to release some more target node attributes in order to minimize the overall memory consumption. @see: release_target_info
[ "Called", "just", "after", "this", "File", "node", "is", "successfully", "built", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3181-L3203
23,446
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.changed
def changed(self, node=None, allowcache=False): """ Returns if the node is up-to-date with respect to the BuildInfo stored last time it was built. For File nodes this is basically a wrapper around Node.changed(), but we allow the return value to get cached after the reference to the Executor got released in release_target_info(). @see: Node.changed() """ if node is None: try: return self._memo['changed'] except KeyError: pass has_changed = SCons.Node.Node.changed(self, node) if allowcache: self._memo['changed'] = has_changed return has_changed
python
def changed(self, node=None, allowcache=False): if node is None: try: return self._memo['changed'] except KeyError: pass has_changed = SCons.Node.Node.changed(self, node) if allowcache: self._memo['changed'] = has_changed return has_changed
[ "def", "changed", "(", "self", ",", "node", "=", "None", ",", "allowcache", "=", "False", ")", ":", "if", "node", "is", "None", ":", "try", ":", "return", "self", ".", "_memo", "[", "'changed'", "]", "except", "KeyError", ":", "pass", "has_changed", ...
Returns if the node is up-to-date with respect to the BuildInfo stored last time it was built. For File nodes this is basically a wrapper around Node.changed(), but we allow the return value to get cached after the reference to the Executor got released in release_target_info(). @see: Node.changed()
[ "Returns", "if", "the", "node", "is", "up", "-", "to", "-", "date", "with", "respect", "to", "the", "BuildInfo", "stored", "last", "time", "it", "was", "built", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3205-L3225
23,447
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_cachedir_csig
def get_cachedir_csig(self): """ Fetch a Node's content signature for purposes of computing another Node's cachesig. This is a wrapper around the normal get_csig() method that handles the somewhat obscure case of using CacheDir with the -n option. Any files that don't exist would normally be "built" by fetching them from the cache, but the normal get_csig() method will try to open up the local file, which doesn't exist because the -n option meant we didn't actually pull the file from cachedir. But since the file *does* actually exist in the cachedir, we can use its contents for the csig. """ try: return self.cachedir_csig except AttributeError: pass cachedir, cachefile = self.get_build_env().get_CacheDir().cachepath(self) if not self.exists() and cachefile and os.path.exists(cachefile): self.cachedir_csig = SCons.Util.MD5filesignature(cachefile, \ SCons.Node.FS.File.md5_chunksize * 1024) else: self.cachedir_csig = self.get_csig() return self.cachedir_csig
python
def get_cachedir_csig(self): try: return self.cachedir_csig except AttributeError: pass cachedir, cachefile = self.get_build_env().get_CacheDir().cachepath(self) if not self.exists() and cachefile and os.path.exists(cachefile): self.cachedir_csig = SCons.Util.MD5filesignature(cachefile, \ SCons.Node.FS.File.md5_chunksize * 1024) else: self.cachedir_csig = self.get_csig() return self.cachedir_csig
[ "def", "get_cachedir_csig", "(", "self", ")", ":", "try", ":", "return", "self", ".", "cachedir_csig", "except", "AttributeError", ":", "pass", "cachedir", ",", "cachefile", "=", "self", ".", "get_build_env", "(", ")", ".", "get_CacheDir", "(", ")", ".", "...
Fetch a Node's content signature for purposes of computing another Node's cachesig. This is a wrapper around the normal get_csig() method that handles the somewhat obscure case of using CacheDir with the -n option. Any files that don't exist would normally be "built" by fetching them from the cache, but the normal get_csig() method will try to open up the local file, which doesn't exist because the -n option meant we didn't actually pull the file from cachedir. But since the file *does* actually exist in the cachedir, we can use its contents for the csig.
[ "Fetch", "a", "Node", "s", "content", "signature", "for", "purposes", "of", "computing", "another", "Node", "s", "cachesig", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3322-L3347
23,448
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_contents_sig
def get_contents_sig(self): """ A helper method for get_cachedir_bsig. It computes and returns the signature for this node's contents. """ try: return self.contentsig except AttributeError: pass executor = self.get_executor() result = self.contentsig = SCons.Util.MD5signature(executor.get_contents()) return result
python
def get_contents_sig(self): try: return self.contentsig except AttributeError: pass executor = self.get_executor() result = self.contentsig = SCons.Util.MD5signature(executor.get_contents()) return result
[ "def", "get_contents_sig", "(", "self", ")", ":", "try", ":", "return", "self", ".", "contentsig", "except", "AttributeError", ":", "pass", "executor", "=", "self", ".", "get_executor", "(", ")", "result", "=", "self", ".", "contentsig", "=", "SCons", ".",...
A helper method for get_cachedir_bsig. It computes and returns the signature for this node's contents.
[ "A", "helper", "method", "for", "get_cachedir_bsig", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3349-L3365
23,449
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
File.get_cachedir_bsig
def get_cachedir_bsig(self): """ Return the signature for a cached file, including its children. It adds the path of the cached file to the cache signature, because multiple targets built by the same action will all have the same build signature, and we have to differentiate them somehow. """ try: return self.cachesig except AttributeError: pass # Collect signatures for all children children = self.children() sigs = [n.get_cachedir_csig() for n in children] # Append this node's signature... sigs.append(self.get_contents_sig()) # ...and it's path sigs.append(self.get_internal_path()) # Merge this all into a single signature result = self.cachesig = SCons.Util.MD5collect(sigs) return result
python
def get_cachedir_bsig(self): try: return self.cachesig except AttributeError: pass # Collect signatures for all children children = self.children() sigs = [n.get_cachedir_csig() for n in children] # Append this node's signature... sigs.append(self.get_contents_sig()) # ...and it's path sigs.append(self.get_internal_path()) # Merge this all into a single signature result = self.cachesig = SCons.Util.MD5collect(sigs) return result
[ "def", "get_cachedir_bsig", "(", "self", ")", ":", "try", ":", "return", "self", ".", "cachesig", "except", "AttributeError", ":", "pass", "# Collect signatures for all children", "children", "=", "self", ".", "children", "(", ")", "sigs", "=", "[", "n", ".", ...
Return the signature for a cached file, including its children. It adds the path of the cached file to the cache signature, because multiple targets built by the same action will all have the same build signature, and we have to differentiate them somehow.
[ "Return", "the", "signature", "for", "a", "cached", "file", "including", "its", "children", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3367-L3391
23,450
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py
FileFinder.find_file
def find_file(self, filename, paths, verbose=None): """ Find a node corresponding to either a derived file or a file that exists already. Only the first file found is returned, and none is returned if no file is found. filename: A filename to find paths: A list of directory path *nodes* to search in. Can be represented as a list, a tuple, or a callable that is called with no arguments and returns the list or tuple. returns The node created from the found file. """ memo_key = self._find_file_key(filename, paths) try: memo_dict = self._memo['find_file'] except KeyError: memo_dict = {} self._memo['find_file'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass if verbose and not callable(verbose): if not SCons.Util.is_String(verbose): verbose = "find_file" _verbose = u' %s: ' % verbose verbose = lambda s: sys.stdout.write(_verbose + s) filedir, filename = os.path.split(filename) if filedir: self.default_filedir = filedir paths = [_f for _f in map(self.filedir_lookup, paths) if _f] result = None for dir in paths: if verbose: verbose("looking for '%s' in '%s' ...\n" % (filename, dir)) node, d = dir.srcdir_find_file(filename) if node: if verbose: verbose("... FOUND '%s' in '%s'\n" % (filename, d)) result = node break memo_dict[memo_key] = result return result
python
def find_file(self, filename, paths, verbose=None): memo_key = self._find_file_key(filename, paths) try: memo_dict = self._memo['find_file'] except KeyError: memo_dict = {} self._memo['find_file'] = memo_dict else: try: return memo_dict[memo_key] except KeyError: pass if verbose and not callable(verbose): if not SCons.Util.is_String(verbose): verbose = "find_file" _verbose = u' %s: ' % verbose verbose = lambda s: sys.stdout.write(_verbose + s) filedir, filename = os.path.split(filename) if filedir: self.default_filedir = filedir paths = [_f for _f in map(self.filedir_lookup, paths) if _f] result = None for dir in paths: if verbose: verbose("looking for '%s' in '%s' ...\n" % (filename, dir)) node, d = dir.srcdir_find_file(filename) if node: if verbose: verbose("... FOUND '%s' in '%s'\n" % (filename, d)) result = node break memo_dict[memo_key] = result return result
[ "def", "find_file", "(", "self", ",", "filename", ",", "paths", ",", "verbose", "=", "None", ")", ":", "memo_key", "=", "self", ".", "_find_file_key", "(", "filename", ",", "paths", ")", "try", ":", "memo_dict", "=", "self", ".", "_memo", "[", "'find_f...
Find a node corresponding to either a derived file or a file that exists already. Only the first file found is returned, and none is returned if no file is found. filename: A filename to find paths: A list of directory path *nodes* to search in. Can be represented as a list, a tuple, or a callable that is called with no arguments and returns the list or tuple. returns The node created from the found file.
[ "Find", "a", "node", "corresponding", "to", "either", "a", "derived", "file", "or", "a", "file", "that", "exists", "already", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L3447-L3495
23,451
iotile/coretools
iotileship/iotile/ship/actions/send_ota_script_step.py
SendOTAScriptStep.run
def run(self, resources): """Actually send the trub script. Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step. """ hwman = resources['connection'] updater = hwman.hwman.app(name='device_updater') updater.run_script(self._script, no_reboot=self._no_reboot)
python
def run(self, resources): hwman = resources['connection'] updater = hwman.hwman.app(name='device_updater') updater.run_script(self._script, no_reboot=self._no_reboot)
[ "def", "run", "(", "self", ",", "resources", ")", ":", "hwman", "=", "resources", "[", "'connection'", "]", "updater", "=", "hwman", ".", "hwman", ".", "app", "(", "name", "=", "'device_updater'", ")", "updater", ".", "run_script", "(", "self", ".", "_...
Actually send the trub script. Args: resources (dict): A dictionary containing the required resources that we needed access to in order to perform this step.
[ "Actually", "send", "the", "trub", "script", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileship/iotile/ship/actions/send_ota_script_step.py#L38-L49
23,452
iotile/coretools
transport_plugins/bled112/iotile_transport_bled112/bgapi_structures.py
process_gatt_service
def process_gatt_service(services, event): """Process a BGAPI event containing a GATT service description and add it to a dictionary Args: services (dict): A dictionary of discovered services that is updated with this event event (BGAPIPacket): An event containing a GATT service """ length = len(event.payload) - 5 handle, start, end, uuid = unpack('<BHH%ds' % length, event.payload) uuid = process_uuid(uuid) services[uuid] = {'uuid_raw': uuid, 'start_handle': start, 'end_handle': end}
python
def process_gatt_service(services, event): length = len(event.payload) - 5 handle, start, end, uuid = unpack('<BHH%ds' % length, event.payload) uuid = process_uuid(uuid) services[uuid] = {'uuid_raw': uuid, 'start_handle': start, 'end_handle': end}
[ "def", "process_gatt_service", "(", "services", ",", "event", ")", ":", "length", "=", "len", "(", "event", ".", "payload", ")", "-", "5", "handle", ",", "start", ",", "end", ",", "uuid", "=", "unpack", "(", "'<BHH%ds'", "%", "length", ",", "event", ...
Process a BGAPI event containing a GATT service description and add it to a dictionary Args: services (dict): A dictionary of discovered services that is updated with this event event (BGAPIPacket): An event containing a GATT service
[ "Process", "a", "BGAPI", "event", "containing", "a", "GATT", "service", "description", "and", "add", "it", "to", "a", "dictionary" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bgapi_structures.py#L27-L41
23,453
iotile/coretools
transport_plugins/bled112/iotile_transport_bled112/bgapi_structures.py
handle_to_uuid
def handle_to_uuid(handle, services): """Find the corresponding UUID for an attribute handle""" for service in services.values(): for char_uuid, char_def in service['characteristics'].items(): if char_def['handle'] == handle: return char_uuid raise ValueError("Handle not found in GATT table")
python
def handle_to_uuid(handle, services): for service in services.values(): for char_uuid, char_def in service['characteristics'].items(): if char_def['handle'] == handle: return char_uuid raise ValueError("Handle not found in GATT table")
[ "def", "handle_to_uuid", "(", "handle", ",", "services", ")", ":", "for", "service", "in", "services", ".", "values", "(", ")", ":", "for", "char_uuid", ",", "char_def", "in", "service", "[", "'characteristics'", "]", ".", "items", "(", ")", ":", "if", ...
Find the corresponding UUID for an attribute handle
[ "Find", "the", "corresponding", "UUID", "for", "an", "attribute", "handle" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bgapi_structures.py#L87-L95
23,454
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/BoolVariable.py
_validator
def _validator(key, val, env): """ Validates the given value to be either '0' or '1'. This is usable as 'validator' for SCons' Variables. """ if not env[key] in (True, False): raise SCons.Errors.UserError( 'Invalid value for boolean option %s: %s' % (key, env[key]))
python
def _validator(key, val, env): if not env[key] in (True, False): raise SCons.Errors.UserError( 'Invalid value for boolean option %s: %s' % (key, env[key]))
[ "def", "_validator", "(", "key", ",", "val", ",", "env", ")", ":", "if", "not", "env", "[", "key", "]", "in", "(", "True", ",", "False", ")", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'Invalid value for boolean option %s: %s'", "%", ...
Validates the given value to be either '0' or '1'. This is usable as 'validator' for SCons' Variables.
[ "Validates", "the", "given", "value", "to", "be", "either", "0", "or", "1", ".", "This", "is", "usable", "as", "validator", "for", "SCons", "Variables", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Variables/BoolVariable.py#L64-L72
23,455
iotile/coretools
iotilegateway/iotilegateway/supervisor/states.py
ServiceMessage.FromDictionary
def FromDictionary(cls, msg_dict): """Create from a dictionary with kv pairs. Args: msg_dict (dict): A dictionary with information as created by to_dict() Returns: ServiceMessage: the converted message """ level = msg_dict.get('level') msg = msg_dict.get('message') now = msg_dict.get('now_time') created = msg_dict.get('created_time') count = msg_dict.get('count', 1) msg_id = msg_dict.get('id', 0) new_msg = ServiceMessage(level, msg, msg_id, created, now) if count > 1: new_msg.count = count return new_msg
python
def FromDictionary(cls, msg_dict): level = msg_dict.get('level') msg = msg_dict.get('message') now = msg_dict.get('now_time') created = msg_dict.get('created_time') count = msg_dict.get('count', 1) msg_id = msg_dict.get('id', 0) new_msg = ServiceMessage(level, msg, msg_id, created, now) if count > 1: new_msg.count = count return new_msg
[ "def", "FromDictionary", "(", "cls", ",", "msg_dict", ")", ":", "level", "=", "msg_dict", ".", "get", "(", "'level'", ")", "msg", "=", "msg_dict", ".", "get", "(", "'message'", ")", "now", "=", "msg_dict", ".", "get", "(", "'now_time'", ")", "created",...
Create from a dictionary with kv pairs. Args: msg_dict (dict): A dictionary with information as created by to_dict() Returns: ServiceMessage: the converted message
[ "Create", "from", "a", "dictionary", "with", "kv", "pairs", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/states.py#L65-L86
23,456
iotile/coretools
iotilegateway/iotilegateway/supervisor/states.py
ServiceMessage.to_dict
def to_dict(self): """Create a dictionary with the information in this message. Returns: dict: The dictionary with information """ msg_dict = {} msg_dict['level'] = self.level msg_dict['message'] = self.message msg_dict['now_time'] = monotonic() msg_dict['created_time'] = self.created msg_dict['id'] = self.id msg_dict['count'] = self.count return msg_dict
python
def to_dict(self): msg_dict = {} msg_dict['level'] = self.level msg_dict['message'] = self.message msg_dict['now_time'] = monotonic() msg_dict['created_time'] = self.created msg_dict['id'] = self.id msg_dict['count'] = self.count return msg_dict
[ "def", "to_dict", "(", "self", ")", ":", "msg_dict", "=", "{", "}", "msg_dict", "[", "'level'", "]", "=", "self", ".", "level", "msg_dict", "[", "'message'", "]", "=", "self", ".", "message", "msg_dict", "[", "'now_time'", "]", "=", "monotonic", "(", ...
Create a dictionary with the information in this message. Returns: dict: The dictionary with information
[ "Create", "a", "dictionary", "with", "the", "information", "in", "this", "message", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/states.py#L88-L103
23,457
iotile/coretools
iotilegateway/iotilegateway/supervisor/states.py
ServiceState.get_message
def get_message(self, message_id): """Get a message by its persistent id. Args: message_id (int): The id of the message that we're looking for """ for message in self.messages: if message.id == message_id: return message raise ArgumentError("Message ID not found", message_id=message_id)
python
def get_message(self, message_id): for message in self.messages: if message.id == message_id: return message raise ArgumentError("Message ID not found", message_id=message_id)
[ "def", "get_message", "(", "self", ",", "message_id", ")", ":", "for", "message", "in", "self", ".", "messages", ":", "if", "message", ".", "id", "==", "message_id", ":", "return", "message", "raise", "ArgumentError", "(", "\"Message ID not found\"", ",", "m...
Get a message by its persistent id. Args: message_id (int): The id of the message that we're looking for
[ "Get", "a", "message", "by", "its", "persistent", "id", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/states.py#L164-L175
23,458
iotile/coretools
iotilegateway/iotilegateway/supervisor/states.py
ServiceState.post_message
def post_message(self, level, message, count=1, timestamp=None, now_reference=None): """Post a new message for service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents count (int): The number of times the message has been repeated timestamp (float): An optional monotonic value in seconds for when the message was created now_reference (float): If timestamp is not relative to monotonic() as called from this module then this should be now() as seen by whoever created the timestamp. Returns: ServiceMessage: The posted message """ if len(self.messages) > 0 and self.messages[-1].message == message: self.messages[-1].count += 1 else: msg_object = ServiceMessage(level, message, self._last_message_id, timestamp, now_reference) msg_object.count = count self.messages.append(msg_object) self._last_message_id += 1 return self.messages[-1]
python
def post_message(self, level, message, count=1, timestamp=None, now_reference=None): if len(self.messages) > 0 and self.messages[-1].message == message: self.messages[-1].count += 1 else: msg_object = ServiceMessage(level, message, self._last_message_id, timestamp, now_reference) msg_object.count = count self.messages.append(msg_object) self._last_message_id += 1 return self.messages[-1]
[ "def", "post_message", "(", "self", ",", "level", ",", "message", ",", "count", "=", "1", ",", "timestamp", "=", "None", ",", "now_reference", "=", "None", ")", ":", "if", "len", "(", "self", ".", "messages", ")", ">", "0", "and", "self", ".", "mes...
Post a new message for service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents count (int): The number of times the message has been repeated timestamp (float): An optional monotonic value in seconds for when the message was created now_reference (float): If timestamp is not relative to monotonic() as called from this module then this should be now() as seen by whoever created the timestamp. Returns: ServiceMessage: The posted message
[ "Post", "a", "new", "message", "for", "service", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/states.py#L177-L200
23,459
iotile/coretools
iotilegateway/iotilegateway/supervisor/states.py
ServiceState.set_headline
def set_headline(self, level, message, timestamp=None, now_reference=None): """Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An optional monotonic value in seconds for when the message was created now_reference (float): If timestamp is not relative to monotonic() as called from this module then this should be now() as seen by whoever created the timestamp. """ if self.headline is not None and self.headline.message == message: self.headline.created = monotonic() self.headline.count += 1 return msg_object = ServiceMessage(level, message, self._last_message_id, timestamp, now_reference) self.headline = msg_object self._last_message_id += 1
python
def set_headline(self, level, message, timestamp=None, now_reference=None): if self.headline is not None and self.headline.message == message: self.headline.created = monotonic() self.headline.count += 1 return msg_object = ServiceMessage(level, message, self._last_message_id, timestamp, now_reference) self.headline = msg_object self._last_message_id += 1
[ "def", "set_headline", "(", "self", ",", "level", ",", "message", ",", "timestamp", "=", "None", ",", "now_reference", "=", "None", ")", ":", "if", "self", ".", "headline", "is", "not", "None", "and", "self", ".", "headline", ".", "message", "==", "mes...
Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An optional monotonic value in seconds for when the message was created now_reference (float): If timestamp is not relative to monotonic() as called from this module then this should be now() as seen by whoever created the timestamp.
[ "Set", "the", "persistent", "headline", "message", "for", "this", "service", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/states.py#L202-L220
23,460
iotile/coretools
iotilebuild/iotile/build/config/site_scons/docbuild.py
generate_doxygen_file
def generate_doxygen_file(output_path, iotile): """Fill in our default doxygen template file with info from an IOTile This populates things like name, version, etc. Arguments: output_path (str): a string path for where the filled template should go iotile (IOTile): An IOTile object that can be queried for information """ mapping = {} mapping['short_name'] = iotile.short_name mapping['full_name'] = iotile.full_name mapping['authors'] = iotile.authors mapping['version'] = iotile.version render_template('doxygen.txt.tpl', mapping, out_path=output_path)
python
def generate_doxygen_file(output_path, iotile): mapping = {} mapping['short_name'] = iotile.short_name mapping['full_name'] = iotile.full_name mapping['authors'] = iotile.authors mapping['version'] = iotile.version render_template('doxygen.txt.tpl', mapping, out_path=output_path)
[ "def", "generate_doxygen_file", "(", "output_path", ",", "iotile", ")", ":", "mapping", "=", "{", "}", "mapping", "[", "'short_name'", "]", "=", "iotile", ".", "short_name", "mapping", "[", "'full_name'", "]", "=", "iotile", ".", "full_name", "mapping", "[",...
Fill in our default doxygen template file with info from an IOTile This populates things like name, version, etc. Arguments: output_path (str): a string path for where the filled template should go iotile (IOTile): An IOTile object that can be queried for information
[ "Fill", "in", "our", "default", "doxygen", "template", "file", "with", "info", "from", "an", "IOTile" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/docbuild.py#L4-L21
23,461
iotile/coretools
iotilebuild/iotile/build/dev/pull_release.py
pull
def pull(name, version, force=False): """Pull a released IOTile component into the current working directory The component is found using whatever DependencyResolvers are installed and registered as part of the default DependencyResolverChain. This is the same mechanism used in iotile depends update, so any component that can be updated using iotile depends update can be found and pulled using this method. """ chain = DependencyResolverChain() ver = SemanticVersionRange.FromString(version) chain.pull_release(name, ver, force=force)
python
def pull(name, version, force=False): chain = DependencyResolverChain() ver = SemanticVersionRange.FromString(version) chain.pull_release(name, ver, force=force)
[ "def", "pull", "(", "name", ",", "version", ",", "force", "=", "False", ")", ":", "chain", "=", "DependencyResolverChain", "(", ")", "ver", "=", "SemanticVersionRange", ".", "FromString", "(", "version", ")", "chain", ".", "pull_release", "(", "name", ",",...
Pull a released IOTile component into the current working directory The component is found using whatever DependencyResolvers are installed and registered as part of the default DependencyResolverChain. This is the same mechanism used in iotile depends update, so any component that can be updated using iotile depends update can be found and pulled using this method.
[ "Pull", "a", "released", "IOTile", "component", "into", "the", "current", "working", "directory" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/dev/pull_release.py#L9-L21
23,462
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py
SynchronousLegacyWrapper.add_callback
def add_callback(self, name, func): """Add a callback when device events happen. Args: name (str): currently support 'on_scan' and 'on_disconnect' func (callable): the function that should be called """ if name == 'on_scan': events = ['device_seen'] def callback(_conn_string, _conn_id, _name, event): func(self.id, event, event.get('validity_period', 60)) elif name == 'on_report': events = ['report', 'broadcast'] def callback(_conn_string, conn_id, _name, event): func(conn_id, event) elif name == 'on_trace': events = ['trace'] def callback(_conn_string, conn_id, _name, event): func(conn_id, event) elif name == 'on_disconnect': events = ['disconnection'] def callback(_conn_string, conn_id, _name, _event): func(self.id, conn_id) else: raise ArgumentError("Unknown callback type {}".format(name)) self._adapter.register_monitor([None], events, callback)
python
def add_callback(self, name, func): if name == 'on_scan': events = ['device_seen'] def callback(_conn_string, _conn_id, _name, event): func(self.id, event, event.get('validity_period', 60)) elif name == 'on_report': events = ['report', 'broadcast'] def callback(_conn_string, conn_id, _name, event): func(conn_id, event) elif name == 'on_trace': events = ['trace'] def callback(_conn_string, conn_id, _name, event): func(conn_id, event) elif name == 'on_disconnect': events = ['disconnection'] def callback(_conn_string, conn_id, _name, _event): func(self.id, conn_id) else: raise ArgumentError("Unknown callback type {}".format(name)) self._adapter.register_monitor([None], events, callback)
[ "def", "add_callback", "(", "self", ",", "name", ",", "func", ")", ":", "if", "name", "==", "'on_scan'", ":", "events", "=", "[", "'device_seen'", "]", "def", "callback", "(", "_conn_string", ",", "_conn_id", ",", "_name", ",", "event", ")", ":", "func...
Add a callback when device events happen. Args: name (str): currently support 'on_scan' and 'on_disconnect' func (callable): the function that should be called
[ "Add", "a", "callback", "when", "device", "events", "happen", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py#L71-L98
23,463
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py
SynchronousLegacyWrapper.disconnect_async
def disconnect_async(self, conn_id, callback): """Asynchronously disconnect from a device.""" future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
python
def disconnect_async(self, conn_id, callback): future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
[ "def", "disconnect_async", "(", "self", ",", "conn_id", ",", "callback", ")", ":", "future", "=", "self", ".", "_loop", ".", "launch_coroutine", "(", "self", ".", "_adapter", ".", "disconnect", "(", "conn_id", ")", ")", "future", ".", "add_done_callback", ...
Asynchronously disconnect from a device.
[ "Asynchronously", "disconnect", "from", "a", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py#L120-L124
23,464
iotile/coretools
iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py
SynchronousLegacyWrapper.send_script_async
def send_script_async(self, conn_id, data, progress_callback, callback): """Asynchronously send a script to the device.""" def monitor_callback(_conn_string, _conn_id, _event_name, event): if event.get('operation') != 'script': return progress_callback(event.get('finished'), event.get('total')) async def _install_monitor(): try: conn_string = self._adapter._get_property(conn_id, 'connection_string') return self._adapter.register_monitor([conn_string], ['progress'], monitor_callback) except: #pylint:disable=bare-except;This is a legacy shim that must always ensure it doesn't raise. self._logger.exception("Error installing script progress monitor") return None monitor_id = self._loop.run_coroutine(_install_monitor()) if monitor_id is None: callback(conn_id, self.id, False, 'could not install progress monitor') return future = self._loop.launch_coroutine(self._adapter.send_script(conn_id, data)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback, monitors=[monitor_id]))
python
def send_script_async(self, conn_id, data, progress_callback, callback): def monitor_callback(_conn_string, _conn_id, _event_name, event): if event.get('operation') != 'script': return progress_callback(event.get('finished'), event.get('total')) async def _install_monitor(): try: conn_string = self._adapter._get_property(conn_id, 'connection_string') return self._adapter.register_monitor([conn_string], ['progress'], monitor_callback) except: #pylint:disable=bare-except;This is a legacy shim that must always ensure it doesn't raise. self._logger.exception("Error installing script progress monitor") return None monitor_id = self._loop.run_coroutine(_install_monitor()) if monitor_id is None: callback(conn_id, self.id, False, 'could not install progress monitor') return future = self._loop.launch_coroutine(self._adapter.send_script(conn_id, data)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback, monitors=[monitor_id]))
[ "def", "send_script_async", "(", "self", ",", "conn_id", ",", "data", ",", "progress_callback", ",", "callback", ")", ":", "def", "monitor_callback", "(", "_conn_string", ",", "_conn_id", ",", "_event_name", ",", "event", ")", ":", "if", "event", ".", "get",...
Asynchronously send a script to the device.
[ "Asynchronously", "send", "a", "script", "to", "the", "device", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py#L218-L241
23,465
iotile/coretools
transport_plugins/awsiot/iotile_transport_awsiot/topic_validator.py
MQTTTopicValidator.lock
def lock(self, key, client): """Set the key that will be used to ensure messages come from one party Args: key (string): The key used to validate future messages client (string): A string that will be returned to indicate who locked this device. """ self.key = key self.client = client
python
def lock(self, key, client): self.key = key self.client = client
[ "def", "lock", "(", "self", ",", "key", ",", "client", ")", ":", "self", ".", "key", "=", "key", "self", ".", "client", "=", "client" ]
Set the key that will be used to ensure messages come from one party Args: key (string): The key used to validate future messages client (string): A string that will be returned to indicate who locked this device.
[ "Set", "the", "key", "that", "will", "be", "used", "to", "ensure", "messages", "come", "from", "one", "party" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/topic_validator.py#L27-L37
23,466
iotile/coretools
iotileemulate/iotile/emulate/virtual/state_log.py
EmulationStateLog.track_change
def track_change(self, tile, property_name, value, formatter=None): """Record that a change happened on a given tile's property. This will as a StateChange object to our list of changes if we are recording changes, otherwise, it will drop the change. Args: tile (int): The address of the tile that the change happened on. property_name (str): The name of the property that changed. value (object): The new value assigned to the property. formatter (callable): Optional function to convert value to a string. This function will only be called if track_changes() is enabled and `name` is on the whitelist for properties that should be tracked. If `formatter` is not passed or is None, it will default to `str`. """ if not self.tracking: return if len(self._whitelist) > 0 and (tile, property_name) not in self._whitelist: return if formatter is None: formatter = str change = StateChange(monotonic(), tile, property_name, value, formatter(value)) with self._lock: self.changes.append(change)
python
def track_change(self, tile, property_name, value, formatter=None): if not self.tracking: return if len(self._whitelist) > 0 and (tile, property_name) not in self._whitelist: return if formatter is None: formatter = str change = StateChange(monotonic(), tile, property_name, value, formatter(value)) with self._lock: self.changes.append(change)
[ "def", "track_change", "(", "self", ",", "tile", ",", "property_name", ",", "value", ",", "formatter", "=", "None", ")", ":", "if", "not", "self", ".", "tracking", ":", "return", "if", "len", "(", "self", ".", "_whitelist", ")", ">", "0", "and", "(",...
Record that a change happened on a given tile's property. This will as a StateChange object to our list of changes if we are recording changes, otherwise, it will drop the change. Args: tile (int): The address of the tile that the change happened on. property_name (str): The name of the property that changed. value (object): The new value assigned to the property. formatter (callable): Optional function to convert value to a string. This function will only be called if track_changes() is enabled and `name` is on the whitelist for properties that should be tracked. If `formatter` is not passed or is None, it will default to `str`.
[ "Record", "that", "a", "change", "happened", "on", "a", "given", "tile", "s", "property", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/state_log.py#L21-L50
23,467
iotile/coretools
iotileemulate/iotile/emulate/virtual/state_log.py
EmulationStateLog.dump
def dump(self, out_path, header=True): """Save this list of changes as a csv file at out_path. The format of the output file will be a CSV with 4 columns: timestamp, tile address, property, string_value There will be a single header row starting the CSV output unless header=False is passed. Args: out_path (str): The path where we should save our current list of changes. header (bool): Whether we should include a header row in the csv file. Defaults to True. """ # See https://stackoverflow.com/a/3348664/9739119 for why this is necessary if sys.version_info[0] < 3: mode = "wb" else: mode = "w" with open(out_path, mode) as outfile: writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL) if header: writer.writerow(["Timestamp", "Tile Address", "Property Name", "Value"]) for entry in self.changes: writer.writerow([entry.time, entry.tile, entry.property, entry.string_value])
python
def dump(self, out_path, header=True): # See https://stackoverflow.com/a/3348664/9739119 for why this is necessary if sys.version_info[0] < 3: mode = "wb" else: mode = "w" with open(out_path, mode) as outfile: writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL) if header: writer.writerow(["Timestamp", "Tile Address", "Property Name", "Value"]) for entry in self.changes: writer.writerow([entry.time, entry.tile, entry.property, entry.string_value])
[ "def", "dump", "(", "self", ",", "out_path", ",", "header", "=", "True", ")", ":", "# See https://stackoverflow.com/a/3348664/9739119 for why this is necessary", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "mode", "=", "\"wb\"", "else", ":", ...
Save this list of changes as a csv file at out_path. The format of the output file will be a CSV with 4 columns: timestamp, tile address, property, string_value There will be a single header row starting the CSV output unless header=False is passed. Args: out_path (str): The path where we should save our current list of changes. header (bool): Whether we should include a header row in the csv file. Defaults to True.
[ "Save", "this", "list", "of", "changes", "as", "a", "csv", "file", "at", "out_path", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/state_log.py#L80-L108
23,468
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/pdftex.py
generate
def generate(env): """Add Builders and construction variables for pdftex to an Environment.""" global PDFTeXAction if PDFTeXAction is None: PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR') global PDFLaTeXAction if PDFLaTeXAction is None: PDFLaTeXAction = SCons.Action.Action("$PDFLATEXCOM", "$PDFLATEXCOMSTR") global PDFTeXLaTeXAction if PDFTeXLaTeXAction is None: PDFTeXLaTeXAction = SCons.Action.Action(PDFTeXLaTeXFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) from . import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.tex', PDFTeXLaTeXAction) bld.add_emitter('.tex', SCons.Tool.tex.tex_pdf_emitter) # Add the epstopdf builder after the pdftex builder # so pdftex is the default for no source suffix pdf.generate2(env) SCons.Tool.tex.generate_common(env)
python
def generate(env): global PDFTeXAction if PDFTeXAction is None: PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR') global PDFLaTeXAction if PDFLaTeXAction is None: PDFLaTeXAction = SCons.Action.Action("$PDFLATEXCOM", "$PDFLATEXCOMSTR") global PDFTeXLaTeXAction if PDFTeXLaTeXAction is None: PDFTeXLaTeXAction = SCons.Action.Action(PDFTeXLaTeXFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) from . import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.tex', PDFTeXLaTeXAction) bld.add_emitter('.tex', SCons.Tool.tex.tex_pdf_emitter) # Add the epstopdf builder after the pdftex builder # so pdftex is the default for no source suffix pdf.generate2(env) SCons.Tool.tex.generate_common(env)
[ "def", "generate", "(", "env", ")", ":", "global", "PDFTeXAction", "if", "PDFTeXAction", "is", "None", ":", "PDFTeXAction", "=", "SCons", ".", "Action", ".", "Action", "(", "'$PDFTEXCOM'", ",", "'$PDFTEXCOMSTR'", ")", "global", "PDFLaTeXAction", "if", "PDFLaTe...
Add Builders and construction variables for pdftex to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "pdftex", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/pdftex.py#L71-L99
23,469
iotile/coretools
iotilecore/iotile/core/hw/virtual/tile_based_device.py
TileBasedVirtualDevice.stop
def stop(self): """Stop running this virtual device including any worker threads.""" for tile in self._tiles.values(): tile.signal_stop() for tile in self._tiles.values(): tile.wait_stopped() super(TileBasedVirtualDevice, self).stop()
python
def stop(self): for tile in self._tiles.values(): tile.signal_stop() for tile in self._tiles.values(): tile.wait_stopped() super(TileBasedVirtualDevice, self).stop()
[ "def", "stop", "(", "self", ")", ":", "for", "tile", "in", "self", ".", "_tiles", ".", "values", "(", ")", ":", "tile", ".", "signal_stop", "(", ")", "for", "tile", "in", "self", ".", "_tiles", ".", "values", "(", ")", ":", "tile", ".", "wait_sto...
Stop running this virtual device including any worker threads.
[ "Stop", "running", "this", "virtual", "device", "including", "any", "worker", "threads", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/virtual/tile_based_device.py#L53-L62
23,470
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SetCacheMode
def SetCacheMode(mode): """Set the Configure cache mode. mode must be one of "auto", "force", or "cache".""" global cache_mode if mode == "auto": cache_mode = AUTO elif mode == "force": cache_mode = FORCE elif mode == "cache": cache_mode = CACHE else: raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode)
python
def SetCacheMode(mode): global cache_mode if mode == "auto": cache_mode = AUTO elif mode == "force": cache_mode = FORCE elif mode == "cache": cache_mode = CACHE else: raise ValueError("SCons.SConf.SetCacheMode: Unknown mode " + mode)
[ "def", "SetCacheMode", "(", "mode", ")", ":", "global", "cache_mode", "if", "mode", "==", "\"auto\"", ":", "cache_mode", "=", "AUTO", "elif", "mode", "==", "\"force\"", ":", "cache_mode", "=", "FORCE", "elif", "mode", "==", "\"cache\"", ":", "cache_mode", ...
Set the Configure cache mode. mode must be one of "auto", "force", or "cache".
[ "Set", "the", "Configure", "cache", "mode", ".", "mode", "must", "be", "one", "of", "auto", "force", "or", "cache", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L79-L90
23,471
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
CreateConfigHBuilder
def CreateConfigHBuilder(env): """Called if necessary just before the building targets phase begins.""" action = SCons.Action.Action(_createConfigH, _stringConfigH) sconfigHBld = SCons.Builder.Builder(action=action) env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} ) for k in list(_ac_config_hs.keys()): env.SConfigHBuilder(k, env.Value(_ac_config_hs[k]))
python
def CreateConfigHBuilder(env): action = SCons.Action.Action(_createConfigH, _stringConfigH) sconfigHBld = SCons.Builder.Builder(action=action) env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} ) for k in list(_ac_config_hs.keys()): env.SConfigHBuilder(k, env.Value(_ac_config_hs[k]))
[ "def", "CreateConfigHBuilder", "(", "env", ")", ":", "action", "=", "SCons", ".", "Action", ".", "Action", "(", "_createConfigH", ",", "_stringConfigH", ")", "sconfigHBld", "=", "SCons", ".", "Builder", ".", "Builder", "(", "action", "=", "action", ")", "e...
Called if necessary just before the building targets phase begins.
[ "Called", "if", "necessary", "just", "before", "the", "building", "targets", "phase", "begins", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L128-L135
23,472
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
CheckHeader
def CheckHeader(context, header, include_quotes = '<>', language = None): """ A test for a C or C++ header file. """ prog_prefix, hdr_to_check = \ createIncludesFromHeaders(header, 1, include_quotes) res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix, language = language, include_quotes = include_quotes) context.did_show_result = 1 return not res
python
def CheckHeader(context, header, include_quotes = '<>', language = None): prog_prefix, hdr_to_check = \ createIncludesFromHeaders(header, 1, include_quotes) res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix, language = language, include_quotes = include_quotes) context.did_show_result = 1 return not res
[ "def", "CheckHeader", "(", "context", ",", "header", ",", "include_quotes", "=", "'<>'", ",", "language", "=", "None", ")", ":", "prog_prefix", ",", "hdr_to_check", "=", "createIncludesFromHeaders", "(", "header", ",", "1", ",", "include_quotes", ")", "res", ...
A test for a C or C++ header file.
[ "A", "test", "for", "a", "C", "or", "C", "++", "header", "file", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L944-L954
23,473
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
CheckLib
def CheckLib(context, library = None, symbol = "main", header = None, language = None, autoadd = 1): """ A test for a library. See also CheckLibWithHeader. Note that library may also be None to test whether the given symbol compiles without flags. """ if library == []: library = [None] if not SCons.Util.is_List(library): library = [library] # ToDo: accept path for the library res = SCons.Conftest.CheckLib(context, library, symbol, header = header, language = language, autoadd = autoadd) context.did_show_result = 1 return not res
python
def CheckLib(context, library = None, symbol = "main", header = None, language = None, autoadd = 1): if library == []: library = [None] if not SCons.Util.is_List(library): library = [library] # ToDo: accept path for the library res = SCons.Conftest.CheckLib(context, library, symbol, header = header, language = language, autoadd = autoadd) context.did_show_result = 1 return not res
[ "def", "CheckLib", "(", "context", ",", "library", "=", "None", ",", "symbol", "=", "\"main\"", ",", "header", "=", "None", ",", "language", "=", "None", ",", "autoadd", "=", "1", ")", ":", "if", "library", "==", "[", "]", ":", "library", "=", "[",...
A test for a library. See also CheckLibWithHeader. Note that library may also be None to test whether the given symbol compiles without flags.
[ "A", "test", "for", "a", "library", ".", "See", "also", "CheckLibWithHeader", ".", "Note", "that", "library", "may", "also", "be", "None", "to", "test", "whether", "the", "given", "symbol", "compiles", "without", "flags", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L994-L1012
23,474
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
CheckProg
def CheckProg(context, prog_name): """Simple check if a program exists in the path. Returns the path for the application, or None if not found. """ res = SCons.Conftest.CheckProg(context, prog_name) context.did_show_result = 1 return res
python
def CheckProg(context, prog_name): res = SCons.Conftest.CheckProg(context, prog_name) context.did_show_result = 1 return res
[ "def", "CheckProg", "(", "context", ",", "prog_name", ")", ":", "res", "=", "SCons", ".", "Conftest", ".", "CheckProg", "(", "context", ",", "prog_name", ")", "context", ".", "did_show_result", "=", "1", "return", "res" ]
Simple check if a program exists in the path. Returns the path for the application, or None if not found.
[ "Simple", "check", "if", "a", "program", "exists", "in", "the", "path", ".", "Returns", "the", "path", "for", "the", "application", "or", "None", "if", "not", "found", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L1040-L1046
23,475
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SConfBuildTask.display_cached_string
def display_cached_string(self, bi): """ Logs the original builder messages, given the SConfBuildInfo instance bi. """ if not isinstance(bi, SConfBuildInfo): SCons.Warnings.warn(SConfWarning, "The stored build information has an unexpected class: %s" % bi.__class__) else: self.display("The original builder output was:\n" + (" |" + str(bi.string)).replace("\n", "\n |"))
python
def display_cached_string(self, bi): if not isinstance(bi, SConfBuildInfo): SCons.Warnings.warn(SConfWarning, "The stored build information has an unexpected class: %s" % bi.__class__) else: self.display("The original builder output was:\n" + (" |" + str(bi.string)).replace("\n", "\n |"))
[ "def", "display_cached_string", "(", "self", ",", "bi", ")", ":", "if", "not", "isinstance", "(", "bi", ",", "SConfBuildInfo", ")", ":", "SCons", ".", "Warnings", ".", "warn", "(", "SConfWarning", ",", "\"The stored build information has an unexpected class: %s\"", ...
Logs the original builder messages, given the SConfBuildInfo instance bi.
[ "Logs", "the", "original", "builder", "messages", "given", "the", "SConfBuildInfo", "instance", "bi", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L231-L241
23,476
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SConfBase.Define
def Define(self, name, value = None, comment = None): """ Define a pre processor symbol name, with the optional given value in the current config header. If value is None (default), then #define name is written. If value is not none, then #define name value is written. comment is a string which will be put as a C comment in the header, to explain the meaning of the value (appropriate C comments will be added automatically). """ lines = [] if comment: comment_str = "/* %s */" % comment lines.append(comment_str) if value is not None: define_str = "#define %s %s" % (name, value) else: define_str = "#define %s" % name lines.append(define_str) lines.append('') self.config_h_text = self.config_h_text + '\n'.join(lines)
python
def Define(self, name, value = None, comment = None): lines = [] if comment: comment_str = "/* %s */" % comment lines.append(comment_str) if value is not None: define_str = "#define %s %s" % (name, value) else: define_str = "#define %s" % name lines.append(define_str) lines.append('') self.config_h_text = self.config_h_text + '\n'.join(lines)
[ "def", "Define", "(", "self", ",", "name", ",", "value", "=", "None", ",", "comment", "=", "None", ")", ":", "lines", "=", "[", "]", "if", "comment", ":", "comment_str", "=", "\"/* %s */\"", "%", "comment", "lines", ".", "append", "(", "comment_str", ...
Define a pre processor symbol name, with the optional given value in the current config header. If value is None (default), then #define name is written. If value is not none, then #define name value is written. comment is a string which will be put as a C comment in the header, to explain the meaning of the value (appropriate C comments will be added automatically).
[ "Define", "a", "pre", "processor", "symbol", "name", "with", "the", "optional", "given", "value", "in", "the", "current", "config", "header", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L453-L476
23,477
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SConfBase.BuildNodes
def BuildNodes(self, nodes): """ Tries to build the given nodes immediately. Returns 1 on success, 0 on error. """ if self.logstream is not None: # override stdout / stderr to write in log file oldStdout = sys.stdout sys.stdout = self.logstream oldStderr = sys.stderr sys.stderr = self.logstream # the engine assumes the current path is the SConstruct directory ... old_fs_dir = SConfFS.getcwd() old_os_dir = os.getcwd() SConfFS.chdir(SConfFS.Top, change_os_dir=1) # Because we take responsibility here for writing out our # own .sconsign info (see SConfBuildTask.execute(), above), # we override the store_info() method with a null place-holder # so we really control how it gets written. for n in nodes: n.store_info = 0 if not hasattr(n, 'attributes'): n.attributes = SCons.Node.Node.Attrs() n.attributes.keep_targetinfo = 1 ret = 1 try: # ToDo: use user options for calc save_max_drift = SConfFS.get_max_drift() SConfFS.set_max_drift(0) tm = SCons.Taskmaster.Taskmaster(nodes, SConfBuildTask) # we don't want to build tests in parallel jobs = SCons.Job.Jobs(1, tm ) jobs.run() for n in nodes: state = n.get_state() if (state != SCons.Node.executed and state != SCons.Node.up_to_date): # the node could not be built. we return 0 in this case ret = 0 finally: SConfFS.set_max_drift(save_max_drift) os.chdir(old_os_dir) SConfFS.chdir(old_fs_dir, change_os_dir=0) if self.logstream is not None: # restore stdout / stderr sys.stdout = oldStdout sys.stderr = oldStderr return ret
python
def BuildNodes(self, nodes): if self.logstream is not None: # override stdout / stderr to write in log file oldStdout = sys.stdout sys.stdout = self.logstream oldStderr = sys.stderr sys.stderr = self.logstream # the engine assumes the current path is the SConstruct directory ... old_fs_dir = SConfFS.getcwd() old_os_dir = os.getcwd() SConfFS.chdir(SConfFS.Top, change_os_dir=1) # Because we take responsibility here for writing out our # own .sconsign info (see SConfBuildTask.execute(), above), # we override the store_info() method with a null place-holder # so we really control how it gets written. for n in nodes: n.store_info = 0 if not hasattr(n, 'attributes'): n.attributes = SCons.Node.Node.Attrs() n.attributes.keep_targetinfo = 1 ret = 1 try: # ToDo: use user options for calc save_max_drift = SConfFS.get_max_drift() SConfFS.set_max_drift(0) tm = SCons.Taskmaster.Taskmaster(nodes, SConfBuildTask) # we don't want to build tests in parallel jobs = SCons.Job.Jobs(1, tm ) jobs.run() for n in nodes: state = n.get_state() if (state != SCons.Node.executed and state != SCons.Node.up_to_date): # the node could not be built. we return 0 in this case ret = 0 finally: SConfFS.set_max_drift(save_max_drift) os.chdir(old_os_dir) SConfFS.chdir(old_fs_dir, change_os_dir=0) if self.logstream is not None: # restore stdout / stderr sys.stdout = oldStdout sys.stderr = oldStderr return ret
[ "def", "BuildNodes", "(", "self", ",", "nodes", ")", ":", "if", "self", ".", "logstream", "is", "not", "None", ":", "# override stdout / stderr to write in log file", "oldStdout", "=", "sys", ".", "stdout", "sys", ".", "stdout", "=", "self", ".", "logstream", ...
Tries to build the given nodes immediately. Returns 1 on success, 0 on error.
[ "Tries", "to", "build", "the", "given", "nodes", "immediately", ".", "Returns", "1", "on", "success", "0", "on", "error", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L478-L529
23,478
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SConfBase.pspawn_wrapper
def pspawn_wrapper(self, sh, escape, cmd, args, env): """Wrapper function for handling piped spawns. This looks to the calling interface (in Action.py) like a "normal" spawn, but associates the call with the PSPAWN variable from the construction environment and with the streams to which we want the output logged. This gets slid into the construction environment as the SPAWN variable so Action.py doesn't have to know or care whether it's spawning a piped command or not. """ return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream)
python
def pspawn_wrapper(self, sh, escape, cmd, args, env): return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream)
[ "def", "pspawn_wrapper", "(", "self", ",", "sh", ",", "escape", ",", "cmd", ",", "args", ",", "env", ")", ":", "return", "self", ".", "pspawn", "(", "sh", ",", "escape", ",", "cmd", ",", "args", ",", "env", ",", "self", ".", "logstream", ",", "se...
Wrapper function for handling piped spawns. This looks to the calling interface (in Action.py) like a "normal" spawn, but associates the call with the PSPAWN variable from the construction environment and with the streams to which we want the output logged. This gets slid into the construction environment as the SPAWN variable so Action.py doesn't have to know or care whether it's spawning a piped command or not.
[ "Wrapper", "function", "for", "handling", "piped", "spawns", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L531-L541
23,479
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SConfBase._startup
def _startup(self): """Private method. Set up logstream, and set the environment variables necessary for a piped build """ global _ac_config_logs global sconf_global global SConfFS self.lastEnvFs = self.env.fs self.env.fs = SConfFS self._createDir(self.confdir) self.confdir.up().add_ignore( [self.confdir] ) if self.logfile is not None and not dryrun: # truncate logfile, if SConf.Configure is called for the first time # in a build if self.logfile in _ac_config_logs: log_mode = "a" else: _ac_config_logs[self.logfile] = None log_mode = "w" fp = open(str(self.logfile), log_mode) self.logstream = SCons.Util.Unbuffered(fp) # logfile may stay in a build directory, so we tell # the build system not to override it with a eventually # existing file with the same name in the source directory self.logfile.dir.add_ignore( [self.logfile] ) tb = traceback.extract_stack()[-3-self.depth] old_fs_dir = SConfFS.getcwd() SConfFS.chdir(SConfFS.Top, change_os_dir=0) self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' % (tb[0], tb[1], str(self.confdir)) ) SConfFS.chdir(old_fs_dir) else: self.logstream = None # we use a special builder to create source files from TEXT action = SCons.Action.Action(_createSource, _stringSource) sconfSrcBld = SCons.Builder.Builder(action=action) self.env.Append( BUILDERS={'SConfSourceBuilder':sconfSrcBld} ) self.config_h_text = _ac_config_hs.get(self.config_h, "") self.active = 1 # only one SConf instance should be active at a time ... sconf_global = self
python
def _startup(self): global _ac_config_logs global sconf_global global SConfFS self.lastEnvFs = self.env.fs self.env.fs = SConfFS self._createDir(self.confdir) self.confdir.up().add_ignore( [self.confdir] ) if self.logfile is not None and not dryrun: # truncate logfile, if SConf.Configure is called for the first time # in a build if self.logfile in _ac_config_logs: log_mode = "a" else: _ac_config_logs[self.logfile] = None log_mode = "w" fp = open(str(self.logfile), log_mode) self.logstream = SCons.Util.Unbuffered(fp) # logfile may stay in a build directory, so we tell # the build system not to override it with a eventually # existing file with the same name in the source directory self.logfile.dir.add_ignore( [self.logfile] ) tb = traceback.extract_stack()[-3-self.depth] old_fs_dir = SConfFS.getcwd() SConfFS.chdir(SConfFS.Top, change_os_dir=0) self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' % (tb[0], tb[1], str(self.confdir)) ) SConfFS.chdir(old_fs_dir) else: self.logstream = None # we use a special builder to create source files from TEXT action = SCons.Action.Action(_createSource, _stringSource) sconfSrcBld = SCons.Builder.Builder(action=action) self.env.Append( BUILDERS={'SConfSourceBuilder':sconfSrcBld} ) self.config_h_text = _ac_config_hs.get(self.config_h, "") self.active = 1 # only one SConf instance should be active at a time ... sconf_global = self
[ "def", "_startup", "(", "self", ")", ":", "global", "_ac_config_logs", "global", "sconf_global", "global", "SConfFS", "self", ".", "lastEnvFs", "=", "self", ".", "env", ".", "fs", "self", ".", "env", ".", "fs", "=", "SConfFS", "self", ".", "_createDir", ...
Private method. Set up logstream, and set the environment variables necessary for a piped build
[ "Private", "method", ".", "Set", "up", "logstream", "and", "set", "the", "environment", "variables", "necessary", "for", "a", "piped", "build" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L685-L729
23,480
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
SConfBase._shutdown
def _shutdown(self): """Private method. Reset to non-piped spawn""" global sconf_global, _ac_config_hs if not self.active: raise SCons.Errors.UserError("Finish may be called only once!") if self.logstream is not None and not dryrun: self.logstream.write("\n") self.logstream.close() self.logstream = None # remove the SConfSourceBuilder from the environment blds = self.env['BUILDERS'] del blds['SConfSourceBuilder'] self.env.Replace( BUILDERS=blds ) self.active = 0 sconf_global = None if not self.config_h is None: _ac_config_hs[self.config_h] = self.config_h_text self.env.fs = self.lastEnvFs
python
def _shutdown(self): global sconf_global, _ac_config_hs if not self.active: raise SCons.Errors.UserError("Finish may be called only once!") if self.logstream is not None and not dryrun: self.logstream.write("\n") self.logstream.close() self.logstream = None # remove the SConfSourceBuilder from the environment blds = self.env['BUILDERS'] del blds['SConfSourceBuilder'] self.env.Replace( BUILDERS=blds ) self.active = 0 sconf_global = None if not self.config_h is None: _ac_config_hs[self.config_h] = self.config_h_text self.env.fs = self.lastEnvFs
[ "def", "_shutdown", "(", "self", ")", ":", "global", "sconf_global", ",", "_ac_config_hs", "if", "not", "self", ".", "active", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "\"Finish may be called only once!\"", ")", "if", "self", ".", "logstrea...
Private method. Reset to non-piped spawn
[ "Private", "method", ".", "Reset", "to", "non", "-", "piped", "spawn" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L731-L749
23,481
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py
CheckContext.Result
def Result(self, res): """Inform about the result of the test. If res is not a string, displays 'yes' or 'no' depending on whether res is evaluated as true or false. The result is only displayed when self.did_show_result is not set. """ if isinstance(res, str): text = res elif res: text = "yes" else: text = "no" if self.did_show_result == 0: # Didn't show result yet, do it now. self.Display(text + "\n") self.did_show_result = 1
python
def Result(self, res): if isinstance(res, str): text = res elif res: text = "yes" else: text = "no" if self.did_show_result == 0: # Didn't show result yet, do it now. self.Display(text + "\n") self.did_show_result = 1
[ "def", "Result", "(", "self", ",", "res", ")", ":", "if", "isinstance", "(", "res", ",", "str", ")", ":", "text", "=", "res", "elif", "res", ":", "text", "=", "\"yes\"", "else", ":", "text", "=", "\"no\"", "if", "self", ".", "did_show_result", "=="...
Inform about the result of the test. If res is not a string, displays 'yes' or 'no' depending on whether res is evaluated as true or false. The result is only displayed when self.did_show_result is not set.
[ "Inform", "about", "the", "result", "of", "the", "test", ".", "If", "res", "is", "not", "a", "string", "displays", "yes", "or", "no", "depending", "on", "whether", "res", "is", "evaluated", "as", "true", "or", "false", ".", "The", "result", "is", "only...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/SConf.py#L795-L810
23,482
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/intelc.py
linux_ver_normalize
def linux_ver_normalize(vstr): """Normalize a Linux compiler version number. Intel changed from "80" to "9.0" in 2005, so we assume if the number is greater than 60 it's an old-style number and otherwise new-style. Always returns an old-style float like 80 or 90 for compatibility with Windows. Shades of Y2K!""" # Check for version number like 9.1.026: return 91.026 # XXX needs to be updated for 2011+ versions (like 2011.11.344 which is compiler v12.1.5) m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', vstr) if m: vmaj,vmin,build = m.groups() return float(vmaj) * 10. + float(vmin) + float(build) / 1000.; else: f = float(vstr) if is_windows: return f else: if f < 60: return f * 10.0 else: return f
python
def linux_ver_normalize(vstr): # Check for version number like 9.1.026: return 91.026 # XXX needs to be updated for 2011+ versions (like 2011.11.344 which is compiler v12.1.5) m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', vstr) if m: vmaj,vmin,build = m.groups() return float(vmaj) * 10. + float(vmin) + float(build) / 1000.; else: f = float(vstr) if is_windows: return f else: if f < 60: return f * 10.0 else: return f
[ "def", "linux_ver_normalize", "(", "vstr", ")", ":", "# Check for version number like 9.1.026: return 91.026", "# XXX needs to be updated for 2011+ versions (like 2011.11.344 which is compiler v12.1.5)", "m", "=", "re", ".", "match", "(", "r'([0-9]+)\\.([0-9]+)\\.([0-9]+)'", ",", "vs...
Normalize a Linux compiler version number. Intel changed from "80" to "9.0" in 2005, so we assume if the number is greater than 60 it's an old-style number and otherwise new-style. Always returns an old-style float like 80 or 90 for compatibility with Windows. Shades of Y2K!
[ "Normalize", "a", "Linux", "compiler", "version", "number", ".", "Intel", "changed", "from", "80", "to", "9", ".", "0", "in", "2005", "so", "we", "assume", "if", "the", "number", "is", "greater", "than", "60", "it", "s", "an", "old", "-", "style", "n...
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/intelc.py#L64-L82
23,483
iotile/coretools
iotilesensorgraph/iotile/sg/node_descriptor.py
parse_node_descriptor
def parse_node_descriptor(desc, model): """Parse a string node descriptor. The function creates an SGNode object without connecting its inputs and outputs and returns a 3-tuple: SGNode, [(input X, trigger X)], <processing function name> Args: desc (str): A description of the node to be created. model (str): A device model for the node to be created that sets any device specific limits on how the node is set up. """ try: data = graph_node.parseString(desc) except ParseException: raise # TODO: Fix this to properly encapsulate the parse error stream_desc = u' '.join(data['node']) stream = DataStream.FromString(stream_desc) node = SGNode(stream, model) inputs = [] if 'input_a' in data: input_a = data['input_a'] stream_a = DataStreamSelector.FromString(u' '.join(input_a['input_stream'])) trigger_a = None if 'type' in input_a: trigger_a = InputTrigger(input_a['type'], input_a['op'], int(input_a['reference'], 0)) inputs.append((stream_a, trigger_a)) if 'input_b' in data: input_a = data['input_b'] stream_a = DataStreamSelector.FromString(u' '.join(input_a['input_stream'])) trigger_a = None if 'type' in input_a: trigger_a = InputTrigger(input_a['type'], input_a['op'], int(input_a['reference'], 0)) inputs.append((stream_a, trigger_a)) if 'combiner' in data and str(data['combiner']) == u'||': node.trigger_combiner = SGNode.OrTriggerCombiner else: node.trigger_combiner = SGNode.AndTriggerCombiner processing = data['processor'] return node, inputs, processing
python
def parse_node_descriptor(desc, model): try: data = graph_node.parseString(desc) except ParseException: raise # TODO: Fix this to properly encapsulate the parse error stream_desc = u' '.join(data['node']) stream = DataStream.FromString(stream_desc) node = SGNode(stream, model) inputs = [] if 'input_a' in data: input_a = data['input_a'] stream_a = DataStreamSelector.FromString(u' '.join(input_a['input_stream'])) trigger_a = None if 'type' in input_a: trigger_a = InputTrigger(input_a['type'], input_a['op'], int(input_a['reference'], 0)) inputs.append((stream_a, trigger_a)) if 'input_b' in data: input_a = data['input_b'] stream_a = DataStreamSelector.FromString(u' '.join(input_a['input_stream'])) trigger_a = None if 'type' in input_a: trigger_a = InputTrigger(input_a['type'], input_a['op'], int(input_a['reference'], 0)) inputs.append((stream_a, trigger_a)) if 'combiner' in data and str(data['combiner']) == u'||': node.trigger_combiner = SGNode.OrTriggerCombiner else: node.trigger_combiner = SGNode.AndTriggerCombiner processing = data['processor'] return node, inputs, processing
[ "def", "parse_node_descriptor", "(", "desc", ",", "model", ")", ":", "try", ":", "data", "=", "graph_node", ".", "parseString", "(", "desc", ")", "except", "ParseException", ":", "raise", "# TODO: Fix this to properly encapsulate the parse error", "stream_desc", "=", ...
Parse a string node descriptor. The function creates an SGNode object without connecting its inputs and outputs and returns a 3-tuple: SGNode, [(input X, trigger X)], <processing function name> Args: desc (str): A description of the node to be created. model (str): A device model for the node to be created that sets any device specific limits on how the node is set up.
[ "Parse", "a", "string", "node", "descriptor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node_descriptor.py#L32-L84
23,484
iotile/coretools
iotilesensorgraph/iotile/sg/node_descriptor.py
create_binary_descriptor
def create_binary_descriptor(descriptor): """Convert a string node descriptor into a 20-byte binary descriptor. This is the inverse operation of parse_binary_descriptor and composing the two operations is a noop. Args: descriptor (str): A string node descriptor Returns: bytes: A 20-byte binary node descriptor. """ func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'} func_codes = {y: x for x, y in func_names.items()} node, inputs, processing = parse_node_descriptor(descriptor, DeviceModel()) func_code = func_codes.get(processing) if func_code is None: raise ArgumentError("Unknown processing function", function=processing) stream_a, trigger_a = inputs[0] stream_a = stream_a.encode() if len(inputs) == 2: stream_b, trigger_b = inputs[1] stream_b = stream_b.encode() else: stream_b, trigger_b = 0xFFFF, None if trigger_a is None: trigger_a = TrueTrigger() if trigger_b is None: trigger_b = TrueTrigger() ref_a = 0 if isinstance(trigger_a, InputTrigger): ref_a = trigger_a.reference ref_b = 0 if isinstance(trigger_b, InputTrigger): ref_b = trigger_b.reference trigger_a = _create_binary_trigger(trigger_a) trigger_b = _create_binary_trigger(trigger_b) combiner = node.trigger_combiner bin_desc = struct.pack("<LLHHHBBBB2x", ref_a, ref_b, node.stream.encode(), stream_a, stream_b, func_code, trigger_a, trigger_b, combiner) return bin_desc
python
def create_binary_descriptor(descriptor): func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'} func_codes = {y: x for x, y in func_names.items()} node, inputs, processing = parse_node_descriptor(descriptor, DeviceModel()) func_code = func_codes.get(processing) if func_code is None: raise ArgumentError("Unknown processing function", function=processing) stream_a, trigger_a = inputs[0] stream_a = stream_a.encode() if len(inputs) == 2: stream_b, trigger_b = inputs[1] stream_b = stream_b.encode() else: stream_b, trigger_b = 0xFFFF, None if trigger_a is None: trigger_a = TrueTrigger() if trigger_b is None: trigger_b = TrueTrigger() ref_a = 0 if isinstance(trigger_a, InputTrigger): ref_a = trigger_a.reference ref_b = 0 if isinstance(trigger_b, InputTrigger): ref_b = trigger_b.reference trigger_a = _create_binary_trigger(trigger_a) trigger_b = _create_binary_trigger(trigger_b) combiner = node.trigger_combiner bin_desc = struct.pack("<LLHHHBBBB2x", ref_a, ref_b, node.stream.encode(), stream_a, stream_b, func_code, trigger_a, trigger_b, combiner) return bin_desc
[ "def", "create_binary_descriptor", "(", "descriptor", ")", ":", "func_names", "=", "{", "0", ":", "'copy_latest_a'", ",", "1", ":", "'average_a'", ",", "2", ":", "'copy_all_a'", ",", "3", ":", "'sum_a'", ",", "4", ":", "'copy_count_a'", ",", "5", ":", "'...
Convert a string node descriptor into a 20-byte binary descriptor. This is the inverse operation of parse_binary_descriptor and composing the two operations is a noop. Args: descriptor (str): A string node descriptor Returns: bytes: A 20-byte binary node descriptor.
[ "Convert", "a", "string", "node", "descriptor", "into", "a", "20", "-", "byte", "binary", "descriptor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node_descriptor.py#L87-L142
23,485
iotile/coretools
iotilesensorgraph/iotile/sg/node_descriptor.py
parse_binary_descriptor
def parse_binary_descriptor(bindata): """Convert a binary node descriptor into a string descriptor. Binary node descriptor are 20-byte binary structures that encode all information needed to create a graph node. They are used to communicate that information to an embedded device in an efficent format. This function exists to turn such a compressed node description back into an understandable string. Args: bindata (bytes): The raw binary structure that contains the node description. Returns: str: The corresponding string description of the same sensor_graph node """ func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'} if len(bindata) != 20: raise ArgumentError("Invalid binary node descriptor with incorrect size", size=len(bindata), expected=20, bindata=bindata) a_trig, b_trig, stream_id, a_id, b_id, proc, a_cond, b_cond, trig_combiner = struct.unpack("<LLHHHBBBB2x", bindata) node_stream = DataStream.FromEncoded(stream_id) if a_id == 0xFFFF: raise ArgumentError("Invalid binary node descriptor with invalid first input", input_selector=a_id) a_selector = DataStreamSelector.FromEncoded(a_id) a_trigger = _process_binary_trigger(a_trig, a_cond) b_selector = None b_trigger = None if b_id != 0xFFFF: b_selector = DataStreamSelector.FromEncoded(b_id) b_trigger = _process_binary_trigger(b_trig, b_cond) if trig_combiner == SGNode.AndTriggerCombiner: comb = '&&' elif trig_combiner == SGNode.OrTriggerCombiner: comb = '||' else: raise ArgumentError("Invalid trigger combiner in binary node descriptor", combiner=trig_combiner) if proc not in func_names: raise ArgumentError("Unknown processing function", function_id=proc, known_functions=func_names) func_name = func_names[proc] # Handle one input nodes if b_selector is None: return '({} {}) => {} using {}'.format(a_selector, a_trigger, node_stream, func_name) return '({} {} {} {} {}) => {} using {}'.format(a_selector, a_trigger, comb, b_selector, b_trigger, node_stream, func_name)
python
def parse_binary_descriptor(bindata): func_names = {0: 'copy_latest_a', 1: 'average_a', 2: 'copy_all_a', 3: 'sum_a', 4: 'copy_count_a', 5: 'trigger_streamer', 6: 'call_rpc', 7: 'subtract_afromb'} if len(bindata) != 20: raise ArgumentError("Invalid binary node descriptor with incorrect size", size=len(bindata), expected=20, bindata=bindata) a_trig, b_trig, stream_id, a_id, b_id, proc, a_cond, b_cond, trig_combiner = struct.unpack("<LLHHHBBBB2x", bindata) node_stream = DataStream.FromEncoded(stream_id) if a_id == 0xFFFF: raise ArgumentError("Invalid binary node descriptor with invalid first input", input_selector=a_id) a_selector = DataStreamSelector.FromEncoded(a_id) a_trigger = _process_binary_trigger(a_trig, a_cond) b_selector = None b_trigger = None if b_id != 0xFFFF: b_selector = DataStreamSelector.FromEncoded(b_id) b_trigger = _process_binary_trigger(b_trig, b_cond) if trig_combiner == SGNode.AndTriggerCombiner: comb = '&&' elif trig_combiner == SGNode.OrTriggerCombiner: comb = '||' else: raise ArgumentError("Invalid trigger combiner in binary node descriptor", combiner=trig_combiner) if proc not in func_names: raise ArgumentError("Unknown processing function", function_id=proc, known_functions=func_names) func_name = func_names[proc] # Handle one input nodes if b_selector is None: return '({} {}) => {} using {}'.format(a_selector, a_trigger, node_stream, func_name) return '({} {} {} {} {}) => {} using {}'.format(a_selector, a_trigger, comb, b_selector, b_trigger, node_stream, func_name)
[ "def", "parse_binary_descriptor", "(", "bindata", ")", ":", "func_names", "=", "{", "0", ":", "'copy_latest_a'", ",", "1", ":", "'average_a'", ",", "2", ":", "'copy_all_a'", ",", "3", ":", "'sum_a'", ",", "4", ":", "'copy_count_a'", ",", "5", ":", "'trig...
Convert a binary node descriptor into a string descriptor. Binary node descriptor are 20-byte binary structures that encode all information needed to create a graph node. They are used to communicate that information to an embedded device in an efficent format. This function exists to turn such a compressed node description back into an understandable string. Args: bindata (bytes): The raw binary structure that contains the node description. Returns: str: The corresponding string description of the same sensor_graph node
[ "Convert", "a", "binary", "node", "descriptor", "into", "a", "string", "descriptor", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node_descriptor.py#L145-L204
23,486
iotile/coretools
iotilesensorgraph/iotile/sg/node_descriptor.py
_process_binary_trigger
def _process_binary_trigger(trigger_value, condition): """Create an InputTrigger object.""" ops = { 0: ">", 1: "<", 2: ">=", 3: "<=", 4: "==", 5: 'always' } sources = { 0: 'value', 1: 'count' } encoded_source = condition & 0b1 encoded_op = condition >> 1 oper = ops.get(encoded_op, None) source = sources.get(encoded_source, None) if oper is None: raise ArgumentError("Unknown operation in binary trigger", condition=condition, operation=encoded_op, known_ops=ops) if source is None: raise ArgumentError("Unknown value source in binary trigger", source=source, known_sources=sources) if oper == 'always': return TrueTrigger() return InputTrigger(source, oper, trigger_value)
python
def _process_binary_trigger(trigger_value, condition): ops = { 0: ">", 1: "<", 2: ">=", 3: "<=", 4: "==", 5: 'always' } sources = { 0: 'value', 1: 'count' } encoded_source = condition & 0b1 encoded_op = condition >> 1 oper = ops.get(encoded_op, None) source = sources.get(encoded_source, None) if oper is None: raise ArgumentError("Unknown operation in binary trigger", condition=condition, operation=encoded_op, known_ops=ops) if source is None: raise ArgumentError("Unknown value source in binary trigger", source=source, known_sources=sources) if oper == 'always': return TrueTrigger() return InputTrigger(source, oper, trigger_value)
[ "def", "_process_binary_trigger", "(", "trigger_value", ",", "condition", ")", ":", "ops", "=", "{", "0", ":", "\">\"", ",", "1", ":", "\"<\"", ",", "2", ":", "\">=\"", ",", "3", ":", "\"<=\"", ",", "4", ":", "\"==\"", ",", "5", ":", "'always'", "}...
Create an InputTrigger object.
[ "Create", "an", "InputTrigger", "object", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node_descriptor.py#L207-L238
23,487
iotile/coretools
iotilesensorgraph/iotile/sg/node_descriptor.py
_create_binary_trigger
def _create_binary_trigger(trigger): """Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger.""" ops = { 0: ">", 1: "<", 2: ">=", 3: "<=", 4: "==", 5: 'always' } op_codes = {y: x for x, y in ops.items()} source = 0 if isinstance(trigger, TrueTrigger): op_code = op_codes['always'] elif isinstance(trigger, FalseTrigger): raise ArgumentError("Cannot express a never trigger in binary descriptor", trigger=trigger) else: op_code = op_codes[trigger.comp_string] if trigger.use_count: source = 1 return (op_code << 1) | source
python
def _create_binary_trigger(trigger): ops = { 0: ">", 1: "<", 2: ">=", 3: "<=", 4: "==", 5: 'always' } op_codes = {y: x for x, y in ops.items()} source = 0 if isinstance(trigger, TrueTrigger): op_code = op_codes['always'] elif isinstance(trigger, FalseTrigger): raise ArgumentError("Cannot express a never trigger in binary descriptor", trigger=trigger) else: op_code = op_codes[trigger.comp_string] if trigger.use_count: source = 1 return (op_code << 1) | source
[ "def", "_create_binary_trigger", "(", "trigger", ")", ":", "ops", "=", "{", "0", ":", "\">\"", ",", "1", ":", "\"<\"", ",", "2", ":", "\">=\"", ",", "3", ":", "\"<=\"", ",", "4", ":", "\"==\"", ",", "5", ":", "'always'", "}", "op_codes", "=", "{"...
Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger.
[ "Create", "an", "8", "-", "bit", "binary", "trigger", "from", "an", "InputTrigger", "TrueTrigger", "FalseTrigger", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/node_descriptor.py#L241-L266
23,488
iotile/coretools
iotilecore/iotile/core/hw/reports/report.py
IOTileReading._try_assign_utc_time
def _try_assign_utc_time(self, raw_time, time_base): """Try to assign a UTC time to this reading.""" # Check if the raw time is encoded UTC since y2k or just uptime if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)): y2k_offset = self.raw_time ^ (1 << 31) return self._Y2KReference + datetime.timedelta(seconds=y2k_offset) if time_base is not None: return time_base + datetime.timedelta(seconds=raw_time) return None
python
def _try_assign_utc_time(self, raw_time, time_base): # Check if the raw time is encoded UTC since y2k or just uptime if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)): y2k_offset = self.raw_time ^ (1 << 31) return self._Y2KReference + datetime.timedelta(seconds=y2k_offset) if time_base is not None: return time_base + datetime.timedelta(seconds=raw_time) return None
[ "def", "_try_assign_utc_time", "(", "self", ",", "raw_time", ",", "time_base", ")", ":", "# Check if the raw time is encoded UTC since y2k or just uptime", "if", "raw_time", "!=", "IOTileEvent", ".", "InvalidRawTime", "and", "(", "raw_time", "&", "(", "1", "<<", "31",...
Try to assign a UTC time to this reading.
[ "Try", "to", "assign", "a", "UTC", "time", "to", "this", "reading", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/report.py#L52-L63
23,489
iotile/coretools
iotilecore/iotile/core/hw/reports/report.py
IOTileReading.asdict
def asdict(self): """Encode the data in this reading into a dictionary. Returns: dict: A dictionary containing the information from this reading. """ timestamp_str = None if self.reading_time is not None: timestamp_str = self.reading_time.isoformat() return { 'stream': self.stream, 'device_timestamp': self.raw_time, 'streamer_local_id': self.reading_id, 'timestamp': timestamp_str, 'value': self.value }
python
def asdict(self): timestamp_str = None if self.reading_time is not None: timestamp_str = self.reading_time.isoformat() return { 'stream': self.stream, 'device_timestamp': self.raw_time, 'streamer_local_id': self.reading_id, 'timestamp': timestamp_str, 'value': self.value }
[ "def", "asdict", "(", "self", ")", ":", "timestamp_str", "=", "None", "if", "self", ".", "reading_time", "is", "not", "None", ":", "timestamp_str", "=", "self", ".", "reading_time", ".", "isoformat", "(", ")", "return", "{", "'stream'", ":", "self", ".",...
Encode the data in this reading into a dictionary. Returns: dict: A dictionary containing the information from this reading.
[ "Encode", "the", "data", "in", "this", "reading", "into", "a", "dictionary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/report.py#L65-L82
23,490
iotile/coretools
iotilecore/iotile/core/hw/reports/report.py
IOTileEvent.asdict
def asdict(self): """Encode the data in this event into a dictionary. The dictionary returned from this method is a reference to the data stored in the IOTileEvent, not a copy. It should be treated as read only. Returns: dict: A dictionary containing the information from this event. """ return { 'stream': self.stream, 'device_timestamp': self.raw_time, 'streamer_local_id': self.reading_id, 'timestamp': self.reading_time, 'extra_data': self.summary_data, 'data': self.raw_data }
python
def asdict(self): return { 'stream': self.stream, 'device_timestamp': self.raw_time, 'streamer_local_id': self.reading_id, 'timestamp': self.reading_time, 'extra_data': self.summary_data, 'data': self.raw_data }
[ "def", "asdict", "(", "self", ")", ":", "return", "{", "'stream'", ":", "self", ".", "stream", ",", "'device_timestamp'", ":", "self", ".", "raw_time", ",", "'streamer_local_id'", ":", "self", ".", "reading_id", ",", "'timestamp'", ":", "self", ".", "readi...
Encode the data in this event into a dictionary. The dictionary returned from this method is a reference to the data stored in the IOTileEvent, not a copy. It should be treated as read only. Returns: dict: A dictionary containing the information from this event.
[ "Encode", "the", "data", "in", "this", "event", "into", "a", "dictionary", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/report.py#L163-L181
23,491
iotile/coretools
iotilecore/iotile/core/hw/reports/report.py
IOTileReport.save
def save(self, path): """Save a binary copy of this report Args: path (string): The path where we should save the binary copy of the report """ data = self.encode() with open(path, "wb") as out: out.write(data)
python
def save(self, path): data = self.encode() with open(path, "wb") as out: out.write(data)
[ "def", "save", "(", "self", ",", "path", ")", ":", "data", "=", "self", ".", "encode", "(", ")", "with", "open", "(", "path", ",", "\"wb\"", ")", "as", "out", ":", "out", ".", "write", "(", "data", ")" ]
Save a binary copy of this report Args: path (string): The path where we should save the binary copy of the report
[ "Save", "a", "binary", "copy", "of", "this", "report" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/report.py#L294-L304
23,492
iotile/coretools
iotilecore/iotile/core/hw/reports/report.py
IOTileReport.serialize
def serialize(self): """Turn this report into a dictionary that encodes all information including received timestamp""" info = {} info['received_time'] = self.received_time info['encoded_report'] = bytes(self.encode()) # Handle python 2 / python 3 differences report_format = info['encoded_report'][0] if not isinstance(report_format, int): report_format = ord(report_format) info['report_format'] = report_format # Report format is the first byte of the encoded report info['origin'] = self.origin return info
python
def serialize(self): info = {} info['received_time'] = self.received_time info['encoded_report'] = bytes(self.encode()) # Handle python 2 / python 3 differences report_format = info['encoded_report'][0] if not isinstance(report_format, int): report_format = ord(report_format) info['report_format'] = report_format # Report format is the first byte of the encoded report info['origin'] = self.origin return info
[ "def", "serialize", "(", "self", ")", ":", "info", "=", "{", "}", "info", "[", "'received_time'", "]", "=", "self", ".", "received_time", "info", "[", "'encoded_report'", "]", "=", "bytes", "(", "self", ".", "encode", "(", ")", ")", "# Handle python 2 / ...
Turn this report into a dictionary that encodes all information including received timestamp
[ "Turn", "this", "report", "into", "a", "dictionary", "that", "encodes", "all", "information", "including", "received", "timestamp" ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/report.py#L306-L320
23,493
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Alias.py
Alias.get_contents
def get_contents(self): """The contents of an alias is the concatenation of the content signatures of all its sources.""" childsigs = [n.get_csig() for n in self.children()] return ''.join(childsigs)
python
def get_contents(self): childsigs = [n.get_csig() for n in self.children()] return ''.join(childsigs)
[ "def", "get_contents", "(", "self", ")", ":", "childsigs", "=", "[", "n", ".", "get_csig", "(", ")", "for", "n", "in", "self", ".", "children", "(", ")", "]", "return", "''", ".", "join", "(", "childsigs", ")" ]
The contents of an alias is the concatenation of the content signatures of all its sources.
[ "The", "contents", "of", "an", "alias", "is", "the", "concatenation", "of", "the", "content", "signatures", "of", "all", "its", "sources", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/Alias.py#L130-L134
23,494
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cxx.py
generate
def generate(env): """ Add Builders and construction variables for Visual Age C++ compilers to an Environment. """ import SCons.Tool import SCons.Tool.cc static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CXXSuffixes: static_obj.add_action(suffix, SCons.Defaults.CXXAction) shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) SCons.Tool.cc.add_common_cc_variables(env) if 'CXX' not in env: env['CXX'] = env.Detect(compilers) or compilers[0] env['CXXFLAGS'] = SCons.Util.CLVar('') env['CXXCOM'] = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES' env['SHCXX'] = '$CXX' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHCXXCOM'] = '$SHCXX -o $TARGET -c $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.os' env['OBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CXXFILESUFFIX'] = '.cc'
python
def generate(env): import SCons.Tool import SCons.Tool.cc static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CXXSuffixes: static_obj.add_action(suffix, SCons.Defaults.CXXAction) shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) SCons.Tool.cc.add_common_cc_variables(env) if 'CXX' not in env: env['CXX'] = env.Detect(compilers) or compilers[0] env['CXXFLAGS'] = SCons.Util.CLVar('') env['CXXCOM'] = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES' env['SHCXX'] = '$CXX' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHCXXCOM'] = '$SHCXX -o $TARGET -c $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.os' env['OBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CXXFILESUFFIX'] = '.cc'
[ "def", "generate", "(", "env", ")", ":", "import", "SCons", ".", "Tool", "import", "SCons", ".", "Tool", ".", "cc", "static_obj", ",", "shared_obj", "=", "SCons", ".", "Tool", ".", "createObjBuilders", "(", "env", ")", "for", "suffix", "in", "CXXSuffixes...
Add Builders and construction variables for Visual Age C++ compilers to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "Visual", "Age", "C", "++", "compilers", "to", "an", "Environment", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/cxx.py#L58-L91
23,495
iotile/coretools
iotilesensorgraph/iotile/sg/streamer.py
DataStreamer.link_to_storage
def link_to_storage(self, sensor_log): """Attach this DataStreamer to an underlying SensorLog. Calling this method is required if you want to use this DataStreamer to generate reports from the underlying data in the SensorLog. You can call it multiple times and it will unlink itself from any previous SensorLog each time. Args: sensor_log (SensorLog): Actually create a StreamWalker to go along with this streamer so that we can check if it's triggered. """ if self.walker is not None: self._sensor_log.destroy_walker(self.walker) self.walker = None self.walker = sensor_log.create_walker(self.selector) self._sensor_log = sensor_log
python
def link_to_storage(self, sensor_log): if self.walker is not None: self._sensor_log.destroy_walker(self.walker) self.walker = None self.walker = sensor_log.create_walker(self.selector) self._sensor_log = sensor_log
[ "def", "link_to_storage", "(", "self", ",", "sensor_log", ")", ":", "if", "self", ".", "walker", "is", "not", "None", ":", "self", ".", "_sensor_log", ".", "destroy_walker", "(", "self", ".", "walker", ")", "self", ".", "walker", "=", "None", "self", "...
Attach this DataStreamer to an underlying SensorLog. Calling this method is required if you want to use this DataStreamer to generate reports from the underlying data in the SensorLog. You can call it multiple times and it will unlink itself from any previous SensorLog each time. Args: sensor_log (SensorLog): Actually create a StreamWalker to go along with this streamer so that we can check if it's triggered.
[ "Attach", "this", "DataStreamer", "to", "an", "underlying", "SensorLog", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer.py#L63-L82
23,496
iotile/coretools
iotilesensorgraph/iotile/sg/streamer.py
DataStreamer.triggered
def triggered(self, manual=False): """Check if this streamer should generate a report. Streamers can be triggered automatically whenever they have data or they can be triggered manually. This method returns True if the streamer is currented triggered. A streamer is triggered if it: - (has data AND is automatic) OR - (has data AND is manually triggered) Args: manual (bool): Indicate that the streamer has been manually triggered. Returns: bool: Whether the streamer can generate a report right now. """ if self.walker is None: raise InternalError("You can only check if a streamer is triggered if you create it with a SensorLog") if not self.automatic and not manual: return False return self.has_data()
python
def triggered(self, manual=False): if self.walker is None: raise InternalError("You can only check if a streamer is triggered if you create it with a SensorLog") if not self.automatic and not manual: return False return self.has_data()
[ "def", "triggered", "(", "self", ",", "manual", "=", "False", ")", ":", "if", "self", ".", "walker", "is", "None", ":", "raise", "InternalError", "(", "\"You can only check if a streamer is triggered if you create it with a SensorLog\"", ")", "if", "not", "self", "....
Check if this streamer should generate a report. Streamers can be triggered automatically whenever they have data or they can be triggered manually. This method returns True if the streamer is currented triggered. A streamer is triggered if it: - (has data AND is automatic) OR - (has data AND is manually triggered) Args: manual (bool): Indicate that the streamer has been manually triggered. Returns: bool: Whether the streamer can generate a report right now.
[ "Check", "if", "this", "streamer", "should", "generate", "a", "report", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer.py#L96-L120
23,497
iotile/coretools
iotilesensorgraph/iotile/sg/streamer.py
DataStreamer.build_report
def build_report(self, device_id, max_size=None, device_uptime=0, report_id=None, auth_chain=None): """Build a report with all of the readings in this streamer. This method will produce an IOTileReport subclass and, if necessary, sign it using the passed authentication chain. Args: device_id (int): The UUID of the device to generate a report for. max_size (int): Optional maximum number of bytes that the report can be device_uptime (int): The device's uptime to use as the sent timestamp of the report report_id (int): The report id to use if the report type require serialization. auth_chain (AuthChain): An auth chain class to use to sign the report if the report type requires signing. Returns: StreamerReport: The report, its highest id and the number of readings in it. The highest reading id and number of readings are returned separately from the report itself because, depending on the format of the report (such as whether it is encrypted or does not contain reading ids), these details may not be recoverable from the report itself. Raises: InternalError: If there was no SensorLog passed when this streamer was created. StreamEmptyError: If there is no data to generate a report from. This can only happen if a call to triggered() returned False. ArgumentError: If the report requires additional metadata that was not passed like a signing key or report_id. """ if self.walker is None or self.index is None: raise InternalError("You can only build a report with a DataStreamer if you create it with a SensorLog and a streamer index") if self.requires_signing() and auth_chain is None: raise ArgumentError("You must pass an auth chain to sign this report.") if self.requires_id() and report_id is None: raise ArgumentError("You must pass a report_id to serialize this report") if self.format == 'individual': reading = self.walker.pop() highest_id = reading.reading_id if self.report_type == 'telegram': return StreamerReport(IndividualReadingReport.FromReadings(device_id, [reading]), 1, highest_id) elif self.report_type == 'broadcast': return StreamerReport(BroadcastReport.FromReadings(device_id, [reading], device_uptime), 1, highest_id) elif self.format == 'hashedlist': max_readings = (max_size - 20 - 24) // 16 if max_readings <= 0: raise InternalError("max_size is too small to hold even a single reading", max_size=max_size) readings = [] highest_id = 0 try: while len(readings) < max_readings: reading = self.walker.pop() readings.append(reading) if reading.reading_id > highest_id: highest_id = reading.reading_id except StreamEmptyError: if len(readings) == 0: raise return StreamerReport(SignedListReport.FromReadings(device_id, readings, report_id=report_id, selector=self.selector.encode(), streamer=self.index, sent_timestamp=device_uptime), len(readings), highest_id) raise InternalError("Streamer report format or type is not supported currently", report_format=self.format, report_type=self.report_type)
python
def build_report(self, device_id, max_size=None, device_uptime=0, report_id=None, auth_chain=None): if self.walker is None or self.index is None: raise InternalError("You can only build a report with a DataStreamer if you create it with a SensorLog and a streamer index") if self.requires_signing() and auth_chain is None: raise ArgumentError("You must pass an auth chain to sign this report.") if self.requires_id() and report_id is None: raise ArgumentError("You must pass a report_id to serialize this report") if self.format == 'individual': reading = self.walker.pop() highest_id = reading.reading_id if self.report_type == 'telegram': return StreamerReport(IndividualReadingReport.FromReadings(device_id, [reading]), 1, highest_id) elif self.report_type == 'broadcast': return StreamerReport(BroadcastReport.FromReadings(device_id, [reading], device_uptime), 1, highest_id) elif self.format == 'hashedlist': max_readings = (max_size - 20 - 24) // 16 if max_readings <= 0: raise InternalError("max_size is too small to hold even a single reading", max_size=max_size) readings = [] highest_id = 0 try: while len(readings) < max_readings: reading = self.walker.pop() readings.append(reading) if reading.reading_id > highest_id: highest_id = reading.reading_id except StreamEmptyError: if len(readings) == 0: raise return StreamerReport(SignedListReport.FromReadings(device_id, readings, report_id=report_id, selector=self.selector.encode(), streamer=self.index, sent_timestamp=device_uptime), len(readings), highest_id) raise InternalError("Streamer report format or type is not supported currently", report_format=self.format, report_type=self.report_type)
[ "def", "build_report", "(", "self", ",", "device_id", ",", "max_size", "=", "None", ",", "device_uptime", "=", "0", ",", "report_id", "=", "None", ",", "auth_chain", "=", "None", ")", ":", "if", "self", ".", "walker", "is", "None", "or", "self", ".", ...
Build a report with all of the readings in this streamer. This method will produce an IOTileReport subclass and, if necessary, sign it using the passed authentication chain. Args: device_id (int): The UUID of the device to generate a report for. max_size (int): Optional maximum number of bytes that the report can be device_uptime (int): The device's uptime to use as the sent timestamp of the report report_id (int): The report id to use if the report type require serialization. auth_chain (AuthChain): An auth chain class to use to sign the report if the report type requires signing. Returns: StreamerReport: The report, its highest id and the number of readings in it. The highest reading id and number of readings are returned separately from the report itself because, depending on the format of the report (such as whether it is encrypted or does not contain reading ids), these details may not be recoverable from the report itself. Raises: InternalError: If there was no SensorLog passed when this streamer was created. StreamEmptyError: If there is no data to generate a report from. This can only happen if a call to triggered() returned False. ArgumentError: If the report requires additional metadata that was not passed like a signing key or report_id.
[ "Build", "a", "report", "with", "all", "of", "the", "readings", "in", "this", "streamer", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/streamer.py#L140-L209
23,498
iotile/coretools
iotilesensorgraph/iotile/sg/slot.py
SlotIdentifier.matches
def matches(self, address, name=None): """Check if this slot identifier matches the given tile. Matching can happen either by address or by module name (not currently implemented). Returns: bool: True if there is a match, otherwise False. """ if self.controller: return address == 8 return self.address == address
python
def matches(self, address, name=None): if self.controller: return address == 8 return self.address == address
[ "def", "matches", "(", "self", ",", "address", ",", "name", "=", "None", ")", ":", "if", "self", ".", "controller", ":", "return", "address", "==", "8", "return", "self", ".", "address", "==", "address" ]
Check if this slot identifier matches the given tile. Matching can happen either by address or by module name (not currently implemented). Returns: bool: True if there is a match, otherwise False.
[ "Check", "if", "this", "slot", "identifier", "matches", "the", "given", "tile", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/slot.py#L64-L76
23,499
iotile/coretools
iotilesensorgraph/iotile/sg/slot.py
SlotIdentifier.FromString
def FromString(cls, desc): """Create a slot identifier from a string description. The string needs to be either: controller OR slot <X> where X is an integer that can be converted with int(X, 0) Args: desc (str): The string description of the slot Returns: SlotIdentifier """ desc = str(desc) if desc == u'controller': return SlotIdentifier(controller=True) words = desc.split() if len(words) != 2 or words[0] != u'slot': raise ArgumentError(u"Illegal slot identifier", descriptor=desc) try: slot_id = int(words[1], 0) except ValueError: raise ArgumentError(u"Could not convert slot identifier to number", descriptor=desc, number=words[1]) return SlotIdentifier(slot=slot_id)
python
def FromString(cls, desc): desc = str(desc) if desc == u'controller': return SlotIdentifier(controller=True) words = desc.split() if len(words) != 2 or words[0] != u'slot': raise ArgumentError(u"Illegal slot identifier", descriptor=desc) try: slot_id = int(words[1], 0) except ValueError: raise ArgumentError(u"Could not convert slot identifier to number", descriptor=desc, number=words[1]) return SlotIdentifier(slot=slot_id)
[ "def", "FromString", "(", "cls", ",", "desc", ")", ":", "desc", "=", "str", "(", "desc", ")", "if", "desc", "==", "u'controller'", ":", "return", "SlotIdentifier", "(", "controller", "=", "True", ")", "words", "=", "desc", ".", "split", "(", ")", "if...
Create a slot identifier from a string description. The string needs to be either: controller OR slot <X> where X is an integer that can be converted with int(X, 0) Args: desc (str): The string description of the slot Returns: SlotIdentifier
[ "Create", "a", "slot", "identifier", "from", "a", "string", "description", "." ]
2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/slot.py#L79-L109