Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def _save_file(self, data): if platform.system() == 'Windows': with open(self.file, "w") as outfile: json.dump(data, outfile) else: newpath = self.file + '.new' with open(newpath, "w") as outfile: json.dump(data, outfile) os.rename( os.path.realpath(newpath), os.path.realpath(self.file) )
[ "Attempt to atomically save file by saving and then moving into position\n\n The goal is to make it difficult for a crash to corrupt our data file since\n the move operation can be made atomic if needed on mission critical filesystems.\n " ]
Please provide a description of the function:def remove(self, key): data = self._load_file() del data[key] self._save_file(data)
[ "Remove a key from the data store\n\n Args:\n key (string): The key to remove\n\n Raises:\n KeyError: if the key was not found\n " ]
Please provide a description of the function:def set(self, key, value): data = self._load_file() data[key] = value self._save_file(data)
[ "Set the value of a key\n\n Args:\n key (string): The key used to store this value\n value (string): The value to store\n " ]
Please provide a description of the function:def trigger_chain(self): trigger_stream = self.allocator.attach_stream(self.trigger_stream) return (trigger_stream, self.trigger_cond)
[ "Return a NodeInput tuple for creating a node.\n\n Returns:\n (StreamIdentifier, InputTrigger)\n " ]
Please provide a description of the function:def add_common_cc_variables(env): if '_CCCOMCOM' not in env: env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS' # It's a hack to test for darwin here, but the alternative # of creating an applecc.py to contain this seems overkill. # Maybe someday the Apple platform will require more setup and # this logic will be moved. env['FRAMEWORKS'] = SCons.Util.CLVar('') env['FRAMEWORKPATH'] = SCons.Util.CLVar('') if env['PLATFORM'] == 'darwin': env['_CCCOMCOM'] = env['_CCCOMCOM'] + ' $_FRAMEWORKPATH' if 'CCFLAGS' not in env: env['CCFLAGS'] = SCons.Util.CLVar('') if 'SHCCFLAGS' not in env: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
[ "\n Add underlying common \"C compiler\" variables that\n are used by multiple tools (specifically, c++).\n " ]
Please provide a description of the function:def generate(env): static_obj, shared_obj = SCons.Tool.createObjBuilders(env) for suffix in CSuffixes: static_obj.add_action(suffix, SCons.Defaults.CAction) shared_obj.add_action(suffix, SCons.Defaults.ShCAction) static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter) shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter) add_common_cc_variables(env) if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] env['CFLAGS'] = SCons.Util.CLVar('') env['CCCOM'] = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES' env['SHCC'] = '$CC' env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS') env['SHCCCOM'] = '$SHCC -o $TARGET -c $SHCFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES' env['CPPDEFPREFIX'] = '-D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '-I' env['INCSUFFIX'] = '' env['SHOBJSUFFIX'] = '.os' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0 env['CFILESUFFIX'] = '.c'
[ "\n Add Builders and construction variables for C compilers to an Environment.\n " ]
Please provide a description of the function:def build_args(): parser = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument(u'sensor_graph', type=str, help=u"The sensor graph file to load and run.") parser.add_argument(u'--stop', u'-s', action=u"append", default=[], type=str, help=u"A stop condition for when the simulation should end.") parser.add_argument(u'--realtime', u'-r', action=u"store_true", help=u"Do not accelerate the simulation, pin the ticks to wall clock time") parser.add_argument(u'--watch', u'-w', action=u"append", default=[], help=u"A stream to watch and print whenever writes are made.") parser.add_argument(u'--trace', u'-t', help=u"Trace all writes to output streams to a file") parser.add_argument(u'--disable-optimizer', action="store_true", help=u"disable the sensor graph optimizer completely") parser.add_argument(u"--mock-rpc", u"-m", action=u"append", type=str, default=[], help=u"mock an rpc, format should be <slot id>:<rpc_id> = value. For example -m \"slot 1:0x500a = 10\"") parser.add_argument(u"--port", u"-p", help=u"The port to use to connect to a device if we are semihosting") parser.add_argument(u"--semihost-device", u"-d", type=lambda x: int(x, 0), help=u"The device id of the device we should semihost this sensor graph on.") parser.add_argument(u"-c", u"--connected", action="store_true", help=u"Simulate with a user connected to the device (to enable realtime outputs)") parser.add_argument(u"-i", u"--stimulus", action=u"append", default=[], help="Push a value to an input stream at the specified time (or before starting). The syntax is [time: ][system ]input X = Y where X and Y are integers") return parser
[ "Create command line argument parser." ]
Please provide a description of the function:def process_mock_rpc(input_string): spec, equals, value = input_string.partition(u'=') if len(equals) == 0: print("Could not parse mock RPC argument: {}".format(input_string)) sys.exit(1) try: value = int(value.strip(), 0) except ValueError as exc: print("Could not parse mock RPC value: {}".format(str(exc))) sys.exit(1) slot, part, rpc_id = spec.partition(u":") if len(part) == 0: print("Could not parse mock RPC slot/rpc definition: {}".format(spec)) sys.exit(1) try: slot = SlotIdentifier.FromString(slot) except ArgumentError as exc: print("Could not parse slot id in mock RPC definition: {}".format(exc.msg)) sys.exit(1) try: rpc_id = int(rpc_id, 0) except ValueError as exc: print("Could not parse mock RPC number: {}".format(str(exc))) sys.exit(1) return slot, rpc_id, value
[ "Process a mock RPC argument.\n\n Args:\n input_string (str): The input string that should be in the format\n <slot id>:<rpc id> = value\n " ]
Please provide a description of the function:def watch_printer(watch, value): print("({: 8} s) {}: {}".format(value.raw_time, watch, value.value))
[ "Print a watched value.\n\n Args:\n watch (DataStream): The stream that was watched\n value (IOTileReading): The value to was seen\n " ]
Please provide a description of the function:def main(argv=None): if argv is None: argv = sys.argv[1:] try: executor = None parser = build_args() args = parser.parse_args(args=argv) model = DeviceModel() parser = SensorGraphFileParser() parser.parse_file(args.sensor_graph) parser.compile(model) if not args.disable_optimizer: opt = SensorGraphOptimizer() opt.optimize(parser.sensor_graph, model=model) graph = parser.sensor_graph sim = SensorGraphSimulator(graph) for stop in args.stop: sim.stop_condition(stop) for watch in args.watch: watch_sel = DataStreamSelector.FromString(watch) graph.sensor_log.watch(watch_sel, watch_printer) # If we are semihosting, create the appropriate executor connected to the device if args.semihost_device is not None: executor = SemihostedRPCExecutor(args.port, args.semihost_device) sim.rpc_executor = executor for mock in args.mock_rpc: slot, rpc_id, value = process_mock_rpc(mock) sim.rpc_executor.mock(slot, rpc_id, value) for stim in args.stimulus: sim.stimulus(stim) graph.load_constants() if args.trace is not None: sim.record_trace() try: if args.connected: sim.step(user_connected, 8) sim.run(accelerated=not args.realtime) except KeyboardInterrupt: pass if args.trace is not None: sim.trace.save(args.trace) finally: if executor is not None: executor.hw.close() return 0
[ "Main entry point for iotile sensorgraph simulator.\n\n This is the iotile-sgrun command line program. It takes\n an optional set of command line parameters to allow for\n testing.\n\n Args:\n argv (list of str): An optional set of command line\n parameters. If not passed, these are taken from\n sys.argv.\n " ]
Please provide a description of the function:def _verify_tile_versions(self, hw): for tile, expected_tile_version in self._tile_versions.items(): actual_tile_version = str(hw.get(tile).tile_version()) if expected_tile_version != actual_tile_version: raise ArgumentError("Tile has incorrect firmware", tile=tile, \ expected_version=expected_tile_version, actual_version=actual_tile_version)
[ "Verify that the tiles have the correct versions\n " ]
Please provide a description of the function:def _verify_os_app_settings(self, hw): con = hw.controller() info = con.test_interface().get_info() if self._os_tag is not None: if info['os_tag'] != self._os_tag: raise ArgumentError("Incorrect os_tag", actual_os_tag=info['os_tag'],\ expected_os_tag=self._os_tag) if self._app_tag is not None: if info['app_tag'] != self._app_tag: raise ArgumentError("Incorrect app_tag", actual_os_tag=info['app_tag'],\ expected_os_tag=self._app_tag) if self._os_version is not None: if info['os_version'] != self._os_version: raise ArgumentError("Incorrect os_version", actual_os_version=info['os_version'],\ expected_os_version=self._os_version) if self._app_version is not None: if info['app_version'] != self._app_version: raise ArgumentError("Incorrect app_version", actual_os_version=info['app_version'],\ expected_os_version=self._app_version)
[ "Verify that the os and app tags/versions are set correctly\n " ]
Please provide a description of the function:def _verify_realtime_streams(self, hw): print("--> Testing realtime data (takes 2 seconds)") time.sleep(2.1) reports = [x for x in hw.iter_reports()] reports_seen = {key: 0 for key in self._realtime_streams} for report in reports: stream_value = report.visible_readings[0].stream if reports_seen.get(stream_value) is not None: reports_seen[stream_value] += 1 for stream in reports_seen.keys(): if reports_seen[stream] < 2: raise ArgumentError("Realtime Stream not pushing any reports", stream=hex(stream), \ reports_seen=reports_seen[stream])
[ "Check that the realtime streams are being produced\n " ]
Please provide a description of the function:def _update_pot_file(target, source, env): import re import os import SCons.Action nop = lambda target, source, env: 0 # Save scons cwd and os cwd (NOTE: they may be different. After the job, we # revert each one to its original state). save_cwd = env.fs.getcwd() save_os_cwd = os.getcwd() chdir = target[0].dir chdir_str = repr(chdir.get_abspath()) # Print chdir message (employ SCons.Action.Action for that. It knows better # than me how to to this correctly). env.Execute(SCons.Action.Action(nop, "Entering " + chdir_str)) # Go to target's directory and do our job env.fs.chdir(chdir, 1) # Go into target's directory try: cmd = _CmdRunner('$XGETTEXTCOM', '$XGETTEXTCOMSTR') action = SCons.Action.Action(cmd, strfunction=cmd.strfunction) status = action([target[0]], source, env) except: # Something went wrong. env.Execute(SCons.Action.Action(nop, "Leaving " + chdir_str)) # Revert working dirs to previous state and re-throw exception. env.fs.chdir(save_cwd, 0) os.chdir(save_os_cwd) raise # Print chdir message. env.Execute(SCons.Action.Action(nop, "Leaving " + chdir_str)) # Revert working dirs to previous state. env.fs.chdir(save_cwd, 0) os.chdir(save_os_cwd) # If the command was not successfull, return error code. if status: return status new_content = cmd.out if not new_content: # When xgettext finds no internationalized messages, no *.pot is created # (because we don't want to bother translators with empty POT files). needs_update = False explain = "no internationalized messages encountered" else: if target[0].exists(): # If the file already exists, it's left unaltered unless its messages # are outdated (w.r.t. to these recovered by xgettext from sources). old_content = target[0].get_text_contents() re_cdate = re.compile(r'^"POT-Creation-Date: .*"$[\r\n]?', re.M) old_content_nocdate = re.sub(re_cdate, "", old_content) new_content_nocdate = re.sub(re_cdate, "", new_content) if (old_content_nocdate == new_content_nocdate): # Messages are up-to-date needs_update = False explain = "messages in file found to be up-to-date" else: # Messages are outdated needs_update = True explain = "messages in file were outdated" else: # No POT file found, create new one needs_update = True explain = "new file" if needs_update: # Print message employing SCons.Action.Action for that. msg = "Writing " + repr(str(target[0])) + " (" + explain + ")" env.Execute(SCons.Action.Action(nop, msg)) f = open(str(target[0]), "w") f.write(new_content) f.close() return 0 else: # Print message employing SCons.Action.Action for that. msg = "Not writing " + repr(str(target[0])) + " (" + explain + ")" env.Execute(SCons.Action.Action(nop, msg)) return 0
[ " Action function for `POTUpdate` builder " ]
Please provide a description of the function:def _scan_xgettext_from_files(target, source, env, files=None, path=None): import re import SCons.Util import SCons.Node.FS if files is None: return 0 if not SCons.Util.is_List(files): files = [files] if path is None: if 'XGETTEXTPATH' in env: path = env['XGETTEXTPATH'] else: path = [] if not SCons.Util.is_List(path): path = [path] path = SCons.Util.flatten(path) dirs = () for p in path: if not isinstance(p, SCons.Node.FS.Base): if SCons.Util.is_String(p): p = env.subst(p, source=source, target=target) p = env.arg2nodes(p, env.fs.Dir) dirs += tuple(p) # cwd is the default search path (when no path is defined by user) if not dirs: dirs = (env.fs.getcwd(),) # Parse 'POTFILE.in' files. re_comment = re.compile(r'^#[^\n\r]*$\r?\n?', re.M) re_emptyln = re.compile(r'^[ \t\r]*$\r?\n?', re.M) re_trailws = re.compile(r'[ \t\r]+$') for f in files: # Find files in search path $XGETTEXTPATH if isinstance(f, SCons.Node.FS.Base) and f.rexists(): contents = f.get_text_contents() contents = re_comment.sub("", contents) contents = re_emptyln.sub("", contents) contents = re_trailws.sub("", contents) depnames = contents.splitlines() for depname in depnames: depfile = SCons.Node.FS.find_file(depname, dirs) if not depfile: depfile = env.arg2nodes(depname, dirs[0].File) env.Depends(target, depfile) return 0
[ " Parses `POTFILES.in`-like file and returns list of extracted file names.\n " ]
Please provide a description of the function:def _pot_update_emitter(target, source, env): from SCons.Tool.GettextCommon import _POTargetFactory import SCons.Util import SCons.Node.FS if 'XGETTEXTFROM' in env: xfrom = env['XGETTEXTFROM'] else: return target, source if not SCons.Util.is_List(xfrom): xfrom = [xfrom] xfrom = SCons.Util.flatten(xfrom) # Prepare list of 'POTFILE.in' files. files = [] for xf in xfrom: if not isinstance(xf, SCons.Node.FS.Base): if SCons.Util.is_String(xf): # Interpolate variables in strings xf = env.subst(xf, source=source, target=target) xf = env.arg2nodes(xf) files.extend(xf) if files: env.Depends(target, files) _scan_xgettext_from_files(target, source, env, files) return target, source
[ " Emitter function for `POTUpdate` builder " ]
Please provide a description of the function:def _POTUpdateBuilder(env, **kw): import SCons.Action from SCons.Tool.GettextCommon import _POTargetFactory kw['action'] = SCons.Action.Action(_update_pot_file, None) kw['suffix'] = '$POTSUFFIX' kw['target_factory'] = _POTargetFactory(env, alias='$POTUPDATE_ALIAS').File kw['emitter'] = _pot_update_emitter return _POTBuilder(**kw)
[ " Creates `POTUpdate` builder object " ]
Please provide a description of the function:def generate(env, **kw): import SCons.Util from SCons.Tool.GettextCommon import RPaths, _detect_xgettext try: env['XGETTEXT'] = _detect_xgettext(env) except: env['XGETTEXT'] = 'xgettext' # NOTE: sources="$SOURCES" would work as well. However, we use following # construction to convert absolute paths provided by scons onto paths # relative to current working dir. Note, that scons expands $SOURCE(S) to # absolute paths for sources $SOURCE(s) outside of current subtree (e.g. in # "../"). With source=$SOURCE these absolute paths would be written to the # resultant *.pot file (and its derived *.po files) as references to lines in # source code (e.g. referring lines in *.c files). Such references would be # correct (e.g. in poedit) only on machine on which *.pot was generated and # would be of no use on other hosts (having a copy of source code located # in different place in filesystem). sources = '$( ${_concat( "", SOURCES, "", __env__, XgettextRPaths, TARGET' \ + ', SOURCES)} $)' # NOTE: the output from $XGETTEXTCOM command must go to stdout, not to a file. # This is required by the POTUpdate builder's action. xgettextcom = '$XGETTEXT $XGETTEXTFLAGS $_XGETTEXTPATHFLAGS' \ + ' $_XGETTEXTFROMFLAGS -o - ' + sources xgettextpathflags = '$( ${_concat( XGETTEXTPATHPREFIX, XGETTEXTPATH' \ + ', XGETTEXTPATHSUFFIX, __env__, RDirs, TARGET, SOURCES)} $)' xgettextfromflags = '$( ${_concat( XGETTEXTFROMPREFIX, XGETTEXTFROM' \ + ', XGETTEXTFROMSUFFIX, __env__, target=TARGET, source=SOURCES)} $)' env.SetDefault( _XGETTEXTDOMAIN='${TARGET.filebase}', XGETTEXTFLAGS=[], XGETTEXTCOM=xgettextcom, XGETTEXTCOMSTR='', XGETTEXTPATH=[], XGETTEXTPATHPREFIX='-D', XGETTEXTPATHSUFFIX='', XGETTEXTFROM=None, XGETTEXTFROMPREFIX='-f', XGETTEXTFROMSUFFIX='', _XGETTEXTPATHFLAGS=xgettextpathflags, _XGETTEXTFROMFLAGS=xgettextfromflags, POTSUFFIX=['.pot'], POTUPDATE_ALIAS='pot-update', XgettextRPaths=RPaths(env) ) env.Append(BUILDERS={ '_POTUpdateBuilder': _POTUpdateBuilder(env) }) env.AddMethod(_POTUpdateBuilderWrapper, 'POTUpdate') env.AlwaysBuild(env.Alias('$POTUPDATE_ALIAS'))
[ " Generate `xgettext` tool " ]
Please provide a description of the function:def generate(env): if 'CC' not in env: env['CC'] = env.Detect(compilers) or compilers[0] cc.generate(env) if env['PLATFORM'] in ['cygwin', 'win32']: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') else: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC') # determine compiler version version = detect_version(env, env['CC']) if version: env['CCVERSION'] = version
[ "Add Builders and construction variables for gcc to an Environment." ]
Please provide a description of the function:def detect_version(env, cc): cc = env.subst(cc) if not cc: return None version = None #pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['-dumpversion'], pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + ['--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) # -dumpversion was added in GCC 3.0. As long as we're supporting # GCC versions older than that, we should use --version and a # regular expression. #line = pipe.stdout.read().strip() #if line: # version = line line = SCons.Util.to_str(pipe.stdout.readline()) match = re.search(r'[0-9]+(\.[0-9]+)+', line) if match: version = match.group(0) # Non-GNU compiler's output (like AIX xlc's) may exceed the stdout buffer: # So continue with reading to let the child process actually terminate. while SCons.Util.to_str(pipe.stdout.readline()): pass ret = pipe.wait() if ret != 0: return None return version
[ "Return the version of the GNU compiler, or None if it is not a GNU compiler." ]
Please provide a description of the function:def convert_to_id(s, id_set): charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.' if s[0] in '0123456789.': s += '_'+s id = [c for c in s if c in charset] # did we already generate an id for this file? try: return id_set[id][s] except KeyError: # no we did not, so initialize with the id if id not in id_set: id_set[id] = { s : id } # there is a collision, generate an id which is unique by appending # the collision number else: id_set[id][s] = id + str(len(id_set[id])) return id_set[id][s]
[ " Some parts of .wxs need an Id attribute (for example: The File and\n Directory directives. The charset is limited to A-Z, a-z, digits,\n underscores, periods. Each Id must begin with a letter or with a\n underscore. Google for \"CNDL0015\" for information about this.\n\n Requirements:\n * the string created must only contain chars from the target charset.\n * the string created must have a minimal editing distance from the\n original string.\n * the string created must be unique for the whole .wxs file.\n\n Observation:\n * There are 62 chars in the charset.\n\n Idea:\n * filter out forbidden characters. Check for a collision with the help\n of the id_set. Add the number of the number of the collision at the\n end of the created string. Furthermore care for a correct start of\n the string.\n " ]
Please provide a description of the function:def is_dos_short_file_name(file): fname, ext = os.path.splitext(file) proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot proper_fname = file.isupper() and len(fname) <= 8 return proper_ext and proper_fname
[ " Examine if the given file is in the 8.3 form.\n " ]
Please provide a description of the function:def gen_dos_short_file_name(file, filename_set): # guard this to not confuse the generation if is_dos_short_file_name(file): return file fname, ext = os.path.splitext(file) # ext contains the dot # first try if it suffices to convert to upper file = file.upper() if is_dos_short_file_name(file): return file # strip forbidden characters. forbidden = '."/[]:;=, ' fname = [c for c in fname if c not in forbidden] # check if we already generated a filename with the same number: # thisis1.txt, thisis2.txt etc. duplicate, num = not None, 1 while duplicate: shortname = "%s%s" % (fname[:8-len(str(num))].upper(),\ str(num)) if len(ext) >= 2: shortname = "%s%s" % (shortname, ext[:4].upper()) duplicate, num = shortname in filename_set, num+1 assert( is_dos_short_file_name(shortname) ), 'shortname is %s, longname is %s' % (shortname, file) filename_set.append(shortname) return shortname
[ " See http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982\n\n These are no complete 8.3 dos short names. The ~ char is missing and \n replaced with one character from the filename. WiX warns about such\n filenames, since a collision might occur. Google for \"CNDL1014\" for\n more information.\n " ]
Please provide a description of the function:def create_feature_dict(files): dict = {} def add_to_dict( feature, file ): if not SCons.Util.is_List( feature ): feature = [ feature ] for f in feature: if f not in dict: dict[ f ] = [ file ] else: dict[ f ].append( file ) for file in files: if hasattr( file, 'PACKAGING_X_MSI_FEATURE' ): add_to_dict(file.PACKAGING_X_MSI_FEATURE, file) elif hasattr( file, 'PACKAGING_DOC' ): add_to_dict( 'PACKAGING_DOC', file ) else: add_to_dict( 'default', file ) return dict
[ " X_MSI_FEATURE and doc FileTag's can be used to collect files in a\n hierarchy. This function collects the files into this hierarchy.\n " ]
Please provide a description of the function:def generate_guids(root): from hashlib import md5 # specify which tags need a guid and in which attribute this should be stored. needs_id = { 'Product' : 'Id', 'Package' : 'Id', 'Component' : 'Guid', } # find all XMl nodes matching the key, retrieve their attribute, hash their # subtree, convert hash to string and add as a attribute to the xml node. for (key,value) in needs_id.items(): node_list = root.getElementsByTagName(key) attribute = value for node in node_list: hash = md5(node.toxml()).hexdigest() hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] ) node.attributes[attribute] = hash_str
[ " generates globally unique identifiers for parts of the xml which need\n them.\n\n Component tags have a special requirement. Their UUID is only allowed to\n change if the list of their contained resources has changed. This allows\n for clean removal and proper updates.\n\n To handle this requirement, the uuid is generated with an md5 hashing the\n whole subtree of a xml node.\n " ]
Please provide a description of the function:def build_wxsfile(target, source, env): file = open(target[0].get_abspath(), 'w') try: # Create a document with the Wix root tag doc = Document() root = doc.createElement( 'Wix' ) root.attributes['xmlns']='http://schemas.microsoft.com/wix/2003/01/wi' doc.appendChild( root ) filename_set = [] # this is to circumvent duplicates in the shortnames id_set = {} # this is to circumvent duplicates in the ids # Create the content build_wxsfile_header_section(root, env) build_wxsfile_file_section(root, source, env['NAME'], env['VERSION'], env['VENDOR'], filename_set, id_set) generate_guids(root) build_wxsfile_features_section(root, source, env['NAME'], env['VERSION'], env['SUMMARY'], id_set) build_wxsfile_default_gui(root) build_license_file(target[0].get_dir(), env) # write the xml to a file file.write( doc.toprettyxml() ) # call a user specified function if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError as e: raise SCons.Errors.UserError( '"%s" package field for MSI is missing.' % e.args[0] )
[ " Compiles a .wxs file from the keywords given in env['msi_spec'] and\n by analyzing the tree of source nodes and their tags.\n " ]
Please provide a description of the function:def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set): doc = Document() d1 = doc.createElement( 'Directory' ) d1.attributes['Id'] = 'TARGETDIR' d1.attributes['Name'] = 'SourceDir' d2 = doc.createElement( 'Directory' ) d2.attributes['Id'] = 'ProgramFilesFolder' d2.attributes['Name'] = 'PFiles' d3 = doc.createElement( 'Directory' ) d3.attributes['Id'] = 'VENDOR_folder' d3.attributes['Name'] = escape( gen_dos_short_file_name( VENDOR, filename_set ) ) d3.attributes['LongName'] = escape( VENDOR ) d4 = doc.createElement( 'Directory' ) project_folder = "%s-%s" % ( NAME, VERSION ) d4.attributes['Id'] = 'MY_DEFAULT_FOLDER' d4.attributes['Name'] = escape( gen_dos_short_file_name( project_folder, filename_set ) ) d4.attributes['LongName'] = escape( project_folder ) d1.childNodes.append( d2 ) d2.childNodes.append( d3 ) d3.childNodes.append( d4 ) root.getElementsByTagName('Product')[0].childNodes.append( d1 ) return d4
[ " Create the wix default target directory layout and return the innermost\n directory.\n\n We assume that the XML tree delivered in the root argument already contains\n the Product tag.\n\n Everything is put under the PFiles directory property defined by WiX.\n After that a directory with the 'VENDOR' tag is placed and then a\n directory with the name of the project and its VERSION. This leads to the\n following TARGET Directory Layout:\n C:\\<PFiles>\\<Vendor>\\<Projectname-Version>\\\n Example: C:\\Programme\\Company\\Product-1.2\\\n " ]
Please provide a description of the function:def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set): root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set ) components = create_feature_dict( files ) factory = Document() def get_directory( node, dir ): if dir == '' or not dir: return node Directory = node dir_parts = dir.split(os.path.sep) # to make sure that our directory ids are unique, the parent folders are # consecutively added to upper_dir upper_dir = '' # walk down the xml tree finding parts of the directory dir_parts = [d for d in dir_parts if d != ''] for d in dir_parts[:]: already_created = [c for c in Directory.childNodes if c.nodeName == 'Directory' and c.attributes['LongName'].value == escape(d)] if already_created != []: Directory = already_created[0] dir_parts.remove(d) upper_dir += d else: break for d in dir_parts: nDirectory = factory.createElement( 'Directory' ) nDirectory.attributes['LongName'] = escape( d ) nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) ) upper_dir += d nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set ) Directory.childNodes.append( nDirectory ) Directory = nDirectory return Directory for file in files: drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION ) filename = os.path.basename( path ) dirname = os.path.dirname( path ) h = { # tagname : default value 'PACKAGING_X_MSI_VITAL' : 'yes', 'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set), 'PACKAGING_X_MSI_LONGNAME' : filename, 'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set), 'PACKAGING_X_MSI_SOURCE' : file.get_path(), } # fill in the default tags given above. for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]: setattr( file, k, v ) File = factory.createElement( 'File' ) File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME ) File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME ) File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE ) File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID ) File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL ) # create the <Component> Tag under which this file should appear Component = factory.createElement('Component') Component.attributes['DiskId'] = '1' Component.attributes['Id'] = convert_to_id( filename, id_set ) # hang the component node under the root node and the file node # under the component node. Directory = get_directory( root, dirname ) Directory.childNodes.append( Component ) Component.childNodes.append( File )
[ " Builds the Component sections of the wxs file with their included files.\n\n Files need to be specified in 8.3 format and in the long name format, long\n filenames will be converted automatically.\n\n Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag.\n ", " Returns the node under the given node representing the directory.\n\n Returns the component node if dir is None or empty.\n " ]
Please provide a description of the function:def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set): factory = Document() Feature = factory.createElement('Feature') Feature.attributes['Id'] = 'complete' Feature.attributes['ConfigurableDirectory'] = 'MY_DEFAULT_FOLDER' Feature.attributes['Level'] = '1' Feature.attributes['Title'] = escape( '%s %s' % (NAME, VERSION) ) Feature.attributes['Description'] = escape( SUMMARY ) Feature.attributes['Display'] = 'expand' for (feature, files) in create_feature_dict(files).items(): SubFeature = factory.createElement('Feature') SubFeature.attributes['Level'] = '1' if SCons.Util.is_Tuple(feature): SubFeature.attributes['Id'] = convert_to_id( feature[0], id_set ) SubFeature.attributes['Title'] = escape(feature[0]) SubFeature.attributes['Description'] = escape(feature[1]) else: SubFeature.attributes['Id'] = convert_to_id( feature, id_set ) if feature=='default': SubFeature.attributes['Description'] = 'Main Part' SubFeature.attributes['Title'] = 'Main Part' elif feature=='PACKAGING_DOC': SubFeature.attributes['Description'] = 'Documentation' SubFeature.attributes['Title'] = 'Documentation' else: SubFeature.attributes['Description'] = escape(feature) SubFeature.attributes['Title'] = escape(feature) # build the componentrefs. As one of the design decision is that every # file is also a component we walk the list of files and create a # reference. for f in files: ComponentRef = factory.createElement('ComponentRef') ComponentRef.attributes['Id'] = convert_to_id( os.path.basename(f.get_path()), id_set ) SubFeature.childNodes.append(ComponentRef) Feature.childNodes.append(SubFeature) root.getElementsByTagName('Product')[0].childNodes.append(Feature)
[ " This function creates the <features> tag based on the supplied xml tree.\n\n This is achieved by finding all <component>s and adding them to a default target.\n\n It should be called after the tree has been built completly. We assume\n that a MY_DEFAULT_FOLDER Property is defined in the wxs file tree.\n\n Furthermore a top-level with the name and VERSION of the software will be created.\n\n An PACKAGING_X_MSI_FEATURE can either be a string, where the feature\n DESCRIPTION will be the same as its title or a Tuple, where the first\n part will be its title and the second its DESCRIPTION.\n " ]
Please provide a description of the function:def build_wxsfile_default_gui(root): factory = Document() Product = root.getElementsByTagName('Product')[0] UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_Mondo' Product.childNodes.append(UIRef) UIRef = factory.createElement('UIRef') UIRef.attributes['Id'] = 'WixUI_ErrorProgressText' Product.childNodes.append(UIRef)
[ " This function adds a default GUI to the wxs file\n " ]
Please provide a description of the function:def build_license_file(directory, spec): name, text = '', '' try: name = spec['LICENSE'] text = spec['X_MSI_LICENSE_TEXT'] except KeyError: pass # ignore this as X_MSI_LICENSE_TEXT is optional if name!='' or text!='': file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' ) file.write('{\\rtf') if text!='': file.write(text.replace('\n', '\\par ')) else: file.write(name+'\\par\\par') file.write('}') file.close()
[ " Creates a License.rtf file with the content of \"X_MSI_LICENSE_TEXT\"\n in the given directory\n " ]
Please provide a description of the function:def build_wxsfile_header_section(root, spec): # Create the needed DOM nodes and add them at the correct position in the tree. factory = Document() Product = factory.createElement( 'Product' ) Package = factory.createElement( 'Package' ) root.childNodes.append( Product ) Product.childNodes.append( Package ) # set "mandatory" default values if 'X_MSI_LANGUAGE' not in spec: spec['X_MSI_LANGUAGE'] = '1033' # select english # mandatory sections, will throw a KeyError if the tag is not available Product.attributes['Name'] = escape( spec['NAME'] ) Product.attributes['Version'] = escape( spec['VERSION'] ) Product.attributes['Manufacturer'] = escape( spec['VENDOR'] ) Product.attributes['Language'] = escape( spec['X_MSI_LANGUAGE'] ) Package.attributes['Description'] = escape( spec['SUMMARY'] ) # now the optional tags, for which we avoid the KeyErrror exception if 'DESCRIPTION' in spec: Package.attributes['Comments'] = escape( spec['DESCRIPTION'] ) if 'X_MSI_UPGRADE_CODE' in spec: Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] ) # We hardcode the media tag as our current model cannot handle it. Media = factory.createElement('Media') Media.attributes['Id'] = '1' Media.attributes['Cabinet'] = 'default.cab' Media.attributes['EmbedCab'] = 'yes' root.getElementsByTagName('Product')[0].childNodes.append(Media)
[ " Adds the xml file node which define the package meta-data.\n " ]
Please provide a description of the function:def generate(env): path, cxx, shcxx, version = get_cppc(env) if path: cxx = os.path.join(path, cxx) shcxx = os.path.join(path, shcxx) cplusplus.generate(env) env['CXX'] = cxx env['SHCXX'] = shcxx env['CXXVERSION'] = version env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -KPIC') env['SHOBJPREFIX'] = 'so_' env['SHOBJSUFFIX'] = '.o'
[ "Add Builders and construction variables for SunPRO C++." ]
Please provide a description of the function:def FromReadings(cls, uuid, readings, events, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0x100, sent_timestamp=0, received_time=None): lowest_id = IOTileReading.InvalidReadingID highest_id = IOTileReading.InvalidReadingID for item in itertools.chain(iter(readings), iter(events)): if item.reading_id == IOTileReading.InvalidReadingID: continue if lowest_id == IOTileReading.InvalidReadingID or item.reading_id < lowest_id: lowest_id = item.reading_id if highest_id == IOTileReading.InvalidReadingID or item.reading_id > highest_id: highest_id = item.reading_id reading_list = [x.asdict() for x in readings] event_list = [x.asdict() for x in events] report_dict = { "format": cls.FORMAT_TAG, "device": uuid, "streamer_index": streamer, "streamer_selector": selector, "incremental_id": report_id, "lowest_id": lowest_id, "highest_id": highest_id, "device_sent_timestamp": sent_timestamp, "events": event_list, "data": reading_list } encoded = msgpack.packb(report_dict, default=_encode_datetime, use_bin_type=True) return FlexibleDictionaryReport(encoded, signed=False, encrypted=False, received_time=received_time)
[ "Create a flexible dictionary report from a list of readings and events.\n\n Args:\n uuid (int): The uuid of the device that this report came from\n readings (list of IOTileReading): A list of IOTileReading objects containing the data in the report\n events (list of IOTileEvent): A list of the events contained in the report.\n report_id (int): The id of the report. If not provided it defaults to IOTileReading.InvalidReadingID.\n Note that you can specify anything you want for the report id but for actual IOTile devices\n the report id will always be greater than the id of all of the readings contained in the report\n since devices generate ids sequentially.\n selector (int): The streamer selector of this report. This can be anything but if the report came from\n a device, it would correspond with the query the device used to pick readings to go into the report.\n streamer (int): The streamer id that this reading was sent from.\n sent_timestamp (int): The device's uptime that sent this report.\n received_time(datetime): The UTC time when this report was received from an IOTile device. If it is being\n created now, received_time defaults to datetime.utcnow().\n\n Returns:\n FlexibleDictionaryReport: A report containing the readings and events passed in.\n " ]
Please provide a description of the function:def decode(self): report_dict = msgpack.unpackb(self.raw_report, raw=False) events = [IOTileEvent.FromDict(x) for x in report_dict.get('events', [])] readings = [IOTileReading.FromDict(x) for x in report_dict.get('data', [])] if 'device' not in report_dict: raise DataError("Invalid encoded FlexibleDictionaryReport that did not " "have a device key set with the device uuid") self.origin = report_dict['device'] self.report_id = report_dict.get("incremental_id", IOTileReading.InvalidReadingID) self.sent_timestamp = report_dict.get("device_sent_timestamp", 0) self.origin_streamer = report_dict.get("streamer_index") self.streamer_selector = report_dict.get("streamer_selector") self.lowest_id = report_dict.get('lowest_id') self.highest_id = report_dict.get('highest_id') return readings, events
[ "Decode this report from a msgpack encoded binary blob." ]
Please provide a description of the function:def _callable_contents(obj): try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.__func__) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: # Test if obj is a function object. return _function_contents(obj)
[ "Return the signature contents of a callable Python object.\n " ]
Please provide a description of the function:def _object_contents(obj): try: # Test if obj is a method. return _function_contents(obj.__func__) except AttributeError: try: # Test if obj is a callable object. return _function_contents(obj.__call__.__func__) except AttributeError: try: # Test if obj is a code object. return _code_contents(obj) except AttributeError: try: # Test if obj is a function object. return _function_contents(obj) except AttributeError as ae: # Should be a pickle-able Python object. try: return _object_instance_content(obj) # pickling an Action instance or object doesn't yield a stable # content as instance property may be dumped in different orders # return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL) except (pickle.PicklingError, TypeError, AttributeError) as ex: # This is weird, but it seems that nested classes # are unpickable. The Python docs say it should # always be a PicklingError, but some Python # versions seem to return TypeError. Just do # the best we can. return bytearray(repr(obj), 'utf-8')
[ "Return the signature contents of any Python object.\n\n We have to handle the case where object contains a code object\n since it can be pickled directly.\n " ]
Please provide a description of the function:def _code_contents(code, docstring=None): # contents = [] # The code contents depends on the number of local variables # but not their actual names. contents = bytearray("{}, {}".format(code.co_argcount, len(code.co_varnames)), 'utf-8') contents.extend(b", ") contents.extend(bytearray(str(len(code.co_cellvars)), 'utf-8')) contents.extend(b", ") contents.extend(bytearray(str(len(code.co_freevars)), 'utf-8')) # The code contents depends on any constants accessed by the # function. Note that we have to call _object_contents on each # constants because the code object of nested functions can # show-up among the constants. z = [_object_contents(cc) for cc in code.co_consts[1:]] contents.extend(b',(') contents.extend(bytearray(',', 'utf-8').join(z)) contents.extend(b')') # The code contents depends on the variable names used to # accessed global variable, as changing the variable name changes # the variable actually accessed and therefore changes the # function result. z= [bytearray(_object_contents(cc)) for cc in code.co_names] contents.extend(b',(') contents.extend(bytearray(',','utf-8').join(z)) contents.extend(b')') # The code contents depends on its actual code!!! contents.extend(b',(') contents.extend(code.co_code) contents.extend(b')') return contents
[ "Return the signature contents of a code object.\n\n By providing direct access to the code object of the\n function, Python makes this extremely easy. Hooray!\n\n Unfortunately, older versions of Python include line\n number indications in the compiled byte code. Boo!\n So we remove the line number byte codes to prevent\n recompilations from moving a Python function.\n\n See:\n - https://docs.python.org/2/library/inspect.html\n - http://python-reference.readthedocs.io/en/latest/docs/code/index.html\n\n For info on what each co\\_ variable provides\n\n The signature is as follows (should be byte/chars):\n co_argcount, len(co_varnames), len(co_cellvars), len(co_freevars),\n ( comma separated signature for each object in co_consts ),\n ( comma separated signature for each object in co_names ),\n ( The bytecode with line number bytecodes removed from co_code )\n\n co_argcount - Returns the number of positional arguments (including arguments with default values).\n co_varnames - Returns a tuple containing the names of the local variables (starting with the argument names).\n co_cellvars - Returns a tuple containing the names of local variables that are referenced by nested functions.\n co_freevars - Returns a tuple containing the names of free variables. (?)\n co_consts - Returns a tuple containing the literals used by the bytecode.\n co_names - Returns a tuple containing the names used by the bytecode.\n co_code - Returns a string representing the sequence of bytecode instructions.\n\n " ]
Please provide a description of the function:def _function_contents(func): contents = [_code_contents(func.__code__, func.__doc__)] # The function contents depends on the value of defaults arguments if func.__defaults__: function_defaults_contents = [_object_contents(cc) for cc in func.__defaults__] defaults = bytearray(b',(') defaults.extend(bytearray(b',').join(function_defaults_contents)) defaults.extend(b')') contents.append(defaults) else: contents.append(b',()') # The function contents depends on the closure captured cell values. closure = func.__closure__ or [] try: closure_contents = [_object_contents(x.cell_contents) for x in closure] except AttributeError: closure_contents = [] contents.append(b',(') contents.append(bytearray(b',').join(closure_contents)) contents.append(b')') retval = bytearray(b'').join(contents) return retval
[ "\n The signature is as follows (should be byte/chars):\n < _code_contents (see above) from func.__code__ >\n ,( comma separated _object_contents for function argument defaults)\n ,( comma separated _object_contents for any closure contents )\n\n\n See also: https://docs.python.org/3/reference/datamodel.html\n - func.__code__ - The code object representing the compiled function body.\n - func.__defaults__ - A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value\n - func.__closure__ - None or a tuple of cells that contain bindings for the function's free variables.\n\n :Returns:\n Signature contents of a function. (in bytes)\n " ]
Please provide a description of the function:def _object_instance_content(obj): retval = bytearray() if obj is None: return b'N.' if isinstance(obj, SCons.Util.BaseStringTypes): return SCons.Util.to_bytes(obj) inst_class = obj.__class__ inst_class_name = bytearray(obj.__class__.__name__,'utf-8') inst_class_module = bytearray(obj.__class__.__module__,'utf-8') inst_class_hierarchy = bytearray(repr(inspect.getclasstree([obj.__class__,])),'utf-8') # print("ICH:%s : %s"%(inst_class_hierarchy, repr(obj))) properties = [(p, getattr(obj, p, "None")) for p in dir(obj) if not (p[:2] == '__' or inspect.ismethod(getattr(obj, p)) or inspect.isbuiltin(getattr(obj,p))) ] properties.sort() properties_str = ','.join(["%s=%s"%(p[0],p[1]) for p in properties]) properties_bytes = bytearray(properties_str,'utf-8') methods = [p for p in dir(obj) if inspect.ismethod(getattr(obj, p))] methods.sort() method_contents = [] for m in methods: # print("Method:%s"%m) v = _function_contents(getattr(obj, m)) # print("[%s->]V:%s [%s]"%(m,v,type(v))) method_contents.append(v) retval = bytearray(b'{') retval.extend(inst_class_name) retval.extend(b":") retval.extend(inst_class_module) retval.extend(b'}[[') retval.extend(inst_class_hierarchy) retval.extend(b']]{{') retval.extend(bytearray(b",").join(method_contents)) retval.extend(b"}}{{{") retval.extend(properties_bytes) retval.extend(b'}}}') return retval
[ "\n Returns consistant content for a action class or an instance thereof\n\n :Parameters:\n - `obj` Should be either and action class or an instance thereof\n\n :Returns:\n bytearray or bytes representing the obj suitable for generating a signature from.\n " ]
Please provide a description of the function:def _do_create_keywords(args, kw): v = kw.get('varlist', ()) # prevent varlist="FOO" from being interpreted as ['F', 'O', 'O'] if is_String(v): v = (v,) kw['varlist'] = tuple(v) if args: # turn positional args into equivalent keywords cmdstrfunc = args[0] if cmdstrfunc is None or is_String(cmdstrfunc): kw['cmdstr'] = cmdstrfunc elif callable(cmdstrfunc): kw['strfunction'] = cmdstrfunc else: raise SCons.Errors.UserError( 'Invalid command display variable type. ' 'You must either pass a string or a callback which ' 'accepts (target, source, env) as parameters.') if len(args) > 1: kw['varlist'] = tuple(SCons.Util.flatten(args[1:])) + kw['varlist'] if kw.get('strfunction', _null) is not _null \ and kw.get('cmdstr', _null) is not _null: raise SCons.Errors.UserError( 'Cannot have both strfunction and cmdstr args to Action()')
[ "This converts any arguments after the action argument into\n their equivalent keywords and adds them to the kw argument.\n " ]
Please provide a description of the function:def _do_create_action(act, kw): if isinstance(act, ActionBase): return act if is_String(act): var=SCons.Util.get_environment_var(act) if var: # This looks like a string that is purely an Environment # variable reference, like "$FOO" or "${FOO}". We do # something special here...we lazily evaluate the contents # of that Environment variable, so a user could put something # like a function or a CommandGenerator in that variable # instead of a string. return LazyAction(var, kw) commands = str(act).split('\n') if len(commands) == 1: return CommandAction(commands[0], **kw) # The list of string commands may include a LazyAction, so we # reprocess them via _do_create_list_action. return _do_create_list_action(commands, kw) if is_List(act): return CommandAction(act, **kw) if callable(act): try: gen = kw['generator'] del kw['generator'] except KeyError: gen = 0 if gen: action_type = CommandGeneratorAction else: action_type = FunctionAction return action_type(act, kw) # Catch a common error case with a nice message: if isinstance(act, int) or isinstance(act, float): raise TypeError("Don't know how to create an Action from a number (%s)"%act) # Else fail silently (???) return None
[ "This is the actual \"implementation\" for the\n Action factory method, below. This handles the\n fact that passing lists to Action() itself has\n different semantics than passing lists as elements\n of lists.\n\n The former will create a ListAction, the latter\n will create a CommandAction by converting the inner\n list elements to strings." ]
Please provide a description of the function:def _do_create_list_action(act, kw): acts = [] for a in act: aa = _do_create_action(a, kw) if aa is not None: acts.append(aa) if not acts: return ListAction([]) elif len(acts) == 1: return acts[0] else: return ListAction(acts)
[ "A factory for list actions. Convert the input list into Actions\n and then wrap them in a ListAction." ]
Please provide a description of the function:def Action(act, *args, **kw): # Really simple: the _do_create_* routines do the heavy lifting. _do_create_keywords(args, kw) if is_List(act): return _do_create_list_action(act, kw) return _do_create_action(act, kw)
[ "A factory for action objects." ]
Please provide a description of the function:def _string_from_cmd_list(cmd_list): cl = [] for arg in map(str, cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) return ' '.join(cl)
[ "Takes a list of command line arguments and returns a pretty\n representation for printing." ]
Please provide a description of the function:def get_default_ENV(env): global default_ENV try: return env['ENV'] except KeyError: if not default_ENV: import SCons.Environment # This is a hideously expensive way to get a default shell # environment. What it really should do is run the platform # setup to get the default ENV. Fortunately, it's incredibly # rare for an Environment not to have a shell environment, so # we're not going to worry about it overmuch. default_ENV = SCons.Environment.Environment()['ENV'] return default_ENV
[ "\n A fiddlin' little function that has an 'import SCons.Environment' which\n can't be moved to the top level without creating an import loop. Since\n this import creates a local variable named 'SCons', it blocks access to\n the global variable, so we move it here to prevent complaints about local\n variables being used uninitialized.\n " ]
Please provide a description of the function:def _subproc(scons_env, cmd, error = 'ignore', **kw): # allow std{in,out,err} to be "'devnull'" io = kw.get('stdin') if is_String(io) and io == 'devnull': kw['stdin'] = open(os.devnull) io = kw.get('stdout') if is_String(io) and io == 'devnull': kw['stdout'] = open(os.devnull, 'w') io = kw.get('stderr') if is_String(io) and io == 'devnull': kw['stderr'] = open(os.devnull, 'w') # Figure out what shell environment to use ENV = kw.get('env', None) if ENV is None: ENV = get_default_ENV(scons_env) # Ensure that the ENV values are all strings: new_env = {} for key, value in ENV.items(): if is_List(value): # If the value is a list, then we assume it is a path list, # because that's a pretty common list-like value to stick # in an environment variable: value = SCons.Util.flatten_sequence(value) new_env[key] = os.pathsep.join(map(str, value)) else: # It's either a string or something else. If it's a string, # we still want to call str() because it might be a *Unicode* # string, which makes subprocess.Popen() gag. If it isn't a # string or a list, then we just coerce it to a string, which # is the proper way to handle Dir and File instances and will # produce something reasonable for just about everything else: new_env[key] = str(value) kw['env'] = new_env try: return subprocess.Popen(cmd, **kw) except EnvironmentError as e: if error == 'raise': raise # return a dummy Popen instance that only returns error class dummyPopen(object): def __init__(self, e): self.exception = e def communicate(self, input=None): return ('', '') def wait(self): return -self.exception.errno stdin = None class f(object): def read(self): return '' def readline(self): return '' def __iter__(self): return iter(()) stdout = stderr = f() return dummyPopen(e)
[ "Do common setup for a subprocess.Popen() call\n\n This function is still in draft mode. We're going to need something like\n it in the long run as more and more places use subprocess, but I'm sure\n it'll have to be tweaked to get the full desired functionality.\n one special arg (so far?), 'error', to tell what to do with exceptions.\n " ]
Please provide a description of the function:def print_cmd_line(self, s, target, source, env): try: sys.stdout.write(s + u"\n") except UnicodeDecodeError: sys.stdout.write(s + "\n")
[ "\n In python 3, and in some of our tests, sys.stdout is\n a String io object, and it takes unicode strings only\n In other cases it's a regular Python 2.x file object\n which takes strings (bytes), and if you pass those a\n unicode object they try to decode with 'ascii' codec\n which fails if the cmd line has any hi-bit-set chars.\n This code assumes s is a regular string, but should\n work if it's unicode too.\n " ]
Please provide a description of the function:def execute(self, target, source, env, executor=None): escape_list = SCons.Subst.escape_list flatten_sequence = SCons.Util.flatten_sequence try: shell = env['SHELL'] except KeyError: raise SCons.Errors.UserError('Missing SHELL construction variable.') try: spawn = env['SPAWN'] except KeyError: raise SCons.Errors.UserError('Missing SPAWN construction variable.') else: if is_String(spawn): spawn = env.subst(spawn, raw=1, conv=lambda x: x) escape = env.get('ESCAPE', lambda x: x) ENV = get_default_ENV(env) # Ensure that the ENV values are all strings: for key, value in ENV.items(): if not is_String(value): if is_List(value): # If the value is a list, then we assume it is a # path list, because that's a pretty common list-like # value to stick in an environment variable: value = flatten_sequence(value) ENV[key] = os.pathsep.join(map(str, value)) else: # If it isn't a string or a list, then we just coerce # it to a string, which is the proper way to handle # Dir and File instances and will produce something # reasonable for just about everything else: ENV[key] = str(value) if executor: target = executor.get_all_targets() source = executor.get_all_sources() cmd_list, ignore, silent = self.process(target, list(map(rfile, source)), env, executor) # Use len() to filter out any "command" that's zero-length. for cmd_line in filter(len, cmd_list): # Escape the command line for the interpreter we are using. cmd_line = escape_list(cmd_line, escape) result = spawn(shell, escape, cmd_line[0], cmd_line, ENV) if not ignore and result: msg = "Error %s" % result return SCons.Errors.BuildError(errstr=msg, status=result, action=self, command=cmd_line) return 0
[ "Execute a command action.\n\n This will handle lists of commands as well as individual commands,\n because construction variable substitution may turn a single\n \"command\" into a list. This means that this class can actually\n handle lists of commands, even though that's not how we use it\n externally.\n " ]
Please provide a description of the function:def get_presig(self, target, source, env, executor=None): from SCons.Subst import SUBST_SIG cmd = self.cmd_list if is_List(cmd): cmd = ' '.join(map(str, cmd)) else: cmd = str(cmd) if executor: return env.subst_target_source(cmd, SUBST_SIG, executor=executor) else: return env.subst_target_source(cmd, SUBST_SIG, target, source)
[ "Return the signature contents of this action's command line.\n\n This strips $(-$) and everything in between the string,\n since those parts don't affect signatures.\n " ]
Please provide a description of the function:def get_presig(self, target, source, env, executor=None): return self._generate(target, source, env, 1, executor).get_presig(target, source, env)
[ "Return the signature contents of this action's command line.\n\n This strips $(-$) and everything in between the string,\n since those parts don't affect signatures.\n " ]
Please provide a description of the function:def get_presig(self, target, source, env): try: return self.gc(target, source, env) except AttributeError: return self.funccontents
[ "Return the signature contents of this callable action." ]
Please provide a description of the function:def get_presig(self, target, source, env): return b"".join([bytes(x.get_contents(target, source, env)) for x in self.list])
[ "Return the signature contents of this action list.\n\n Simple concatenation of the signatures of the elements.\n " ]
Please provide a description of the function:def generate(env): SCons.Tool.createStaticLibBuilder(env) if env.Detect('CC'): env['AR'] = 'CC' env['ARFLAGS'] = SCons.Util.CLVar('-ar') env['ARCOM'] = '$AR $ARFLAGS -o $TARGET $SOURCES' else: env['AR'] = 'ar' env['ARFLAGS'] = SCons.Util.CLVar('r') env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES' env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = '$SHLINK $SHLINKFLAGS -o $TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a'
[ "Add Builders and construction variables for ar to an Environment." ]
Please provide a description of the function:async def _notify_update(self, name, change_type, change_info=None, directed_client=None): for monitor in self._monitors: try: result = monitor(name, change_type, change_info, directed_client=directed_client) if inspect.isawaitable(result): await result except Exception: # We can't allow any exceptions in a monitor routine to break the server. self._logger.warning("Error calling monitor with update %s", name, exc_info=True)
[ "Notify updates on a service to anyone who cares." ]
Please provide a description of the function:async def update_state(self, short_name, state): if short_name not in self.services: raise ArgumentError("Service name is unknown", short_name=short_name) if state not in states.KNOWN_STATES: raise ArgumentError("Invalid service state", state=state) serv = self.services[short_name]['state'] if serv.state == state: return update = {} update['old_status'] = serv.state update['new_status'] = state update['new_status_string'] = states.KNOWN_STATES[state] serv.state = state await self._notify_update(short_name, 'state_change', update)
[ "Set the current state of a service.\n\n If the state is unchanged from a previous attempt, this routine does\n nothing.\n\n Args:\n short_name (string): The short name of the service\n state (int): The new stae of the service\n " ]
Please provide a description of the function:def add_service(self, name, long_name, preregistered=False, notify=True): if name in self.services: raise ArgumentError("Could not add service because the long_name is taken", long_name=long_name) serv_state = states.ServiceState(name, long_name, preregistered) service = { 'state': serv_state, 'heartbeat_threshold': 600 } self.services[name] = service if notify: return self._notify_update(name, 'new_service', self.service_info(name)) return None
[ "Add a service to the list of tracked services.\n\n Args:\n name (string): A unique short service name for the service\n long_name (string): A longer, user friendly name for the service\n preregistered (bool): Whether this service is an expected preregistered\n service.\n notify (bool): Send notifications about this service to all clients\n\n Returns:\n awaitable: If notify is True, an awaitable for the notifications.\n\n Otherwise None.\n " ]
Please provide a description of the function:def service_info(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) info = {} info['short_name'] = short_name info['long_name'] = self.services[short_name]['state'].long_name info['preregistered'] = self.services[short_name]['state'].preregistered return info
[ "Get static information about a service.\n\n Args:\n short_name (string): The short name of the service to query\n\n Returns:\n dict: A dictionary with the long_name and preregistered info\n on this service.\n " ]
Please provide a description of the function:def service_messages(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return list(self.services[short_name]['state'].messages)
[ "Get the messages stored for a service.\n\n Args:\n short_name (string): The short name of the service to get messages for\n\n Returns:\n list(ServiceMessage): A list of the ServiceMessages stored for this service\n " ]
Please provide a description of the function:def service_headline(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) return self.services[short_name]['state'].headline
[ "Get the headline stored for a service.\n\n Args:\n short_name (string): The short name of the service to get messages for\n\n Returns:\n ServiceMessage: the headline or None if there is no headline\n " ]
Please provide a description of the function:def service_status(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) info = {} service = self.services[short_name]['state'] info['heartbeat_age'] = monotonic() - service.last_heartbeat info['numeric_status'] = service.state info['string_status'] = service.string_state return info
[ "Get the current status of a service.\n\n Returns information about the service such as the length since the last\n heartbeat, any status messages that have been posted about the service\n and whether the heartbeat should be considered out of the ordinary.\n\n Args:\n short_name (string): The short name of the service to query\n\n Returns:\n dict: A dictionary with the status of the service\n " ]
Please provide a description of the function:async def send_message(self, name, level, message): if name not in self.services: raise ArgumentError("Unknown service name", short_name=name) msg = self.services[name]['state'].post_message(level, message) await self._notify_update(name, 'new_message', msg.to_dict())
[ "Post a message for a service.\n\n Args:\n name (string): The short name of the service to query\n level (int): The level of the message (info, warning, error)\n message (string): The message contents\n " ]
Please provide a description of the function:async def set_headline(self, name, level, message): if name not in self.services: raise ArgumentError("Unknown service name", short_name=name) self.services[name]['state'].set_headline(level, message) headline = self.services[name]['state'].headline.to_dict() await self._notify_update(name, 'new_headline', headline)
[ "Set the sticky headline for a service.\n\n Args:\n name (string): The short name of the service to query\n level (int): The level of the message (info, warning, error)\n message (string): The message contents\n " ]
Please provide a description of the function:async def send_heartbeat(self, short_name): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) self.services[short_name]['state'].heartbeat() await self._notify_update(short_name, 'heartbeat')
[ "Post a heartbeat for a service.\n\n Args:\n short_name (string): The short name of the service to query\n " ]
Please provide a description of the function:def set_agent(self, short_name, client_id): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) self.agents[short_name] = client_id
[ "Register a client id that handlers commands for a service.\n\n Args:\n short_name (str): The name of the service to set an agent\n for.\n client_id (str): A globally unique id for the client that\n should receive commands for this service.\n " ]
Please provide a description of the function:def clear_agent(self, short_name, client_id): if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) if short_name not in self.agents: raise ArgumentError("No agent registered for service", short_name=short_name) if client_id != self.agents[short_name]: raise ArgumentError("Client was not registered for service", short_name=short_name, client_id=client_id, current_client=self.agents[short_name]) del self.agents[short_name]
[ "Remove a client id from being the command handler for a service.\n\n Args:\n short_name (str): The name of the service to set an agent\n for.\n client_id (str): A globally unique id for the client that\n should no longer receive commands for this service.\n " ]
Please provide a description of the function:async def send_rpc_command(self, short_name, rpc_id, payload, sender_client, timeout=1.0): rpc_tag = str(uuid.uuid4()) self.rpc_results.declare(rpc_tag) if short_name in self.services and short_name in self.agents: agent_tag = self.agents[short_name] rpc_message = { 'rpc_id': rpc_id, 'payload': payload, 'response_uuid': rpc_tag } self.in_flight_rpcs[rpc_tag] = InFlightRPC(sender_client, short_name, monotonic(), timeout) await self._notify_update(short_name, 'rpc_command', rpc_message, directed_client=agent_tag) else: response = dict(result='service_not_found', response=b'') self.rpc_results.set(rpc_tag, response) return rpc_tag
[ "Send an RPC to a service using its registered agent.\n\n Args:\n short_name (str): The name of the service we would like to send\n and RPC to\n rpc_id (int): The rpc id that we would like to call\n payload (bytes): The raw bytes that we would like to send as an\n argument\n sender_client (str): The uuid of the sending client\n timeout (float): The maximum number of seconds before we signal a timeout\n of the RPC\n\n Returns:\n str: A unique id that can used to identify the notified response of this\n RPC.\n " ]
Please provide a description of the function:def send_rpc_response(self, rpc_tag, result, response): if rpc_tag not in self.in_flight_rpcs: raise ArgumentError("In flight RPC could not be found, it may have timed out", rpc_tag=rpc_tag) del self.in_flight_rpcs[rpc_tag] response_message = { 'response': response, 'result': result } try: self.rpc_results.set(rpc_tag, response_message) except KeyError: self._logger.warning("RPC response came but no one was waiting: response=%s", response)
[ "Send a response to an RPC.\n\n Args:\n rpc_tag (str): The exact string given in a previous call to send_rpc_command\n result (str): The result of the operation. The possible values of response are:\n service_not_found, rpc_not_found, timeout, success, invalid_response,\n invalid_arguments, execution_exception\n response (bytes): The raw bytes that we should send back as a response.\n " ]
Please provide a description of the function:def periodic_service_rpcs(self): to_remove = [] now = monotonic() for rpc_tag, rpc in self.in_flight_rpcs.items(): expiry = rpc.sent_timestamp + rpc.timeout if now > expiry: to_remove.append(rpc_tag) for tag in to_remove: del self.in_flight_rpcs[tag]
[ "Check if any RPC has expired and remove it from the in flight list.\n\n This function should be called periodically to expire any RPCs that never complete.\n " ]
Please provide a description of the function:def PackageVariable(key, help, default, searchfunc=None): # NB: searchfunc is currently undocumented and unsupported help = '\n '.join( (help, '( yes | no | /path/to/%s )' % key)) return (key, help, default, lambda k, v, e: _validator(k,v,e,searchfunc), _converter)
[ "\n The input parameters describe a 'package list' option, thus they\n are returned with the correct converter and validator appended. The\n result is usable for input to opts.Add() .\n\n A 'package list' option may either be 'all', 'none' or a list of\n package names (separated by space).\n " ]
Please provide a description of the function:def settings_directory(): system = platform.system() basedir = None if system == 'Windows': if 'APPDATA' in os.environ: basedir = os.environ['APPDATA'] # If we're not on Windows assume we're on some # kind of posix system or Mac, where the appropriate place would be # ~/.config if basedir is None: basedir = os.path.expanduser('~') basedir = os.path.join(basedir, '.config') settings_dir = os.path.abspath(os.path.join(basedir, 'IOTile-Core')) return settings_dir
[ "Find a per user settings directory that is appropriate for each\n type of system that we are installed on.\n " ]
Please provide a description of the function:def generate(env): global GhostscriptAction # The following try-except block enables us to use the Tool # in standalone mode (without the accompanying pdf.py), # whenever we need an explicit call of gs via the Gs() # Builder ... try: if GhostscriptAction is None: GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR') from SCons.Tool import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.ps', GhostscriptAction) except ImportError as e: pass gsbuilder = SCons.Builder.Builder(action = SCons.Action.Action('$GSCOM', '$GSCOMSTR')) env['BUILDERS']['Gs'] = gsbuilder env['GS'] = gs env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite') env['GSCOM'] = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES'
[ "Add Builders and construction variables for Ghostscript to an\n Environment." ]
Please provide a description of the function:def resource_path(relative_path=None, expect=None): if expect not in (None, 'file', 'folder'): raise ArgumentError("Invalid expect parameter, must be None, 'file' or 'folder'", expect=expect) this_dir = os.path.dirname(__file__) _resource_path = os.path.join(this_dir, '..', 'config') if relative_path is not None: path = os.path.normpath(relative_path) _resource_path = os.path.join(_resource_path, path) if expect == 'file' and not os.path.isfile(_resource_path): raise DataError("Expected resource %s to be a file and it wasn't" % _resource_path) elif expect == 'folder' and not os.path.isdir(_resource_path): raise DataError("Expected resource %s to be a folder and it wasn't" % _resource_path) return os.path.abspath(_resource_path)
[ "Return the absolute path to a resource in iotile-build.\n\n This method finds the path to the `config` folder inside\n iotile-build, appends `relative_path` to it and then\n checks to make sure the desired file or directory exists.\n\n You can specify expect=(None, 'file', or 'folder') for\n what you expect to find at the given path.\n\n Args:\n relative_path (str): The relative_path from the config\n folder to the resource in question. This path can\n be specified using / characters on all operating\n systems since it will be normalized before usage.\n If None is passed, the based config folder will\n be returned.\n expect (str): What the path should resolve to, which is\n checked before returning, raising a DataError if\n the check fails. You can pass None for no checking,\n file for checking `os.path.isfile`, or folder for\n checking `os.path.isdir`. Default: None\n\n Returns:\n str: The normalized absolute path to the resource.\n " ]
Please provide a description of the function:def unpack(fmt, arg): if isinstance(arg, bytearray) and not (sys.version_info >= (2, 7, 5)): return struct.unpack(fmt, str(arg)) return struct.unpack(fmt, arg)
[ "A shim around struct.unpack to allow it to work on python 2.7.3." ]
Please provide a description of the function:async def initialize(self, timeout=2.0): if self.initialized.is_set(): raise InternalError("initialize called when already initialized") self._emulator.add_task(8, self._reset_vector()) await asyncio.wait_for(self.initialized.wait(), timeout=timeout)
[ "Launch any background tasks associated with this subsystem.\n\n This method will synchronously await self.initialized() which makes\n sure that the background tasks start up correctly.\n " ]
Please provide a description of the function:def _check_registry_type(folder=None): folder = _registry_folder(folder) default_file = os.path.join(folder, 'registry_type.txt') try: with open(default_file, "r") as infile: data = infile.read() data = data.strip() ComponentRegistry.SetBackingStore(data) except IOError: pass
[ "Check if the user has placed a registry_type.txt file to choose the registry type\n\n If a default registry type file is found, the DefaultBackingType and DefaultBackingFile\n class parameters in ComponentRegistry are updated accordingly.\n\n Args:\n folder (string): The folder that we should check for a default registry type\n " ]
Please provide a description of the function:def _ensure_package_loaded(path, component): logger = logging.getLogger(__name__) packages = component.find_products('support_package') if len(packages) == 0: return None elif len(packages) > 1: raise ExternalError("Component had multiple products declared as 'support_package", products=packages) if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths path, _, _ = path.rpartition(":") package_base = packages[0] relative_path = os.path.normpath(os.path.relpath(path, start=package_base)) if relative_path.startswith('..'): raise ExternalError("Component had python product output of support_package", package=package_base, product=path, relative_path=relative_path) if not relative_path.endswith('.py'): raise ExternalError("Python product did not end with .py", path=path) relative_path = relative_path[:-3] if os.pathsep in relative_path: raise ExternalError("Python support wheels with multiple subpackages not yet supported", relative_path=relative_path) support_distro = component.support_distribution if support_distro not in sys.modules: logger.debug("Creating dynamic support wheel package: %s", support_distro) file, path, desc = imp.find_module(os.path.basename(package_base), [os.path.dirname(package_base)]) imp.load_module(support_distro, file, path, desc) return "{}.{}".format(support_distro, relative_path)
[ "Ensure that the given module is loaded as a submodule.\n\n Returns:\n str: The name that the module should be imported as.\n " ]
Please provide a description of the function:def _try_load_module(path, import_name=None): logger = logging.getLogger(__name__) obj_name = None if len(path) > 2 and ':' in path[2:]: # Don't flag windows C: type paths path, _, obj_name = path.rpartition(":") folder, basename = os.path.split(path) if folder == '': folder = './' if basename == '' or not os.path.exists(path): raise ArgumentError("Could not find python module to load extension", path=path) basename, ext = os.path.splitext(basename) if ext not in (".py", ".pyc", ""): raise ArgumentError("Attempted to load module is not a python package or module (.py or .pyc)", path=path) if import_name is None: import_name = basename else: logger.debug("Importing module as subpackage: %s", import_name) try: fileobj = None fileobj, pathname, description = imp.find_module(basename, [folder]) # Don't load modules twice if basename in sys.modules: mod = sys.modules[basename] else: mod = imp.load_module(import_name, fileobj, pathname, description) if obj_name is not None: if obj_name not in mod.__dict__: raise ArgumentError("Cannot find named object '%s' inside module '%s'" % (obj_name, basename), path=path) mod = mod.__dict__[obj_name] return basename, mod finally: if fileobj is not None: fileobj.close()
[ "Try to programmatically load a python module by path.\n\n Path should point to a python file (optionally without the .py) at the\n end. If it ends in a :<name> then name must point to an object defined in\n the module, which is returned instead of the module itself.\n\n Args:\n path (str): The path of the module to load\n import_name (str): The explicity name that the module should be given.\n If not specified, this defaults to being the basename() of\n path. However, if the module is inside of a support package,\n you should pass the correct name so that relative imports\n proceed correctly.\n\n Returns:\n str, object: The basename of the module loaded and the requested object.\n " ]
Please provide a description of the function:def frozen(self): frozen_path = os.path.join(_registry_folder(), 'frozen_extensions.json') return os.path.isfile(frozen_path)
[ "Return whether we have a cached list of all installed entry_points." ]
Please provide a description of the function:def kvstore(self): if self._kvstore is None: self._kvstore = self.BackingType(self.BackingFileName, respect_venv=True) return self._kvstore
[ "Lazily load the underlying key-value store backing this registry." ]
Please provide a description of the function:def plugins(self): if self._plugins is None: self._plugins = {} for _, plugin in self.load_extensions('iotile.plugin'): links = plugin() for name, value in links: self._plugins[name] = value return self._plugins
[ "Lazily load iotile plugins only on demand.\n\n This is a slow operation on computers with a slow FS and is rarely\n accessed information, so only compute it when it is actually asked\n for.\n " ]
Please provide a description of the function:def load_extensions(self, group, name_filter=None, comp_filter=None, class_filter=None, product_name=None, unique=False): found_extensions = [] if product_name is not None: for comp in self.iter_components(): if comp_filter is not None and comp.name != comp_filter: continue products = comp.find_products(product_name) for product in products: try: entries = self.load_extension(product, name_filter=name_filter, class_filter=class_filter, component=comp) if len(entries) == 0 and name_filter is None: # Don't warn if we're filtering by name since most extensions won't match self._logger.warn("Found no valid extensions in product %s of component %s", product, comp.path) continue found_extensions.extend(entries) except: # pylint:disable=bare-except;We don't want a broken extension to take down the whole system self._logger.exception("Unable to load extension %s from local component %s at path %s", product_name, comp, product) for entry in self._iter_entrypoint_group(group): name = entry.name if name_filter is not None and name != name_filter: continue try: ext = entry.load() except: # pylint:disable=bare-except; self._logger.warn("Unable to load %s from %s", entry.name, entry.distro, exc_info=True) continue found_extensions.extend((name, x) for x in self._filter_subclasses(ext, class_filter)) for (name, ext) in self._registered_extensions.get(group, []): if name_filter is not None and name != name_filter: continue found_extensions.extend((name, x) for x in self._filter_subclasses(ext, class_filter)) found_extensions = [(name, x) for name, x in found_extensions if self._filter_nonextensions(x)] if unique is True: if len(found_extensions) > 1: raise ArgumentError("Extension %s should have had exactly one instance of class %s, found %d" % (group, class_filter.__name__, len(found_extensions)), classes=found_extensions) elif len(found_extensions) == 0: raise ArgumentError("Extension %s had no instances of class %s" % (group, class_filter.__name__)) return found_extensions[0] return found_extensions
[ "Dynamically load and return extension objects of a given type.\n\n This is the centralized way for all parts of CoreTools to allow plugin\n behavior. Whenever a plugin is needed, this method should be called\n to load it. Examples of plugins are proxy modules, emulated tiles,\n iotile-build autobuilders, etc.\n\n Each kind of plugin will typically be a subclass of a certain base class\n and can be provided one of three ways:\n\n 1. It can be registered as an entry point in a pip installed package.\n The entry point group must map the group passed to load_extensions.\n 2. It can be listed as a product of an IOTile component that is stored\n in this ComponentRegistry. The relevant python file inside the\n component will be imported dynamically as needed.\n 3. It can be programmatically registered by calling ``register_extension()``\n on this class with a string name and an object. This is equivalent to\n exposing that same object as an entry point with the given name.\n\n There is special behavior of this function if class_filter is passed\n and the object returned by one of the above three methods is a python\n module. The module will be search for object definitions that match\n the defined class.\n\n The order of the returned objects list is only partially defined.\n Locally installed components are searched before pip installed\n packages with entry points. The order of results within each group is\n not specified.\n\n Args:\n group (str): The extension type that you wish to enumerate. This\n will be used as the entry_point group for searching pip\n installed packages.\n name_filter (str): Only return objects with the given name\n comp_filter (str): When searching through installed components\n (not entry_points), only search through components with the\n given name.\n class_filter (type or tuple of types): An object that will be passed to\n instanceof() to verify that all extension objects have the correct\n types. If not passed, no checking will be done.\n product_name (str): If this extension can be provided by a registered\n local component, the name of the product that should be loaded.\n unique (bool): If True (default is False), there must be exactly one object\n found inside this extension that matches all of the other criteria.\n\n Returns:\n list of (str, object): A list of the found and loaded extension objects.\n\n The string returned with each extension is the name of the\n entry_point or the base name of the file in the component or the\n value provided by the call to register_extension depending on how\n the extension was found.\n\n If unique is True, then the list only contains a single entry and that\n entry will be directly returned.\n " ]
Please provide a description of the function:def register_extension(self, group, name, extension): if isinstance(extension, str): name, extension = self.load_extension(extension)[0] if group not in self._registered_extensions: self._registered_extensions[group] = [] self._registered_extensions[group].append((name, extension))
[ "Register an extension.\n\n Args:\n group (str): The type of the extension\n name (str): A name for the extension\n extension (str or class): If this is a string, then it will be\n interpreted as a path to import and load. Otherwise it\n will be treated as the extension object itself.\n " ]
Please provide a description of the function:def clear_extensions(self, group=None): if group is None: ComponentRegistry._registered_extensions = {} return if group in self._registered_extensions: self._registered_extensions[group] = []
[ "Clear all previously registered extensions." ]
Please provide a description of the function:def freeze_extensions(self): output_path = os.path.join(_registry_folder(), 'frozen_extensions.json') with open(output_path, "w") as outfile: json.dump(self._dump_extensions(), outfile)
[ "Freeze the set of extensions into a single file.\n\n Freezing extensions can speed up the extension loading process on\n machines with slow file systems since it requires only a single file\n to store all of the extensions.\n\n Calling this method will save a file into the current virtual\n environment that stores a list of all currently found extensions that\n have been installed as entry_points. Future calls to\n `load_extensions` will only search the one single file containing\n frozen extensions rather than enumerating all installed distributions.\n " ]
Please provide a description of the function:def unfreeze_extensions(self): output_path = os.path.join(_registry_folder(), 'frozen_extensions.json') if not os.path.isfile(output_path): raise ExternalError("There is no frozen extension list") os.remove(output_path) ComponentRegistry._frozen_extensions = None
[ "Remove a previously frozen list of extensions." ]
Please provide a description of the function:def load_extension(self, path, name_filter=None, class_filter=None, unique=False, component=None): import_name = None if component is not None: import_name = _ensure_package_loaded(path, component) name, ext = _try_load_module(path, import_name=import_name) if name_filter is not None and name != name_filter: return [] found = [(name, x) for x in self._filter_subclasses(ext, class_filter)] found = [(name, x) for name, x in found if self._filter_nonextensions(x)] if not unique: return found if len(found) > 1: raise ArgumentError("Extension %s should have had exactly one instance of class %s, found %d" % (path, class_filter.__name__, len(found)), classes=found) elif len(found) == 0: raise ArgumentError("Extension %s had no instances of class %s" % (path, class_filter.__name__)) return found[0]
[ "Load a single python module extension.\n\n This function is similar to using the imp module directly to load a\n module and potentially inspecting the objects it declares to filter\n them by class.\n\n Args:\n path (str): The path to the python file to load\n name_filter (str): If passed, the basename of the module must match\n name or nothing is returned.\n class_filter (type): If passed, only instance of this class are returned.\n unique (bool): If True (default is False), there must be exactly one object\n found inside this extension that matches all of the other criteria.\n component (IOTile): The component that this extension comes from if it is\n loaded from an installed component. This is used to properly import\n the extension as a submodule of the component's support package.\n\n Returns:\n list of (name, type): A list of the objects found at the extension path.\n\n If unique is True, then the list only contains a single entry and that\n entry will be directly returned.\n " ]
Please provide a description of the function:def _filter_nonextensions(cls, obj): # Not all objects have __dict__ attributes. For example, tuples don't. # and tuples are used in iotile.build for some entry points. if hasattr(obj, '__dict__') and obj.__dict__.get('__NO_EXTENSION__', False) is True: return False return True
[ "Remove all classes marked as not extensions.\n\n This allows us to have a deeper hierarchy of classes than just\n one base class that is filtered by _filter_subclasses. Any\n class can define a class propery named:\n\n __NO_EXTENSION__ = True\n\n That class will never be returned as an extension. This is useful\n for masking out base classes for extensions that are declared in\n CoreTools and would be present in module imports but should not\n create a second entry point.\n " ]
Please provide a description of the function:def SetBackingStore(cls, backing): if backing not in ['json', 'sqlite', 'memory']: raise ArgumentError("Unknown backing store type that is not json or sqlite", backing=backing) if backing == 'json': cls.BackingType = JSONKVStore cls.BackingFileName = 'component_registry.json' elif backing == 'memory': cls.BackingType = InMemoryKVStore cls.BackingFileName = None else: cls.BackingType = SQLiteKVStore cls.BackingFileName = 'component_registry.db'
[ "Set the global backing type used by the ComponentRegistry from this point forward\n\n This function must be called before any operations that use the registry are initiated\n otherwise they will work from different registries that will likely contain different data\n " ]
Please provide a description of the function:def add_component(self, component, temporary=False): tile = IOTile(component) value = os.path.normpath(os.path.abspath(component)) if temporary is True: self._component_overlays[tile.name] = value else: self.kvstore.set(tile.name, value)
[ "Register a component with ComponentRegistry.\n\n Component must be a buildable object with a module_settings.json file\n that describes its name and the domain that it is part of. By\n default, this component is saved in the permanent registry associated\n with this environment and will remain registered for future CoreTools\n invocations.\n\n If you only want this component to be temporarily registered during\n this program's session, you can pass temporary=True and the component\n will be stored in RAM only, not persisted to the underlying key-value\n store.\n\n Args:\n component (str): The path to a component that should be registered.\n temporary (bool): Optional flag to only temporarily register the\n component for the duration of this program invocation.\n " ]
Please provide a description of the function:def list_plugins(self): vals = self.plugins.items() return {x: y for x, y in vals}
[ "\n List all of the plugins that have been registerd for the iotile program on this computer\n " ]
Please provide a description of the function:def clear_components(self): ComponentRegistry._component_overlays = {} for key in self.list_components(): self.remove_component(key)
[ "Clear all of the registered components\n " ]
Please provide a description of the function:def list_components(self): overlays = list(self._component_overlays) items = self.kvstore.get_all() return overlays + [x[0] for x in items if not x[0].startswith('config:')]
[ "List all of the registered component names.\n\n This list will include all of the permanently stored components as\n well as any temporary components that were added with a temporary=True\n flag in this session.\n\n Returns:\n list of str: The list of component names.\n\n Any of these names can be passed to get_component as is to get the\n corresponding IOTile object.\n " ]
Please provide a description of the function:def iter_components(self): names = self.list_components() for name in names: yield self.get_component(name)
[ "Iterate over all defined components yielding IOTile objects." ]
Please provide a description of the function:def list_config(self): items = self.kvstore.get_all() return ["{0}={1}".format(x[0][len('config:'):], x[1]) for x in items if x[0].startswith('config:')]
[ "List all of the configuration variables\n " ]
Please provide a description of the function:def set_config(self, key, value): keyname = "config:" + key self.kvstore.set(keyname, value)
[ "Set a persistent config key to a value, stored in the registry\n\n Args:\n key (string): The key name\n value (string): The key value\n " ]
Please provide a description of the function:def get_config(self, key, default=MISSING): keyname = "config:" + key try: return self.kvstore.get(keyname) except KeyError: if default is MISSING: raise ArgumentError("No config value found for key", key=key) return default
[ "Get the value of a persistent config key from the registry\n\n If no default is specified and the key is not found ArgumentError is raised.\n\n Args:\n key (string): The key name to fetch\n default (string): an optional value to be returned if key cannot be found\n\n Returns:\n string: the key's value\n " ]
Please provide a description of the function:def execute_action_list(obj, target, kw): env = obj.get_build_env() kw = obj.get_kw(kw) status = 0 for act in obj.get_action_list(): args = ([], [], env) status = act(*args, **kw) if isinstance(status, SCons.Errors.BuildError): status.executor = obj raise status elif status: msg = "Error %s" % status raise SCons.Errors.BuildError( errstr=msg, node=obj.batches[0].targets, executor=obj, action=act) return status
[ "Actually execute the action list." ]
Please provide a description of the function:def get_all_targets(self): result = [] for batch in self.batches: result.extend(batch.targets) return result
[ "Returns all targets for all batches of this Executor." ]
Please provide a description of the function:def get_all_sources(self): result = [] for batch in self.batches: result.extend(batch.sources) return result
[ "Returns all sources for all batches of this Executor." ]