Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def _reset_sig_handler(self): signal.signal(signal.SIGINT, self.old_sigint) signal.signal(signal.SIGTERM, self.old_sigterm) try: signal.signal(signal.SIGHUP, self.old_sighup) except AttributeError: pass
[ "Restore the signal handlers to their previous state (before the\n call to _setup_sig_handler()." ]
Please provide a description of the function:def start(self): while True: task = self.taskmaster.next_task() if task is None: break try: task.prepare() if task.needs_execute(): task.execute() except: if self.interrupted(): try: raise SCons.Errors.BuildError( task.targets[0], errstr=interrupt_msg) except: task.exception_set() else: task.exception_set() # Let the failed() callback function arrange for the # build to stop if that's appropriate. task.failed() else: task.executed() task.postprocess() self.taskmaster.cleanup()
[ "Start the job. This will begin pulling tasks from the taskmaster\n and executing them, and return when there are no more tasks. If a task\n fails to execute (i.e. execute() raises an exception), then the job will\n stop." ]
Please provide a description of the function:def expired(self): if self.timeout is None: return False return monotonic() - self.start_time > self.timeout
[ "Boolean property if this action has expired\n " ]
Please provide a description of the function:def add_connection(self, connection_id, internal_id, context): # Make sure we are not reusing an id that is currently connected to something if self._get_connection_state(connection_id) != self.Disconnected: return if self._get_connection_state(internal_id) != self.Disconnected: return conn_data = { 'state': self.Idle, 'microstate': None, 'connection_id': connection_id, 'internal_id': internal_id, 'context': context } self._connections[connection_id] = conn_data self._int_connections[internal_id] = conn_data
[ "Add an already created connection. Used to register devices connected before starting the device adapter.\n \n Args:\n connection_id (int): The external connection id\n internal_id (string): An internal identifier for the connection\n context (dict): Additional information to associate with this context\n " ]
Please provide a description of the function:def begin_connection(self, connection_id, internal_id, callback, context, timeout): data = { 'callback': callback, 'connection_id': connection_id, 'internal_id': internal_id, 'context': context } action = ConnectionAction('begin_connection', data, timeout=timeout, sync=False) self._actions.put(action)
[ "Asynchronously begin a connection attempt\n\n Args:\n connection_id (int): The external connection id\n internal_id (string): An internal identifier for the connection\n callback (callable): The function to be called when the connection\n attempt finishes\n context (dict): Additional information to associate with this context\n timeout (float): How long to allow this connection attempt to proceed\n without timing it out\n " ]
Please provide a description of the function:def finish_connection(self, conn_or_internal_id, successful, failure_reason=None): data = { 'id': conn_or_internal_id, 'success': successful, 'failure_reason': failure_reason } action = ConnectionAction('finish_connection', data, sync=False) self._actions.put(action)
[ "Finish a connection attempt\n\n Args:\n conn_or_internal_id (string, int): Either an integer connection id or a string\n internal_id\n successful (bool): Whether this connection attempt was successful\n failure_reason (string): If this connection attempt failed, an optional reason\n for the failure.\n " ]
Please provide a description of the function:def _begin_connection_action(self, action): connection_id = action.data['connection_id'] internal_id = action.data['internal_id'] callback = action.data['callback'] # Make sure we are not reusing an id that is currently connected to something if self._get_connection_state(connection_id) != self.Disconnected: callback(connection_id, self.id, False, 'Connection ID is already in use for another connection') return if self._get_connection_state(internal_id) != self.Disconnected: callback(connection_id, self.id, False, 'Internal ID is already in use for another connection') return conn_data = { 'state': self.Connecting, 'microstate': None, 'connection_id': connection_id, 'internal_id': internal_id, 'action': action, 'context': action.data['context'] } self._connections[connection_id] = conn_data self._int_connections[internal_id] = conn_data
[ "Begin a connection attempt\n\n Args:\n action (ConnectionAction): the action object describing what we are\n connecting to\n " ]
Please provide a description of the function:def _force_disconnect_action(self, action): conn_key = action.data['id'] if self._get_connection_state(conn_key) == self.Disconnected: return data = self._get_connection(conn_key) # If there are any operations in progress, cancel them cleanly if data['state'] == self.Connecting: callback = data['action'].data['callback'] callback(data['connection_id'], self.id, False, 'Unexpected disconnection') elif data['state'] == self.Disconnecting: callback = data['action'].data['callback'] callback(data['connection_id'], self.id, True, None) elif data['state'] == self.InProgress: callback = data['action'].data['callback'] if data['microstate'] == 'rpc': callback(False, 'Unexpected disconnection', 0xFF, None) elif data['microstate'] == 'open_interface': callback(False, 'Unexpected disconnection') elif data['microstate'] == 'close_interface': callback(False, 'Unexpected disconnection') connection_id = data['connection_id'] internal_id = data['internal_id'] del self._connections[connection_id] del self._int_connections[internal_id]
[ "Forcibly disconnect a device.\n\n Args:\n action (ConnectionAction): the action object describing what we are\n forcibly disconnecting\n " ]
Please provide a description of the function:def _finish_disconnection_action(self, action): success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.Disconnecting: self._logger.error( "Invalid finish_disconnection action on a connection whose state is not Disconnecting, conn_key={}" .format(str(conn_key)) ) return # Cannot be None since we checked above to make sure it exists data = self._get_connection(conn_key) connection_id = data['connection_id'] internal_id = data['internal_id'] last_action = data['action'] callback = last_action.data['callback'] if success is False: failure_reason = action.data['failure_reason'] if failure_reason is None: failure_reason = "No reason was given" data['state'] = self.Idle data['microstate'] = None del data['action'] callback(connection_id, self.id, False, failure_reason) else: del self._connections[connection_id] del self._int_connections[internal_id] callback(connection_id, self.id, True, None)
[ "Finish a disconnection attempt\n\n There are two possible outcomes:\n - if we were successful at disconnecting, we transition to disconnected\n - if we failed at disconnecting, we transition back to idle\n\n Args:\n action (ConnectionAction): the action object describing what we are\n disconnecting from and what the result of the operation was\n " ]
Please provide a description of the function:def begin_operation(self, conn_or_internal_id, op_name, callback, timeout): data = { 'id': conn_or_internal_id, 'callback': callback, 'operation_name': op_name } action = ConnectionAction('begin_operation', data, timeout=timeout, sync=False) self._actions.put(action)
[ "Begin an operation on a connection\n\n Args:\n conn_or_internal_id (string, int): Either an integer connection id or a string\n internal_id\n op_name (string): The name of the operation that we are starting (stored in\n the connection's microstate)\n callback (callable): Callback to call when this disconnection attempt either\n succeeds or fails\n timeout (float): How long to allow this connection attempt to proceed\n without timing it out (in seconds)\n " ]
Please provide a description of the function:def _begin_operation_action(self, action): conn_key = action.data['id'] callback = action.data['callback'] if self._get_connection_state(conn_key) != self.Idle: callback(conn_key, self.id, False, 'Cannot start operation, connection is not idle') return data = self._get_connection(conn_key) data['state'] = self.InProgress data['microstate'] = action.data['operation_name'] data['action'] = action
[ "Begin an attempted operation.\n\n Args:\n action (ConnectionAction): the action object describing what we are\n operating on\n " ]
Please provide a description of the function:def allow_exception(self, exc_class): name = exc_class.__name__ self._allowed_exceptions[name] = exc_class
[ "Allow raising this class of exceptions from commands.\n\n When a command fails on the server side due to an exception, by\n default it is turned into a string and raised on the client side as an\n ExternalError. The original class name is sent but ignored. If you\n would like to instead raise an instance of the same exception on the\n client side, you can pass the exception class object to this method\n and instances of that exception will be reraised.\n\n The caveat is that the exception must be creatable with a single\n string parameter and it should have a ``msg`` property.\n\n Args:\n exc_class (class): A class object with the exception that\n we should allow to pass from server to client.\n " ]
Please provide a description of the function:async def start(self, name="websocket_client"): self._con = await websockets.connect(self.url) self._connection_task = self._loop.add_task(self._manage_connection(), name=name)
[ "Connect to the websocket server.\n\n This method will spawn a background task in the designated event loop\n that will run until stop() is called. You can control the name of the\n background task for debugging purposes using the name parameter. The\n name is not used in anyway except for debug logging statements.\n\n Args:\n name (str): Optional name for the background task.\n " ]
Please provide a description of the function:async def stop(self): if self._connection_task is None: return try: await self._connection_task.stop() finally: self._con = None self._connection_task = None self._manager.clear()
[ "Stop this websocket client and disconnect from the server.\n\n This method is idempotent and may be called multiple times. If called\n when there is no active connection, it will simply return.\n " ]
Please provide a description of the function:async def send_command(self, command, args, validator, timeout=10.0): if self._con is None: raise ExternalError("No websock connection established") cmd_uuid = str(uuid.uuid4()) msg = dict(type='command', operation=command, uuid=cmd_uuid, payload=args) packed = pack(msg) # Note: register future before sending to avoid race conditions response_future = self._manager.wait_for(type="response", uuid=cmd_uuid, timeout=timeout) await self._con.send(packed) response = await response_future if response.get('success') is False: self._raise_error(command, response) if validator is None: return response.get('payload') return validator.verify(response.get('payload'))
[ "Send a command and synchronously wait for a single response.\n\n Args:\n command (string): The command name\n args (dict): Optional arguments.\n validator (Verifier): A SchemaVerifier to verify the response\n payload.\n timeout (float): The maximum time to wait for a response.\n Defaults to 10 seconds.\n\n Returns:\n dict: The response payload\n\n Raises:\n ExternalError: If the server is not connected or the command\n fails.\n asyncio.TimeoutError: If the command times out.\n ValidationError: If the response payload does not match the\n given validator.\n " ]
Please provide a description of the function:async def _manage_connection(self): try: while True: message = await self._con.recv() try: unpacked = unpack(message) except Exception: # pylint:disable=broad-except;This is a background worker self._logger.exception("Corrupt message received") continue if not VALID_SERVER_MESSAGE.matches(unpacked): self._logger.warning("Dropping invalid message from server: %s", unpacked) continue # Don't block until all callbacks have finished since once of # those callbacks may call self.send_command, which would deadlock # since it couldn't get the response until it had already finished. if not await self._manager.process_message(unpacked, wait=False): self._logger.warning("No handler found for received message, message=%s", unpacked) except asyncio.CancelledError: self._logger.info("Closing connection to server due to stop()") finally: await self._manager.process_message(dict(type='event', name=self.DISCONNECT_EVENT, payload=None)) await self._con.close()
[ "Internal coroutine for managing the client connection." ]
Please provide a description of the function:def register_event(self, name, callback, validator): async def _validate_and_call(message): payload = message.get('payload') try: payload = validator.verify(payload) except ValidationError: self._logger.warning("Dropping invalid payload for event %s, payload=%s", name, payload) return try: result = callback(payload) if inspect.isawaitable(result): await result except: # pylint:disable=bare-except;This is a background logging routine self._logger.error("Error calling callback for event %s, payload=%s", name, payload, exc_info=True) self._manager.every_match(_validate_and_call, type="event", name=name)
[ "Register a callback to receive events.\n\n Every event with the matching name will have its payload validated\n using validator and then will be passed to callback if validation\n succeeds.\n\n Callback must be a normal callback function, coroutines are not\n allowed. If you need to run a coroutine you are free to schedule it\n from your callback.\n\n Args:\n name (str): The name of the event that we are listening\n for\n callback (callable): The function that should be called\n when a message that matches validator is received.\n validator (Verifier): A schema verifier that will\n validate a received message uniquely\n " ]
Please provide a description of the function:def post_command(self, command, args): self._loop.log_coroutine(self.send_command(command, args, Verifier()))
[ "Post a command asynchronously and don't wait for a response.\n\n There is no notification of any error that could happen during\n command execution. A log message will be generated if an error\n occurred. The command's response is discarded.\n\n This method is thread-safe and may be called from inside or ouside\n of the background event loop. If there is no websockets connection,\n no error will be raised (though an error will be logged).\n\n Args:\n command (string): The command name\n args (dict): Optional arguments\n " ]
Please provide a description of the function:def copy_all_a(input_a, *other_inputs, **kwargs): output = [] while input_a.count() > 0: output.append(input_a.pop()) for input_x in other_inputs: input_x.skip_all() return output
[ "Copy all readings in input a into the output.\n\n All other inputs are skipped so that after this function runs there are no\n readings left in any of the input walkers when the function finishes, even\n if it generated no output readings.\n\n Returns:\n list(IOTileReading)\n " ]
Please provide a description of the function:def copy_count_a(input_a, *other_inputs, **kwargs): count = input_a.count() input_a.skip_all(); for input_x in other_inputs: input_x.skip_all() return [IOTileReading(0, 0, count)]
[ "Copy the latest reading from input a into the output.\n\n All other inputs are skipped to that after this function\n runs there are no readings left in any of the input walkers\n even if no output is generated.\n\n Returns:\n list(IOTileReading)\n " ]
Please provide a description of the function:def call_rpc(*inputs, **kwargs): rpc_executor = kwargs['rpc_executor'] output = [] try: value = inputs[1].pop() addr = value.value >> 16 rpc_id = value.value & 0xFFFF reading_value = rpc_executor.rpc(addr, rpc_id) output.append(IOTileReading(0, 0, reading_value)) except (HardwareError, StreamEmptyError): pass for input_x in inputs: input_x.skip_all() return output
[ "Call an RPC based on the encoded value read from input b.\n\n The response of the RPC must be a 4 byte value that is used as\n the output of this call. The encoded RPC must be a 32 bit value\n encoded as \"BBH\":\n B: ignored, should be 0\n B: the address of the tile that we should call\n H: The id of the RPC to call\n\n All other readings are then skipped so that there are no\n readings in any input queue when this function returns\n\n Returns:\n list(IOTileReading)\n " ]
Please provide a description of the function:def trigger_streamer(*inputs, **kwargs): streamer_marker = kwargs['mark_streamer'] try: reading = inputs[1].pop() except StreamEmptyError: return [] finally: for input_x in inputs: input_x.skip_all() try: streamer_marker(reading.value) except ArgumentError: return [] return [IOTileReading(0, 0, 0)]
[ "Trigger a streamer based on the index read from input b.\n\n Returns:\n list(IOTileReading)\n " ]
Please provide a description of the function:def subtract_afromb(*inputs, **kwargs): try: value_a = inputs[0].pop() value_b = inputs[1].pop() return [IOTileReading(0, 0, value_b.value - value_a.value)] except StreamEmptyError: return []
[ "Subtract stream a from stream b.\n\n Returns:\n list(IOTileReading)\n " ]
Please provide a description of the function:def _do_subst(node, subs): contents = node.get_text_contents() if subs: for (k, val) in subs: contents = re.sub(k, val, contents) if 'b' in TEXTFILE_FILE_WRITE_MODE: try: contents = bytearray(contents, 'utf-8') except UnicodeDecodeError: # contents is already utf-8 encoded python 2 str i.e. a byte array contents = bytearray(contents) return contents
[ "\n Fetch the node contents and replace all instances of the keys with\n their values. For example, if subs is\n {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'},\n then all instances of %VERSION% in the file will be replaced with\n 1.2345 and so forth.\n " ]
Please provide a description of the function:def _clean_intenum(obj): if isinstance(obj, dict): for key, value in obj.items(): if isinstance(value, IntEnum): obj[key] = value.value elif isinstance(value, (dict, list)): obj[key] = _clean_intenum(value) elif isinstance(obj, list): for i, value in enumerate(obj): if isinstance(value, IntEnum): obj[i] = value.value elif isinstance(value, (dict, list)): obj[i] = _clean_intenum(value) return obj
[ "Remove all IntEnum classes from a map." ]
Please provide a description of the function:def _track_change(self, name, value, formatter=None): self._emulation_log.track_change(self._emulation_address, name, value, formatter)
[ "Track that a change happened.\n\n This function is only needed for manually recording changes that are\n not captured by changes to properties of this object that are tracked\n automatically. Classes that inherit from `emulation_mixin` should\n use this function to record interesting changes in their internal\n state or events that happen.\n\n The `value` parameter that you pass here should be a native python\n object best representing what the value of the property that changed\n is. When saved to disk, it will be converted to a string using:\n `str(value)`. If you do not like the string that would result from\n such a call, you can pass a custom formatter that will be called as\n `formatter(value)` and must return a string.\n\n Args:\n name (str): The name of the property that changed.\n value (object): The new value of the property.\n formatter (callable): Optional function to convert value to a\n string. This function will only be called if track_changes()\n is enabled and `name` is on the whitelist for properties that\n should be tracked. If `formatter` is not passed or is None,\n it will default to `str`\n " ]
Please provide a description of the function:def save_state(self, out_path): state = self.dump_state() # Remove all IntEnums from state since they cannot be json-serialized on python 2.7 # See https://bitbucket.org/stoneleaf/enum34/issues/17/difference-between-enum34-and-enum-json state = _clean_intenum(state) with open(out_path, "w") as outfile: json.dump(state, outfile, indent=4)
[ "Save the current state of this emulated object to a file.\n\n Args:\n out_path (str): The path to save the dumped state of this emulated\n object.\n " ]
Please provide a description of the function:def load_state(self, in_path): with open(in_path, "r") as infile: state = json.load(infile) self.restore_state(state)
[ "Load the current state of this emulated object from a file.\n\n The file should have been produced by a previous call to save_state.\n\n Args:\n in_path (str): The path to the saved state dump that you wish\n to load.\n " ]
Please provide a description of the function:def load_scenario(self, scenario_name, **kwargs): scenario = self._known_scenarios.get(scenario_name) if scenario is None: raise ArgumentError("Unknown scenario %s" % scenario_name, known_scenarios=list(self._known_scenarios)) scenario(**kwargs)
[ "Load a scenario into the emulated object.\n\n Scenarios are specific states of an an object that can be customized\n with keyword parameters. Typical examples are:\n\n - data logger with full storage\n - device with low battery indication on\n\n Args:\n scenario_name (str): The name of the scenario that we wish to\n load.\n **kwargs: Any arguments that should be passed to configure\n the scenario. These arguments will be passed directly\n to the scenario handler.\n " ]
Please provide a description of the function:def register_scenario(self, scenario_name, handler): if scenario_name in self._known_scenarios: raise ArgumentError("Attempted to add the same scenario name twice", scenario_name=scenario_name, previous_handler=self._known_scenarios[scenario_name]) self._known_scenarios[scenario_name] = handler
[ "Register a scenario handler for this object.\n\n Scenario handlers are callable functions with no positional arguments\n that can be called by name with the load_scenario function and should\n prepare the emulated object into a known state. The purpose of a\n scenario is to make it easy to get a device into a specific state for\n testing purposes that may otherwise be difficult or time consuming to\n prepare on the physical, non-emulated device.\n\n Args:\n scenario_name (str): The name of this scenario that can be passed to\n load_scenario later in order to invoke the scenario.\n handler (callable): A callable function that takes no positional\n arguments and can prepare this object into the given scenario\n state. It may take required or optional keyword arguments that\n may be passed to `load_scenario` if needed.\n " ]
Please provide a description of the function:def generate(env): cc.generate(env) env['CXX'] = 'aCC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS +Z')
[ "Add Builders and construction variables for aCC & cc to an Environment." ]
Please provide a description of the function:def add_pass(self, name, opt_pass, before=None, after=None): if before is None: before = [] if after is None: after = [] self._known_passes[name] = (opt_pass, before, after)
[ "Add an optimization pass to the optimizer.\n\n Optimization passes have a name that allows them\n to be enabled or disabled by name. By default all\n optimization passed are enabled and unordered. You can\n explicitly specify passes by name that this pass must run\n before or after this passs so that they can be properly\n ordered.\n\n Args:\n name (str): The name of the optimization pass to allow for\n enabling/disabling it by name\n opt_pass (OptimizationPass): The optimization pass class itself\n before (list(str)): A list of the passes that this pass should\n run before.\n after (list(str)): A list of the passes that this pass should\n run after.\n " ]
Please provide a description of the function:def _order_pases(self, passes): passes = set(passes) pass_deps = {} for opt in passes: _, before, after = self._known_passes[opt] if opt not in pass_deps: pass_deps[opt] = set() for after_pass in after: pass_deps[opt].add(after_pass) # For passes that we are before, we may need to # preemptively add them to the list early for other in before: if other not in passes: continue if other not in pass_deps: pass_deps[other] = set() pass_deps[other].add(opt) return toposort_flatten(pass_deps)
[ "Topologically sort optimization passes.\n\n This ensures that the resulting passes are run in order\n respecting before/after constraints.\n\n Args:\n passes (iterable): An iterable of pass names that should\n be included in the optimization passes run.\n " ]
Please provide a description of the function:def optimize(self, sensor_graph, model): passes = self._order_pases(self._known_passes.keys()) for opt_name in passes: rerun = True pass_instance = self._known_passes[opt_name][0]() while rerun: rerun = pass_instance.run(sensor_graph, model=model)
[ "Optimize a sensor graph by running optimization passes.\n\n The passes are run one at a time and modify the sensor graph\n for future passes.\n\n Args:\n sensor_graph (SensorGraph): The graph to be optimized\n model (DeviceModel): The device that we are optimizing\n for, that OptimizationPass objects are free to use\n to guide their optimizations.\n " ]
Please provide a description of the function:def get_calling_namespaces(): try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). frame = sys.exc_info()[2].tb_frame.f_back # Find the first frame that *isn't* from this file. This means # that we expect all of the SCons frames that implement an Export() # or SConscript() call to be in this file, so that we can identify # the first non-Script.SConscript frame as the user's local calling # environment, and the locals and globals dictionaries from that # frame as the calling namespaces. See the comment below preceding # the DefaultEnvironmentCall block for even more explanation. while frame.f_globals.get("__name__") == __name__: frame = frame.f_back return frame.f_locals, frame.f_globals
[ "Return the locals and globals for the function that called\n into this module in the current call stack." ]
Please provide a description of the function:def compute_exports(exports): loc, glob = get_calling_namespaces() retval = {} try: for export in exports: if SCons.Util.is_Dict(export): retval.update(export) else: try: retval[export] = loc[export] except KeyError: retval[export] = glob[export] except KeyError as x: raise SCons.Errors.UserError("Export of non-existent variable '%s'"%x) return retval
[ "Compute a dictionary of exports given one of the parameters\n to the Export() function or the exports argument to SConscript()." ]
Please provide a description of the function:def SConscript_exception(file=sys.stderr): exc_type, exc_value, exc_tb = sys.exc_info() tb = exc_tb while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find our exec statement, so this was actually a bug # in SCons itself. Show the whole stack. tb = exc_tb stack = traceback.extract_tb(tb) try: type = exc_type.__name__ except AttributeError: type = str(exc_type) if type[:11] == "exceptions.": type = type[11:] file.write('%s: %s:\n' % (type, exc_value)) for fname, line, func, text in stack: file.write(' File "%s", line %d:\n' % (fname, line)) file.write(' %s\n' % text)
[ "Print an exception stack trace just for the SConscript file(s).\n This will show users who have Python errors where the problem is,\n without cluttering the output with all of the internal calls leading\n up to where we exec the SConscript." ]
Please provide a description of the function:def annotate(node): tb = sys.exc_info()[2] while tb and stack_bottom not in tb.tb_frame.f_locals: tb = tb.tb_next if not tb: # We did not find any exec of an SConscript file: what?! raise SCons.Errors.InternalError("could not find SConscript stack frame") node.creator = traceback.extract_stack(tb)[0]
[ "Annotate a node with the stack frame describing the\n SConscript file and line number that created it." ]
Please provide a description of the function:def BuildDefaultGlobals(): global GlobalDict if GlobalDict is None: GlobalDict = {} import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] return GlobalDict.copy()
[ "\n Create a dictionary containing all the default globals for\n SConstruct and SConscript files.\n " ]
Please provide a description of the function:def _exceeds_version(self, major, minor, v_major, v_minor): return (major > v_major or (major == v_major and minor > v_minor))
[ "Return 1 if 'major' and 'minor' are greater than the version\n in 'v_major' and 'v_minor', and 0 otherwise." ]
Please provide a description of the function:def _get_major_minor_revision(self, version_string): version = version_string.split(' ')[0].split('.') v_major = int(version[0]) v_minor = int(re.match('\d+', version[1]).group()) if len(version) >= 3: v_revision = int(re.match('\d+', version[2]).group()) else: v_revision = 0 return v_major, v_minor, v_revision
[ "Split a version string into major, minor and (optionally)\n revision parts.\n\n This is complicated by the fact that a version string can be\n something like 3.2b1." ]
Please provide a description of the function:def _get_SConscript_filenames(self, ls, kw): exports = [] if len(ls) == 0: try: dirs = kw["dirs"] except KeyError: raise SCons.Errors.UserError("Invalid SConscript usage - no parameters") if not SCons.Util.is_List(dirs): dirs = [ dirs ] dirs = list(map(str, dirs)) name = kw.get('name', 'SConscript') files = [os.path.join(n, name) for n in dirs] elif len(ls) == 1: files = ls[0] elif len(ls) == 2: files = ls[0] exports = self.Split(ls[1]) else: raise SCons.Errors.UserError("Invalid SConscript() usage - too many arguments") if not SCons.Util.is_List(files): files = [ files ] if kw.get('exports'): exports.extend(self.Split(kw['exports'])) variant_dir = kw.get('variant_dir') or kw.get('build_dir') if variant_dir: if len(files) != 1: raise SCons.Errors.UserError("Invalid SConscript() usage - can only specify one SConscript with a variant_dir") duplicate = kw.get('duplicate', 1) src_dir = kw.get('src_dir') if not src_dir: src_dir, fname = os.path.split(str(files[0])) files = [os.path.join(str(variant_dir), fname)] else: if not isinstance(src_dir, SCons.Node.Node): src_dir = self.fs.Dir(src_dir) fn = files[0] if not isinstance(fn, SCons.Node.Node): fn = self.fs.File(fn) if fn.is_under(src_dir): # Get path relative to the source directory. fname = fn.get_path(src_dir) files = [os.path.join(str(variant_dir), fname)] else: files = [fn.get_abspath()] kw['src_dir'] = variant_dir self.fs.VariantDir(variant_dir, src_dir, duplicate) return (files, exports)
[ "\n Convert the parameters passed to SConscript() calls into a list\n of files and export variables. If the parameters are invalid,\n throws SCons.Errors.UserError. Returns a tuple (l, e) where l\n is a list of SConscript filenames and e is a list of exports.\n " ]
Please provide a description of the function:def EnsureSConsVersion(self, major, minor, revision=0): # split string to avoid replacement during build process if SCons.__version__ == '__' + 'VERSION__': SCons.Warnings.warn(SCons.Warnings.DevelopmentVersionWarning, "EnsureSConsVersion is ignored for development version") return scons_ver = self._get_major_minor_revision(SCons.__version__) if scons_ver < (major, minor, revision): if revision: scons_ver_string = '%d.%d.%d' % (major, minor, revision) else: scons_ver_string = '%d.%d' % (major, minor) print("SCons %s or greater required, but you have SCons %s" % \ (scons_ver_string, SCons.__version__)) sys.exit(2)
[ "Exit abnormally if the SCons version is not late enough." ]
Please provide a description of the function:def EnsurePythonVersion(self, major, minor): if sys.version_info < (major, minor): v = sys.version.split()[0] print("Python %d.%d or greater required, but you have Python %s" %(major,minor,v)) sys.exit(2)
[ "Exit abnormally if the Python version is not late enough." ]
Please provide a description of the function:def FromBinary(cls, record_data, record_count=1): if len(record_data) != 0: raise ArgumentError("Reset device record should have no included data", length=len(record_data)) return ResetDeviceRecord()
[ "Create an UpdateRecord subclass from binary record data.\n\n This should be called with a binary record blob (NOT including the\n record type header) and it will decode it into a ResetDeviceRecord.\n\n Args:\n record_data (bytearray): The raw record data that we wish to parse\n into an UpdateRecord subclass NOT including its 8 byte record header.\n record_count (int): The number of records included in record_data.\n\n Raises:\n ArgumentError: If the record_data is malformed and cannot be parsed.\n\n Returns:\n ResetDeviceRecord: The decoded reflash tile record.\n " ]
Please provide a description of the function:def validate_vars(env): if 'PCH' in env and env['PCH']: if 'PCHSTOP' not in env: raise SCons.Errors.UserError("The PCHSTOP construction must be defined if PCH is defined.") if not SCons.Util.is_String(env['PCHSTOP']): raise SCons.Errors.UserError("The PCHSTOP construction variable must be a string: %r"%env['PCHSTOP'])
[ "Validate the PCH and PCHSTOP construction variables." ]
Please provide a description of the function:def msvc_set_PCHPDBFLAGS(env): if env.get('MSVC_VERSION',False): maj, min = msvc_version_to_maj_min(env['MSVC_VERSION']) if maj < 8: env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}']) else: env['PCHPDBFLAGS'] = '' else: # Default if we can't determine which version of MSVC we're using env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}'])
[ "\n Set appropriate PCHPDBFLAGS for the MSVC version being used.\n " ]
Please provide a description of the function:def pch_emitter(target, source, env): validate_vars(env) pch = None obj = None for t in target: if SCons.Util.splitext(str(t))[1] == '.pch': pch = t if SCons.Util.splitext(str(t))[1] == '.obj': obj = t if not obj: obj = SCons.Util.splitext(str(pch))[0]+'.obj' target = [pch, obj] # pch must be first, and obj second for the PCHCOM to work return (target, source)
[ "Adds the object file target." ]
Please provide a description of the function:def object_emitter(target, source, env, parent_emitter): validate_vars(env) parent_emitter(target, source, env) # Add a dependency, but only if the target (e.g. 'Source1.obj') # doesn't correspond to the pre-compiled header ('Source1.pch'). # If the basenames match, then this was most likely caused by # someone adding the source file to both the env.PCH() and the # env.Program() calls, and adding the explicit dependency would # cause a cycle on the .pch file itself. # # See issue #2505 for a discussion of what to do if it turns # out this assumption causes trouble in the wild: # http://scons.tigris.org/issues/show_bug.cgi?id=2505 if 'PCH' in env: pch = env['PCH'] if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj': env.Depends(target, pch) return (target, source)
[ "Sets up the PCH dependencies for an object file." ]
Please provide a description of the function:def msvc_batch_key(action, env, target, source): # Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH # was set to False. This new version should work better. # Note we need to do the env.subst so $MSVC_BATCH can be a reference to # another construction variable, which is why we test for False and 0 # as strings. if not 'MSVC_BATCH' in env or env.subst('$MSVC_BATCH') in ('0', 'False', '', None): # We're not using batching; return no key. return None t = target[0] s = source[0] if os.path.splitext(t.name)[0] != os.path.splitext(s.name)[0]: # The base names are different, so this *must* be compiled # separately; return no key. return None return (id(action), id(env), t.dir, s.dir)
[ "\n Returns a key to identify unique batches of sources for compilation.\n\n If batching is enabled (via the $MSVC_BATCH setting), then all\n target+source pairs that use the same action, defined by the same\n environment, and have the same target and source directories, will\n be batched.\n\n Returning None specifies that the specified target+source should not\n be batched with other compilations.\n " ]
Please provide a description of the function:def msvc_output_flag(target, source, env, for_signature): # Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH # was set to False. This new version should work better. Removed # len(source)==1 as batch mode can compile only one file # (and it also fixed problem with compiling only one changed file # with batch mode enabled) if not 'MSVC_BATCH' in env or env.subst('$MSVC_BATCH') in ('0', 'False', '', None): return '/Fo$TARGET' else: # The Visual C/C++ compiler requires a \ at the end of the /Fo # option to indicate an output directory. We use os.sep here so # that the test(s) for this can be run on non-Windows systems # without having a hard-coded backslash mess up command-line # argument parsing. return '/Fo${TARGET.dir}' + os.sep
[ "\n Returns the correct /Fo flag for batching.\n\n If batching is disabled or there's only one source file, then we\n return an /Fo string that specifies the target explicitly. Otherwise,\n we return an /Fo string that just specifies the first target's\n directory (where the Visual C/C++ compiler will put the .obj files).\n " ]
Please provide a description of the function:def generate(env): static_obj, shared_obj = SCons.Tool.createObjBuilders(env) # TODO(batch): shouldn't reach in to cmdgen this way; necessary # for now to bypass the checks in Builder.DictCmdGenerator.__call__() # and allow .cc and .cpp to be compiled in the same command line. static_obj.cmdgen.source_ext_match = False shared_obj.cmdgen.source_ext_match = False for suffix in CSuffixes: static_obj.add_action(suffix, CAction) shared_obj.add_action(suffix, ShCAction) static_obj.add_emitter(suffix, static_object_emitter) shared_obj.add_emitter(suffix, shared_object_emitter) for suffix in CXXSuffixes: static_obj.add_action(suffix, CXXAction) shared_obj.add_action(suffix, ShCXXAction) static_obj.add_emitter(suffix, static_object_emitter) shared_obj.add_emitter(suffix, shared_object_emitter) env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}']) env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s \\\"/Fp%s\\\""%(PCHSTOP or "",File(PCH))) or ""}']) env['_MSVC_OUTPUT_FLAG'] = msvc_output_flag env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS' env['CC'] = 'cl' env['CCFLAGS'] = SCons.Util.CLVar('/nologo') env['CFLAGS'] = SCons.Util.CLVar('') env['CCCOM'] = '${TEMPFILE("$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM","$CCCOMSTR")}' env['SHCC'] = '$CC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS') env['SHCCCOM'] = '${TEMPFILE("$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM","$SHCCCOMSTR")}' env['CXX'] = '$CC' env['CXXFLAGS'] = SCons.Util.CLVar('$( /TP $)') env['CXXCOM'] = '${TEMPFILE("$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM","$CXXCOMSTR")}' env['SHCXX'] = '$CXX' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHCXXCOM'] = '${TEMPFILE("$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM","$SHCXXCOMSTR")}' env['CPPDEFPREFIX'] = '/D' env['CPPDEFSUFFIX'] = '' env['INCPREFIX'] = '/I' env['INCSUFFIX'] = '' # env.Append(OBJEMITTER = [static_object_emitter]) # env.Append(SHOBJEMITTER = [shared_object_emitter]) env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = 'rc' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCSUFFIXES']=['.rc','.rc2'] env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES' env['BUILDERS']['RES'] = res_builder env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' # Set-up ms tools paths msvc_setup_env_once(env) env['CFILESUFFIX'] = '.c' env['CXXFILESUFFIX'] = '.cc' msvc_set_PCHPDBFLAGS(env) env['PCHCOM'] = '$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS' env['BUILDERS']['PCH'] = pch_builder if 'ENV' not in env: env['ENV'] = {} if 'SystemRoot' not in env['ENV']: # required for dlls in the winsxs folders env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root()
[ "Add Builders and construction variables for MSVC++ to an Environment." ]
Please provide a description of the function:def open(self): self.hwman = HardwareManager(port=self._port) self.opened = True if self._connection_string is not None: try: self.hwman.connect_direct(self._connection_string) except HardwareError: self.hwman.close() raise elif self._connect_id is not None: try: self.hwman.connect(self._connect_id) except HardwareError: self.hwman.close() raise
[ "Open and potentially connect to a device." ]
Please provide a description of the function:def close(self): if self.hwman.stream.connected: self.hwman.disconnect() self.hwman.close() self.opened = False
[ "Close and potentially disconnect from a device." ]
Please provide a description of the function:def get_support_package(tile): packages = tile.find_products('support_package') if len(packages) == 0: return None elif len(packages) == 1: return packages[0] raise BuildError("Tile declared multiple support packages, only one is supported", packages=packages)
[ "Returns the support_package product." ]
Please provide a description of the function:def iter_support_files(tile): support_package = get_support_package(tile) if support_package is None: for module, _, _ in iter_python_modules(tile): yield os.path.basename(module), module else: for dirpath, _dirnames, filenames in os.walk(support_package): for filename in filenames: if not filename.endswith('.py'): continue input_path = os.path.join(dirpath, filename) output_path = os.path.relpath(input_path, start=support_package) if output_path == "__init__.py": continue yield output_path, input_path
[ "Iterate over all files that go in the support wheel.\n\n This method has two possible behaviors. If there is a 'support_package'\n product defined, then this recursively enumerates all .py files inside\n that folder and adds them all in the same hierarchy to the support wheel.\n\n If there is no support_package product defined, then the old behavior\n takes over, where all files containing python entrypoints are iterated\n over using iter_python_modules() and they are copied into the support\n wheel and then an __init__.py file is added.\n\n The files are yielded as tuples of (copy_name, input_path).\n " ]
Please provide a description of the function:def iter_python_modules(tile): for product_type in tile.PYTHON_PRODUCTS: for product in tile.find_products(product_type): entry_point = ENTRY_POINT_MAP.get(product_type) if entry_point is None: raise BuildError("Found an unknown python product (%s) whose entrypoint could not be determined (%s)" % (product_type, product)) if ':' in product: module, _, obj_name = product.rpartition(':') else: module = product obj_name = None if not os.path.exists(module): raise BuildError("Found a python product whose path did not exist: %s" % module) product_name = os.path.basename(module) if product_name.endswith(".py"): product_name = product_name[:-3] import_string = "{} = {}.{}".format(product_name, tile.support_distribution, product_name) if obj_name is not None: import_string += ":{}".format(obj_name) yield (module, import_string, entry_point)
[ "Iterate over all python products in the given tile.\n\n This will yield tuples where the first entry is the path to the module\n containing the product the second entry is the appropriate\n import string to include in an entry point, and the third entry is\n the entry point name.\n " ]
Please provide a description of the function:def generate_setup_py(target, source, env): tile = env['TILE'] data = {} entry_points = {} for _mod, import_string, entry_point in iter_python_modules(tile): if entry_point not in entry_points: entry_points[entry_point] = [] entry_points[entry_point].append(import_string) data['name'] = tile.support_distribution data['package'] = tile.support_distribution data['version'] = tile.parsed_version.pep440_string() data['deps'] = ["{0} {1}".format(x.support_distribution, x.parsed_version.pep440_compatibility_specifier()) for x in _iter_dependencies(tile) if x.has_wheel] # If there are some python packages needed, we add them to the list of dependencies required if tile.support_wheel_depends: data['deps'] += tile.support_wheel_depends data['entry_points'] = entry_points outdir = os.path.dirname(str(target[0])) render_template('setup.py.tpl', data, out_path=str(target[0])) # Run setuptools to generate a wheel and an sdist curr = os.getcwd() os.chdir(outdir) try: setuptools.sandbox.run_setup('setup.py', ['-q', 'clean', 'sdist']) if "python_universal" in tile.settings: setuptools.sandbox.run_setup('setup.py', ['-q', 'clean', 'bdist_wheel', '--universal']) else: setuptools.sandbox.run_setup('setup.py', ['-q', 'clean', 'bdist_wheel']) finally: os.chdir(curr)
[ "Generate the setup.py file for this distribution." ]
Please provide a description of the function:def defaultMachine(use_rpm_default=True): if use_rpm_default: try: # This should be the most reliable way to get the default arch rmachine = subprocess.check_output(['rpm', '--eval=%_target_cpu'], shell=False).rstrip() rmachine = SCons.Util.to_str(rmachine) except Exception as e: # Something went wrong, try again by looking up platform.machine() return defaultMachine(False) else: rmachine = platform.machine() # Try to lookup the string in the canon table if rmachine in arch_canon: rmachine = arch_canon[rmachine][0] return rmachine
[ " Return the canonicalized machine name. " ]
Please provide a description of the function:def defaultSystem(): rsystem = platform.system() # Try to lookup the string in the canon tables if rsystem in os_canon: rsystem = os_canon[rsystem][0] return rsystem
[ " Return the canonicalized system name. " ]
Please provide a description of the function:def updateRpmDicts(rpmrc, pyfile): try: # Read old rpmutils.py file oldpy = open(pyfile,"r").readlines() # Read current rpmrc.in file rpm = open(rpmrc,"r").readlines() # Parse for data data = {} # Allowed section names that get parsed sections = ['optflags', 'arch_canon', 'os_canon', 'buildarchtranslate', 'arch_compat', 'os_compat', 'buildarch_compat'] for l in rpm: l = l.rstrip('\n').replace(':',' ') # Skip comments if l.lstrip().startswith('#'): continue tokens = l.strip().split() if len(tokens): key = tokens[0] if key in sections: # Have we met this section before? if tokens[0] not in data: # No, so insert it data[key] = {} # Insert data data[key][tokens[1]] = tokens[2:] # Write new rpmutils.py file out = open(pyfile,"w") pm = 0 for l in oldpy: if pm: if l.startswith('# End of rpmrc dictionaries'): pm = 0 out.write(l) else: out.write(l) if l.startswith('# Start of rpmrc dictionaries'): pm = 1 # Write data sections to single dictionaries for key, entries in data.items(): out.write("%s = {\n" % key) for arch in sorted(entries.keys()): out.write(" '%s' : ['%s'],\n" % (arch, "','".join(entries[arch]))) out.write("}\n\n") out.close() except: pass
[ " Read the given rpmrc file with RPM definitions and update the\n info dictionaries in the file pyfile with it.\n The arguments will usually be 'rpmrc.in' from a recent RPM source\n tree, and 'rpmutils.py' referring to this script itself.\n See also usage() below.\n " ]
Please provide a description of the function:def prepare(self): global print_prepare T = self.tm.trace if T: T.write(self.trace_message(u'Task.prepare()', self.node)) # Now that it's the appropriate time, give the TaskMaster a # chance to raise any exceptions it encountered while preparing # this task. self.exception_raise() if self.tm.message: self.display(self.tm.message) self.tm.message = None # Let the targets take care of any necessary preparations. # This includes verifying that all of the necessary sources # and dependencies exist, removing the target file(s), etc. # # As of April 2008, the get_executor().prepare() method makes # sure that all of the aggregate sources necessary to build this # Task's target(s) exist in one up-front check. The individual # target t.prepare() methods check that each target's explicit # or implicit dependencies exists, and also initialize the # .sconsign info. executor = self.targets[0].get_executor() if executor is None: return executor.prepare() for t in executor.get_action_targets(): if print_prepare: print("Preparing target %s..."%t) for s in t.side_effects: print("...with side-effect %s..."%s) t.prepare() for s in t.side_effects: if print_prepare: print("...Preparing side-effect %s..."%s) s.prepare()
[ "\n Called just before the task is executed.\n\n This is mainly intended to give the target Nodes a chance to\n unlink underlying files and make all necessary directories before\n the Action is actually called to build the targets.\n " ]
Please provide a description of the function:def execute(self): T = self.tm.trace if T: T.write(self.trace_message(u'Task.execute()', self.node)) try: cached_targets = [] for t in self.targets: if not t.retrieve_from_cache(): break cached_targets.append(t) if len(cached_targets) < len(self.targets): # Remove targets before building. It's possible that we # partially retrieved targets from the cache, leaving # them in read-only mode. That might cause the command # to fail. # for t in cached_targets: try: t.fs.unlink(t.get_internal_path()) except (IOError, OSError): pass self.targets[0].build() else: for t in cached_targets: t.cached = 1 except SystemExit: exc_value = sys.exc_info()[1] raise SCons.Errors.ExplicitExit(self.targets[0], exc_value.code) except SCons.Errors.UserError: raise except SCons.Errors.BuildError: raise except Exception as e: buildError = SCons.Errors.convert_to_BuildError(e) buildError.node = self.targets[0] buildError.exc_info = sys.exc_info() raise buildError
[ "\n Called to execute the task.\n\n This method is called from multiple threads in a parallel build,\n so only do thread safe stuff here. Do thread unsafe stuff in\n prepare(), executed() or failed().\n " ]
Please provide a description of the function:def executed_without_callbacks(self): T = self.tm.trace if T: T.write(self.trace_message('Task.executed_without_callbacks()', self.node)) for t in self.targets: if t.get_state() == NODE_EXECUTING: for side_effect in t.side_effects: side_effect.set_state(NODE_NO_STATE) t.set_state(NODE_EXECUTED)
[ "\n Called when the task has been successfully executed\n and the Taskmaster instance doesn't want to call\n the Node's callback methods.\n " ]
Please provide a description of the function:def executed_with_callbacks(self): global print_prepare T = self.tm.trace if T: T.write(self.trace_message('Task.executed_with_callbacks()', self.node)) for t in self.targets: if t.get_state() == NODE_EXECUTING: for side_effect in t.side_effects: side_effect.set_state(NODE_NO_STATE) t.set_state(NODE_EXECUTED) if not t.cached: t.push_to_cache() t.built() t.visited() if (not print_prepare and (not hasattr(self, 'options') or not self.options.debug_includes)): t.release_target_info() else: t.visited()
[ "\n Called when the task has been successfully executed and\n the Taskmaster instance wants to call the Node's callback\n methods.\n\n This may have been a do-nothing operation (to preserve build\n order), so we must check the node's state before deciding whether\n it was \"built\", in which case we call the appropriate Node method.\n In any event, we always call \"visited()\", which will handle any\n post-visit actions that must take place regardless of whether\n or not the target was an actual built target or a source Node.\n " ]
Please provide a description of the function:def fail_stop(self): T = self.tm.trace if T: T.write(self.trace_message('Task.failed_stop()', self.node)) # Invoke will_not_build() to clean-up the pending children # list. self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED)) # Tell the taskmaster to not start any new tasks self.tm.stop() # We're stopping because of a build failure, but give the # calling Task class a chance to postprocess() the top-level # target under which the build failure occurred. self.targets = [self.tm.current_top] self.top = 1
[ "\n Explicit stop-the-build failure.\n\n This sets failure status on the target nodes and all of\n their dependent parent nodes.\n\n Note: Although this function is normally invoked on nodes in\n the executing state, it might also be invoked on up-to-date\n nodes when using Configure().\n " ]
Please provide a description of the function:def fail_continue(self): T = self.tm.trace if T: T.write(self.trace_message('Task.failed_continue()', self.node)) self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED))
[ "\n Explicit continue-the-build failure.\n\n This sets failure status on the target nodes and all of\n their dependent parent nodes.\n\n Note: Although this function is normally invoked on nodes in\n the executing state, it might also be invoked on up-to-date\n nodes when using Configure().\n " ]
Please provide a description of the function:def make_ready_all(self): T = self.tm.trace if T: T.write(self.trace_message('Task.make_ready_all()', self.node)) self.out_of_date = self.targets[:] for t in self.targets: t.disambiguate().set_state(NODE_EXECUTING) for s in t.side_effects: # add disambiguate here to mirror the call on targets above s.disambiguate().set_state(NODE_EXECUTING)
[ "\n Marks all targets in a task ready for execution.\n\n This is used when the interface needs every target Node to be\n visited--the canonical example being the \"scons -c\" option.\n " ]
Please provide a description of the function:def make_ready_current(self): global print_prepare T = self.tm.trace if T: T.write(self.trace_message(u'Task.make_ready_current()', self.node)) self.out_of_date = [] needs_executing = False for t in self.targets: try: t.disambiguate().make_ready() is_up_to_date = not t.has_builder() or \ (not t.always_build and t.is_up_to_date()) except EnvironmentError as e: raise SCons.Errors.BuildError(node=t, errstr=e.strerror, filename=e.filename) if not is_up_to_date: self.out_of_date.append(t) needs_executing = True if needs_executing: for t in self.targets: t.set_state(NODE_EXECUTING) for s in t.side_effects: # add disambiguate here to mirror the call on targets in first loop above s.disambiguate().set_state(NODE_EXECUTING) else: for t in self.targets: # We must invoke visited() to ensure that the node # information has been computed before allowing the # parent nodes to execute. (That could occur in a # parallel build...) t.visited() t.set_state(NODE_UP_TO_DATE) if (not print_prepare and (not hasattr(self, 'options') or not self.options.debug_includes)): t.release_target_info()
[ "\n Marks all targets in a task ready for execution if any target\n is not current.\n\n This is the default behavior for building only what's necessary.\n " ]
Please provide a description of the function:def postprocess(self): T = self.tm.trace if T: T.write(self.trace_message(u'Task.postprocess()', self.node)) # We may have built multiple targets, some of which may have # common parents waiting for this build. Count up how many # targets each parent was waiting for so we can subtract the # values later, and so we *don't* put waiting side-effect Nodes # back on the candidates list if the Node is also a waiting # parent. targets = set(self.targets) pending_children = self.tm.pending_children parents = {} for t in targets: # A node can only be in the pending_children set if it has # some waiting_parents. if t.waiting_parents: if T: T.write(self.trace_message(u'Task.postprocess()', t, 'removing')) pending_children.discard(t) for p in t.waiting_parents: parents[p] = parents.get(p, 0) + 1 for t in targets: if t.side_effects is not None: for s in t.side_effects: if s.get_state() == NODE_EXECUTING: s.set_state(NODE_NO_STATE) for p in s.waiting_parents: parents[p] = parents.get(p, 0) + 1 for p in s.waiting_s_e: if p.ref_count == 0: self.tm.candidates.append(p) for p, subtract in parents.items(): p.ref_count = p.ref_count - subtract if T: T.write(self.trace_message(u'Task.postprocess()', p, 'adjusted parent ref count')) if p.ref_count == 0: self.tm.candidates.append(p) for t in targets: t.postprocess()
[ "\n Post-processes a task after it's been executed.\n\n This examines all the targets just built (or not, we don't care\n if the build was successful, or even if there was no build\n because everything was up-to-date) to see if they have any\n waiting parent Nodes, or Nodes waiting on a common side effect,\n that can be put back on the candidates list.\n " ]
Please provide a description of the function:def exception_set(self, exception=None): if not exception: exception = sys.exc_info() self.exception = exception self.exception_raise = self._exception_raise
[ "\n Records an exception to be raised at the appropriate time.\n\n This also changes the \"exception_raise\" attribute to point\n to the method that will, in fact\n " ]
Please provide a description of the function:def _exception_raise(self): exc = self.exc_info()[:] try: exc_type, exc_value, exc_traceback = exc except ValueError: exc_type, exc_value = exc exc_traceback = None # raise exc_type(exc_value).with_traceback(exc_traceback) if sys.version_info[0] == 2: exec("raise exc_type, exc_value, exc_traceback") else: # sys.version_info[0] == 3: if isinstance(exc_value, Exception): #hasattr(exc_value, 'with_traceback'): # If exc_value is an exception, then just reraise exec("raise exc_value.with_traceback(exc_traceback)") else: # else we'll create an exception using the value and raise that exec("raise exc_type(exc_value).with_traceback(exc_traceback)")
[ "\n Raises a pending exception that was recorded while getting a\n Task ready for execution.\n " ]
Please provide a description of the function:def find_next_candidate(self): try: return self.candidates.pop() except IndexError: pass try: node = self.top_targets_left.pop() except IndexError: return None self.current_top = node alt, message = node.alter_targets() if alt: self.message = message self.candidates.append(node) self.candidates.extend(self.order(alt)) node = self.candidates.pop() return node
[ "\n Returns the next candidate Node for (potential) evaluation.\n\n The candidate list (really a stack) initially consists of all of\n the top-level (command line) targets provided when the Taskmaster\n was initialized. While we walk the DAG, visiting Nodes, all the\n children that haven't finished processing get pushed on to the\n candidate list. Each child can then be popped and examined in\n turn for whether *their* children are all up-to-date, in which\n case a Task will be created for their actual evaluation and\n potential building.\n\n Here is where we also allow candidate Nodes to alter the list of\n Nodes that should be examined. This is used, for example, when\n invoking SCons in a source directory. A source directory Node can\n return its corresponding build directory Node, essentially saying,\n \"Hey, you really need to build this thing over here instead.\"\n " ]
Please provide a description of the function:def no_next_candidate(self): while self.candidates: candidates = self.candidates self.candidates = [] self.will_not_build(candidates) return None
[ "\n Stops Taskmaster processing by not returning a next candidate.\n\n Note that we have to clean-up the Taskmaster candidate list\n because the cycle detection depends on the fact all nodes have\n been processed somehow.\n " ]
Please provide a description of the function:def _validate_pending_children(self): for n in self.pending_children: assert n.state in (NODE_PENDING, NODE_EXECUTING), \ (str(n), StateString[n.state]) assert len(n.waiting_parents) != 0, (str(n), len(n.waiting_parents)) for p in n.waiting_parents: assert p.ref_count > 0, (str(n), str(p), p.ref_count)
[ "\n Validate the content of the pending_children set. Assert if an\n internal error is found.\n\n This function is used strictly for debugging the taskmaster by\n checking that no invariants are violated. It is not used in\n normal operation.\n\n The pending_children set is used to detect cycles in the\n dependency graph. We call a \"pending child\" a child that is\n found in the \"pending\" state when checking the dependencies of\n its parent node.\n\n A pending child can occur when the Taskmaster completes a loop\n through a cycle. For example, let's imagine a graph made of\n three nodes (A, B and C) making a cycle. The evaluation starts\n at node A. The Taskmaster first considers whether node A's\n child B is up-to-date. Then, recursively, node B needs to\n check whether node C is up-to-date. This leaves us with a\n dependency graph looking like::\n\n Next candidate \\\n \\\n Node A (Pending) --> Node B(Pending) --> Node C (NoState)\n ^ |\n | |\n +-------------------------------------+\n\n Now, when the Taskmaster examines the Node C's child Node A,\n it finds that Node A is in the \"pending\" state. Therefore,\n Node A is a pending child of node C.\n\n Pending children indicate that the Taskmaster has potentially\n loop back through a cycle. We say potentially because it could\n also occur when a DAG is evaluated in parallel. For example,\n consider the following graph::\n\n Node A (Pending) --> Node B(Pending) --> Node C (Pending) --> ...\n | ^\n | |\n +----------> Node D (NoState) --------+\n /\n Next candidate /\n\n The Taskmaster first evaluates the nodes A, B, and C and\n starts building some children of node C. Assuming, that the\n maximum parallel level has not been reached, the Taskmaster\n will examine Node D. It will find that Node C is a pending\n child of Node D.\n\n In summary, evaluating a graph with a cycle will always\n involve a pending child at one point. A pending child might\n indicate either a cycle or a diamond-shaped DAG. Only a\n fraction of the nodes ends-up being a \"pending child\" of\n another node. This keeps the pending_children set small in\n practice.\n\n We can differentiate between the two cases if we wait until\n the end of the build. At this point, all the pending children\n nodes due to a diamond-shaped DAG will have been properly\n built (or will have failed to build). But, the pending\n children involved in a cycle will still be in the pending\n state.\n\n The taskmaster removes nodes from the pending_children set as\n soon as a pending_children node moves out of the pending\n state. This also helps to keep the pending_children set small.\n " ]
Please provide a description of the function:def _find_next_ready_node(self): self.ready_exc = None T = self.trace if T: T.write(SCons.Util.UnicodeType('\n') + self.trace_message('Looking for a node to evaluate')) while True: node = self.next_candidate() if node is None: if T: T.write(self.trace_message('No candidate anymore.') + u'\n') return None node = node.disambiguate() state = node.get_state() # For debugging only: # # try: # self._validate_pending_children() # except: # self.ready_exc = sys.exc_info() # return node if CollectStats: if not hasattr(node.attributes, 'stats'): node.attributes.stats = Stats() StatsNodes.append(node) S = node.attributes.stats S.considered = S.considered + 1 else: S = None if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node))) if state == NODE_NO_STATE: # Mark this node as being on the execution stack: node.set_state(NODE_PENDING) elif state > NODE_PENDING: # Skip this node if it has already been evaluated: if S: S.already_handled = S.already_handled + 1 if T: T.write(self.trace_message(u' already handled (executed)')) continue executor = node.get_executor() try: children = executor.get_all_children() except SystemExit: exc_value = sys.exc_info()[1] e = SCons.Errors.ExplicitExit(node, exc_value.code) self.ready_exc = (SCons.Errors.ExplicitExit, e) if T: T.write(self.trace_message(' SystemExit')) return node except Exception as e: # We had a problem just trying to figure out the # children (like a child couldn't be linked in to a # VariantDir, or a Scanner threw something). Arrange to # raise the exception when the Task is "executed." self.ready_exc = sys.exc_info() if S: S.problem = S.problem + 1 if T: T.write(self.trace_message(' exception %s while scanning children.\n' % e)) return node children_not_visited = [] children_pending = set() children_not_ready = [] children_failed = False for child in chain(executor.get_all_prerequisites(), children): childstate = child.get_state() if T: T.write(self.trace_message(u' ' + self.trace_node(child))) if childstate == NODE_NO_STATE: children_not_visited.append(child) elif childstate == NODE_PENDING: children_pending.add(child) elif childstate == NODE_FAILED: children_failed = True if childstate <= NODE_EXECUTING: children_not_ready.append(child) # These nodes have not even been visited yet. Add # them to the list so that on some next pass we can # take a stab at evaluating them (or their children). children_not_visited.reverse() self.candidates.extend(self.order(children_not_visited)) # if T and children_not_visited: # T.write(self.trace_message(' adding to candidates: %s' % map(str, children_not_visited))) # T.write(self.trace_message(' candidates now: %s\n' % map(str, self.candidates))) # Skip this node if any of its children have failed. # # This catches the case where we're descending a top-level # target and one of our children failed while trying to be # built by a *previous* descent of an earlier top-level # target. # # It can also occur if a node is reused in multiple # targets. One first descends though the one of the # target, the next time occurs through the other target. # # Note that we can only have failed_children if the # --keep-going flag was used, because without it the build # will stop before diving in the other branch. # # Note that even if one of the children fails, we still # added the other children to the list of candidate nodes # to keep on building (--keep-going). if children_failed: for n in executor.get_action_targets(): n.set_state(NODE_FAILED) if S: S.child_failed = S.child_failed + 1 if T: T.write(self.trace_message('****** %s\n' % self.trace_node(node))) continue if children_not_ready: for child in children_not_ready: # We're waiting on one or more derived targets # that have not yet finished building. if S: S.not_built = S.not_built + 1 # Add this node to the waiting parents lists of # anything we're waiting on, with a reference # count so we can be put back on the list for # re-evaluation when they've all finished. node.ref_count = node.ref_count + child.add_to_waiting_parents(node) if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' % (self.trace_node(node), repr(str(child))))) if T: for pc in children_pending: T.write(self.trace_message(' adding %s to the pending children set\n' % self.trace_node(pc))) self.pending_children = self.pending_children | children_pending continue # Skip this node if it has side-effects that are # currently being built: wait_side_effects = False for se in executor.get_action_side_effects(): if se.get_state() == NODE_EXECUTING: se.add_to_waiting_s_e(node) wait_side_effects = True if wait_side_effects: if S: S.side_effects = S.side_effects + 1 continue # The default when we've gotten through all of the checks above: # this node is ready to be built. if S: S.build = S.build + 1 if T: T.write(self.trace_message(u'Evaluating %s\n' % self.trace_node(node))) # For debugging only: # # try: # self._validate_pending_children() # except: # self.ready_exc = sys.exc_info() # return node return node return None
[ "\n Finds the next node that is ready to be built.\n\n This is *the* main guts of the DAG walk. We loop through the\n list of candidates, looking for something that has no un-built\n children (i.e., that is a leaf Node or has dependencies that are\n all leaf Nodes or up-to-date). Candidate Nodes are re-scanned\n (both the target Node itself and its sources, which are always\n scanned in the context of a given target) to discover implicit\n dependencies. A Node that must wait for some children to be\n built will be put back on the candidates list after the children\n have finished building. A Node that has been put back on the\n candidates list in this way may have itself (or its sources)\n re-scanned, in order to handle generated header files (e.g.) and\n the implicit dependencies therein.\n\n Note that this method does not do any signature calculation or\n up-to-date check itself. All of that is handled by the Task\n class. This is purely concerned with the dependency graph walk.\n " ]
Please provide a description of the function:def next_task(self): node = self._find_next_ready_node() if node is None: return None executor = node.get_executor() if executor is None: return None tlist = executor.get_all_targets() task = self.tasker(self, tlist, node in self.original_top, node) try: task.make_ready() except Exception as e : # We had a problem just trying to get this task ready (like # a child couldn't be linked to a VariantDir when deciding # whether this node is current). Arrange to raise the # exception when the Task is "executed." self.ready_exc = sys.exc_info() if self.ready_exc: task.exception_set(self.ready_exc) self.ready_exc = None return task
[ "\n Returns the next task to be executed.\n\n This simply asks for the next Node to be evaluated, and then wraps\n it in the specific Task subclass with which we were initialized.\n " ]
Please provide a description of the function:def will_not_build(self, nodes, node_func=lambda n: None): T = self.trace pending_children = self.pending_children to_visit = set(nodes) pending_children = pending_children - to_visit if T: for n in nodes: T.write(self.trace_message(' removing node %s from the pending children set\n' % self.trace_node(n))) try: while len(to_visit): node = to_visit.pop() node_func(node) # Prune recursion by flushing the waiting children # list immediately. parents = node.waiting_parents node.waiting_parents = set() to_visit = to_visit | parents pending_children = pending_children - parents for p in parents: p.ref_count = p.ref_count - 1 if T: T.write(self.trace_message(' removing parent %s from the pending children set\n' % self.trace_node(p))) except KeyError: # The container to_visit has been emptied. pass # We have the stick back the pending_children list into the # taskmaster because the python 1.5.2 compatibility does not # allow us to use in-place updates self.pending_children = pending_children
[ "\n Perform clean-up about nodes that will never be built. Invokes\n a user defined function on all of these nodes (including all\n of their parents).\n " ]
Please provide a description of the function:def cleanup(self): if not self.pending_children: return nclist = [(n, find_cycle([n], set())) for n in self.pending_children] genuine_cycles = [ node for node,cycle in nclist if cycle or node.get_state() != NODE_EXECUTED ] if not genuine_cycles: # All of the "cycles" found were single nodes in EXECUTED state, # which is to say, they really weren't cycles. Just return. return desc = 'Found dependency cycle(s):\n' for node, cycle in nclist: if cycle: desc = desc + " " + " -> ".join(map(str, cycle)) + "\n" else: desc = desc + \ " Internal Error: no cycle found for node %s (%s) in state %s\n" % \ (node, repr(node), StateString[node.get_state()]) raise SCons.Errors.UserError(desc)
[ "\n Check for dependency cycles.\n " ]
Please provide a description of the function:def run(self, sensor_graph, model): # This check can be done if there is 1 input and it is count == 1 # and the stream type is input or unbuffered for node, inputs, outputs in sensor_graph.iterate_bfs(): if node.num_inputs != 1: continue input_a, trigger_a = node.inputs[0] if input_a.selector.match_type not in [DataStream.InputType, DataStream.UnbufferedType]: continue if not isinstance(trigger_a, InputTrigger): continue if trigger_a.comp_string != u'==': continue if not trigger_a.use_count: continue if trigger_a.reference != 1: continue # here we're looking at count input | unbuffered X == 1 node.inputs[0] = (input_a, TrueTrigger())
[ "Run this optimization pass on the sensor graph\n\n If necessary, information on the device model being targeted\n can be found in the associated model argument.\n\n Args:\n sensor_graph (SensorGraph): The sensor graph to optimize\n model (DeviceModel): The device model we're using\n " ]
Please provide a description of the function:def instantiate_resolver(self, name, args): if name not in self._known_resolvers: raise ArgumentError("Attempting to instantiate unknown dependency resolver", name=name) return self._known_resolvers[name](args)
[ "Directly instantiate a dependency resolver by name with the given arguments\n\n Args:\n name (string): The name of the class that we want to instantiate\n args (dict): The arguments to pass to the resolver factory\n\n Returns:\n DependencyResolver\n " ]
Please provide a description of the function:def pull_release(self, name, version, destfolder=".", force=False): unique_id = name.replace('/', '_') depdict = { 'name': name, 'unique_id': unique_id, 'required_version': version, 'required_version_string': str(version) } destdir = os.path.join(destfolder, unique_id) if os.path.exists(destdir): if not force: raise ExternalError("Output directory exists and force was not specified, aborting", output_directory=destdir) shutil.rmtree(destdir) result = self.update_dependency(None, depdict, destdir) if result != "installed": raise ArgumentError("Could not find component to satisfy name/version combination")
[ "Download and unpack a released iotile component by name and version range\n\n If the folder that would be created already exists, this command fails unless\n you pass force=True\n\n Args:\n name (string): The name of the component to download\n version (SemanticVersionRange): The valid versions of the component to fetch\n destfolder (string): The folder into which to unpack the result, defaults to\n the current working directory\n force (bool): Forcibly overwrite whatever is currently in the folder that would\n be fetched.\n\n Raises:\n ExternalError: If the destination folder exists and force is not specified\n ArgumentError: If the specified component could not be found with the required version\n " ]
Please provide a description of the function:def update_dependency(self, tile, depinfo, destdir=None): if destdir is None: destdir = os.path.join(tile.folder, 'build', 'deps', depinfo['unique_id']) has_version = False had_version = False if os.path.exists(destdir): has_version = True had_version = True for priority, rule in self.rules: if not self._check_rule(rule, depinfo): continue resolver = self._find_resolver(rule) if has_version: deptile = IOTile(destdir) # If the dependency is not up to date, don't do anything depstatus = self._check_dep(depinfo, deptile, resolver) if depstatus is False: shutil.rmtree(destdir) has_version = False else: continue # Now try to resolve this dependency with the latest version result = resolver.resolve(depinfo, destdir) if not result['found'] and result.get('stop', False): return 'not found' if not result['found']: continue settings = { 'resolver': resolver.__class__.__name__, 'factory_args': rule[2] } if 'settings' in result: settings['settings'] = result['settings'] self._save_depsettings(destdir, settings) if had_version: return "updated" return "installed" if has_version: return "already installed" return "not found"
[ "Attempt to install or update a dependency to the latest version.\n\n Args:\n tile (IOTile): An IOTile object describing the tile that has the dependency\n depinfo (dict): a dictionary from tile.dependencies specifying the dependency\n destdir (string): An optional folder into which to unpack the dependency\n\n Returns:\n string: a string indicating the outcome. Possible values are:\n \"already installed\"\n \"installed\"\n \"updated\"\n \"not found\"\n " ]
Please provide a description of the function:def _check_dep(self, depinfo, deptile, resolver): try: settings = self._load_depsettings(deptile) except IOError: return False # If this dependency was initially resolved with a different resolver, then # we cannot check if it is up to date if settings['resolver'] != resolver.__class__.__name__: return None resolver_settings = {} if 'settings' in settings: resolver_settings = settings['settings'] return resolver.check(depinfo, deptile, resolver_settings)
[ "Check if a dependency tile is up to date\n\n Returns:\n bool: True if it is up to date, False if it not and None if this resolver\n cannot assess whether or not it is up to date.\n " ]
Please provide a description of the function:def _log_future_exception(future, logger): if not future.done(): return try: future.result() except: #pylint:disable=bare-except;This is a background logging helper logger.warning("Exception in ignored future: %s", future, exc_info=True)
[ "Log any exception raised by future." ]
Please provide a description of the function:def create_subtask(self, cor, name=None, stop_timeout=1.0): if self.stopped: raise InternalError("Cannot add a subtask to a parent that is already stopped") subtask = BackgroundTask(cor, name, loop=self._loop, stop_timeout=stop_timeout) self.add_subtask(subtask) return subtask
[ "Create and add a subtask from a coroutine.\n\n This function will create a BackgroundTask and then\n call self.add_subtask() on it.\n\n Args:\n cor (coroutine): The coroutine that should be wrapped\n in a background task.\n name (str): An optional name for the task.\n stop_timeout (float): The maximum time to wait for this\n subtask to die after stopping it.\n\n Returns:\n Backgroundtask: The created subtask.\n " ]
Please provide a description of the function:def add_subtask(self, subtask): if self.stopped: raise InternalError("Cannot add a subtask to a parent that is already stopped") if not isinstance(subtask, BackgroundTask): raise ArgumentError("Subtasks must inherit from BackgroundTask, task={}".format(subtask)) #pylint:disable=protected-access;It is the same class as us so is equivalent to self access. if subtask._loop != self._loop: raise ArgumentError("Subtasks must run in the same BackgroundEventLoop as their parent", subtask=subtask, parent=self) self.subtasks.append(subtask)
[ "Link a subtask to this parent task.\n\n This will cause stop() to block until the subtask has also\n finished. Calling stop will not directly cancel the subtask.\n It is expected that your finalizer for this parent task will\n cancel or otherwise stop the subtask.\n\n Args:\n subtask (BackgroundTask): Another task that will be stopped\n when this task is stopped.\n " ]
Please provide a description of the function:async def stop(self): if self.stopped: return self._logger.debug("Stopping task %s", self.name) if self._finalizer is not None: try: result = self._finalizer(self) if inspect.isawaitable(result): await result except: #pylint:disable=bare-except;We need to make sure we always wait for the task self._logger.exception("Error running finalizer for task %s", self.name) elif self.task is not None: self.task.cancel() tasks = [] if self.task is not None: tasks.append(self.task) tasks.extend(x.task for x in self.subtasks) finished = asyncio.gather(*tasks, return_exceptions=True) outcomes = [] try: outcomes = await asyncio.wait_for(finished, timeout=self._stop_timeout) except asyncio.TimeoutError as err: # See discussion here: https://github.com/python/asyncio/issues/253#issuecomment-120138132 # This prevents a nuisance log error message, finished is guaranteed # to be cancelled but not awaited when wait_for() has a timeout. try: outcomes = await finished except asyncio.CancelledError: pass # See https://mail.python.org/pipermail/python-3000/2008-May/013740.html # for why we need to explictly name the error here raise err finally: self.stopped = True for outcome in outcomes: if isinstance(outcome, Exception) and not isinstance(outcome, asyncio.CancelledError): self._logger.error(outcome) if self in self._loop.tasks: self._loop.tasks.remove(self)
[ "Stop this task and wait until it and all its subtasks end.\n\n This function will finalize this task either by using the finalizer\n function passed during creation or by calling task.cancel() if no\n finalizer was passed.\n\n It will then call join() on this task and any registered subtasks\n with the given maximum timeout, raising asyncio.TimeoutError if\n the tasks did not exit within the given timeout.\n\n This method should only be called once.\n\n After this method returns, the task is finished and no more subtasks\n can be added. If this task is being tracked inside of the\n BackgroundEventLoop that it is part of, it will automatically be\n removed from the event loop's list of tasks.\n " ]
Please provide a description of the function:def stop_threadsafe(self): if self.stopped: return try: self._loop.run_coroutine(self.stop()) except asyncio.TimeoutError: raise TimeoutExpiredError("Timeout stopping task {} with {} subtasks".format(self.name, len(self.subtasks)))
[ "Stop this task from another thread and wait for it to finish.\n\n This method must not be called from within the BackgroundEventLoop but\n will inject self.stop() into the event loop and block until it\n returns.\n\n Raises:\n TimeoutExpiredError: If the task does not stop in the given\n timeout specified in __init__()\n " ]
Please provide a description of the function:def start(self, aug='EventLoopThread'): if self.stopping: raise LoopStoppingError("Cannot perform action while loop is stopping.") if not self.loop: self._logger.debug("Starting event loop") self.loop = asyncio.new_event_loop() self.thread = threading.Thread(target=self._loop_thread_main, name=aug, daemon=True) self.thread.start()
[ "Ensure the background loop is running.\n\n This method is safe to call multiple times. If the loop is already\n running, it will not do anything.\n " ]
Please provide a description of the function:def wait_for_interrupt(self, check_interval=1.0, max_time=None): self.start() wait = max(check_interval, 0.01) accum = 0 try: while max_time is None or accum < max_time: try: time.sleep(wait) except IOError: pass # IOError comes when this call is interrupted in a signal handler accum += wait except KeyboardInterrupt: pass
[ "Run the event loop until we receive a ctrl-c interrupt or max_time passes.\n\n This method will wake up every 1 second by default to check for any\n interrupt signals or if the maximum runtime has expired. This can be\n set lower for testing purpose to reduce latency but in production\n settings, this can cause increased CPU usage so 1 second is an\n appropriate value.\n\n Args:\n check_interval (float): How often to wake up and check for\n a SIGTERM. Defaults to 1s. Setting this faster is useful\n for unit testing. Cannot be < 0.01 s.\n max_time (float): Stop the event loop after max_time seconds.\n This is useful for testing purposes. Defaults to None,\n which means run forever until interrupt.\n " ]
Please provide a description of the function:def stop(self): if not self.loop: return if self.inside_loop(): raise InternalError("BackgroundEventLoop.stop() called from inside event loop; " "would have deadlocked.") try: self.run_coroutine(self._stop_internal()) self.thread.join() except: self._logger.exception("Error stopping BackgroundEventLoop") raise finally: self.thread = None self.loop = None self.tasks = set()
[ "Synchronously stop the background loop from outside.\n\n This method will block until the background loop is completely stopped\n so it cannot be called from inside the loop itself.\n\n This method is safe to call multiple times. If the loop is not\n currently running it will return without doing anything.\n " ]
Please provide a description of the function:async def _stop_internal(self): # Make sure we only try to stop once if self.stopping is True: return self.stopping = True awaitables = [task.stop() for task in self.tasks] results = await asyncio.gather(*awaitables, return_exceptions=True) for task, result in zip(self.tasks, results): if isinstance(result, Exception): self._logger.error("Error stopping task %s: %s", task.name, repr(result)) # It is important to defer this call by one loop cycle so # that this coroutine is finalized and anyone blocking on it # resumes execution. self.loop.call_soon(self.loop.stop)
[ "Cleanly stop the event loop after shutting down all tasks." ]
Please provide a description of the function:def _loop_thread_main(self): asyncio.set_event_loop(self.loop) self._loop_check.inside_loop = True try: self._logger.debug("Starting loop in background thread") self.loop.run_forever() self._logger.debug("Finished loop in background thread") except: # pylint:disable=bare-except;This is a background worker thread. self._logger.exception("Exception raised from event loop thread") finally: self.loop.close()
[ "Main background thread running the event loop." ]
Please provide a description of the function:def add_task(self, cor, name=None, finalizer=None, stop_timeout=1.0, parent=None): if self.stopping: raise LoopStoppingError("Cannot add task because loop is stopping") # Ensure the loop exists and is started self.start() if parent is not None and parent not in self.tasks: raise ArgumentError("Designated parent task {} is not registered".format(parent)) task = BackgroundTask(cor, name, finalizer, stop_timeout, loop=self) if parent is None: self.tasks.add(task) self._logger.debug("Added primary task %s", task.name) else: parent.add_subtask(task) self._logger.debug("Added subtask %s to parent %s", task.name, parent.name) return task
[ "Schedule a task to run on the background event loop.\n\n This method will start the given coroutine as a task and keep track\n of it so that it can be properly shutdown which the event loop is\n stopped.\n\n If parent is None, the task will be stopped by calling finalizer()\n inside the event loop and then awaiting the task. If finalizer is\n None then task.cancel() will be called to stop the task. If finalizer\n is specified, it is called with a single argument (self, this\n BackgroundTask). Finalizer can be a simple function, or any\n awaitable. If it is an awaitable it will be awaited.\n\n If parent is not None, it must be a BackgroundTask object previously\n created by a call to BackgroundEventLoop.add_task() and this task will be\n registered as a subtask of that task. It is that task's job then to\n cancel this task or otherwise stop it when it is stopped.\n\n This method is safe to call either from inside the event loop itself\n or from any other thread without fear of deadlock or race.\n\n Args:\n cor (coroutine or asyncio.Task): An asyncio Task or the coroutine\n that we should execute as a task. If a coroutine is given\n it is scheduled as a task in threadsafe manner automatically.\n name (str): The name of the task for pretty printing and debug\n purposes. If not specified, it defaults to the underlying\n asyncio task object instance name.\n finalizer (callable): An optional callable that should be\n invoked to cancel the task. If not specified, calling stop()\n will result in cancel() being called on the underlying task.\n\n\n stop_timeout (float): The maximum amount of time to wait for this\n task to stop when stop() is called in seconds. None indicates\n an unlimited amount of time. Default is 1.\n\n This is ignored if parent is not None.\n parent (BackgroundTask): A previously created task that will take\n responsibility for stopping this task when it is stopped.\n\n Returns:\n BackgroundTask: The BackgroundTask representing this task.\n " ]
Please provide a description of the function:def run_coroutine(self, cor, *args, **kwargs): if self.stopping: raise LoopStoppingError("Could not launch coroutine because loop is shutting down: %s" % cor) self.start() cor = _instaniate_coroutine(cor, args, kwargs) if self.inside_loop(): raise InternalError("BackgroundEventLoop.run_coroutine called from inside event loop, " "would have deadlocked.") future = self.launch_coroutine(cor) return future.result()
[ "Run a coroutine to completion and return its result.\n\n This method may only be called outside of the event loop.\n Attempting to call it from inside the event loop would deadlock\n and will raise InternalError instead.\n\n Args:\n cor (coroutine): The coroutine that we wish to run in the\n background and wait until it finishes.\n\n Returns:\n object: Whatever the coroutine cor returns.\n " ]
Please provide a description of the function:def launch_coroutine(self, cor, *args, **kwargs): if self.stopping: raise LoopStoppingError("Could not launch coroutine because loop is shutting down: %s" % cor) # Ensure the loop exists and is started self.start() cor = _instaniate_coroutine(cor, args, kwargs) if self.inside_loop(): return asyncio.ensure_future(cor, loop=self.loop) return asyncio.run_coroutine_threadsafe(cor, loop=self.loop)
[ "Start a coroutine task and return a blockable/awaitable object.\n\n If this method is called from inside the event loop, it will return an\n awaitable object. If it is called from outside the event loop it will\n return an concurrent Future object that can block the calling thread\n until the operation is finished.\n\n Args:\n cor (coroutine): The coroutine that we wish to run in the\n background and wait until it finishes.\n\n Returns:\n Future or asyncio.Task: A future representing the coroutine.\n\n If this method is called from within the background loop\n then an awaitable asyncio.Tasks is returned. Otherwise,\n a concurrent Future object is returned that you can call\n ``result()`` on to block the calling thread.\n " ]
Please provide a description of the function:def log_coroutine(self, cor, *args, **kwargs): if self.stopping: raise LoopStoppingError("Could not launch coroutine because loop is shutting down: %s" % cor) self.start() cor = _instaniate_coroutine(cor, args, kwargs) def _run_and_log(): task = self.loop.create_task(cor) task.add_done_callback(lambda x: _log_future_exception(x, self._logger)) if self.inside_loop(): _run_and_log() else: self.loop.call_soon_threadsafe(_run_and_log)
[ "Run a coroutine logging any exception raised.\n\n This routine will not block until the coroutine is finished\n nor will it return any result. It will just log if any\n exception is raised by the coroutine during operation.\n\n It is safe to call from both inside and outside the event loop.\n\n There is no guarantee on how soon the coroutine will be scheduled.\n\n Args:\n cor (coroutine): The coroutine that we wish to run in the\n background and wait until it finishes.\n " ]
Please provide a description of the function:def link_cloud(self, username=None, password=None, device_id=None): reg = ComponentRegistry() domain = self.get('cloud:server') if username is None: prompt_str = "Please enter your IOTile.cloud email: " username = input(prompt_str) if password is None: prompt_str = "Please enter your IOTile.cloud password: " password = getpass.getpass(prompt_str) cloud = Api(domain=domain) ok_resp = cloud.login(email=username, password=password) if not ok_resp: raise ArgumentError("Could not login to iotile.cloud as user %s" % username) reg.set_config('arch:cloud_user', cloud.username) reg.set_config('arch:cloud_token', cloud.token) reg.set_config('arch:cloud_token_type', cloud.token_type) if device_id is not None: cloud = IOTileCloud() cloud.impersonate_device(device_id)
[ "Create and store a token for interacting with the IOTile Cloud API.\n\n You will need to call link_cloud once for each virtualenv that\n you create and want to use with any api calls that touch iotile cloud.\n\n Note that this method is called on a ConfigManager instance\n\n If you do not pass your username or password it will be prompted from\n you securely on stdin.\n\n If you are logging in for a user, the token will expire periodically and you\n will have to relogin.\n\n If you pass a device_id, you can obtain a limited token for that device\n that will never expire, assuming you have access to that device.\n\n Args:\n username (string): Your iotile.cloud username. This is prompted\n from stdin if not provided.\n password (string): Your iotile.cloud password. This is prompted\n from stdin if not provided.\n device_id (int): Optional device id to obtain permanent credentials\n for a device.\n " ]
Please provide a description of the function:def _load_file(self): if not os.path.exists(self.file): return {} with open(self.file, "r") as infile: data = json.load(infile) return data
[ "Load all entries from json backing file\n " ]