Code stringlengths 103 85.9k | Summary listlengths 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.execut... | [
"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_co... | [
"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 inform... |
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
}
... | [
"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 ... |
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 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 faile... |
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... | [
"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 progre... | [
"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_dis... | [
"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... |
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... | [
"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 ... |
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, connect... | [
"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 inste... |
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... |
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... | [
"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 ... |
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... | [
"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:
... | [
"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 nee... |
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 c... |
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)
... | [
"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 ... |
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:
... | [
"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')
... | [
"\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(v... | [
"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 c... |
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
... | [
"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))
s... | [
"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_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=se... | [
"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 eas... |
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 a... |
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 aft... | [
"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:
... | [
"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 ... |
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 firs... | [
"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:
r... | [
"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 actual... | [
"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 SCo... | [
"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... | [
"\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.... | [
"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")
... | [
"\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,
"En... | [
"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 ... |
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 SC... | [
"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['PCHPDB... | [
"\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 n... | [
"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 t... | [
"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
# anothe... | [
"\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 Ret... |
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... | [
"\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 wi... |
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 ... | [
"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:
... | [
"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 suppor... | [
"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 i... | [
"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 suppo... |
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... | [
"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] = []
... | [
"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()
rm... | [
" 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 secti... | [
" 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 encount... | [
"\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():
... | [
"\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_EX... | [
"\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... | [
"\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 \... |
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... | [
"\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... |
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 u... |
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)
... | [
"\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 = ... | [
"\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
... | [
"\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 waitin... |
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... | [
"\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 =... | [
"\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 th... |
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_paren... | [
"\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... |
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()
... | [
"\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).... |
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 ... | [
"\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:
... | [
"\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... | [
"\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:... | [
"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... |
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_... | [
"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 (SemanticVersionRan... |
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):... | [
"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 int... |
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 ... | [
"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... | [
"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)... | [
"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 ... |
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 Bac... | [
"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 ... |
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.isawaita... | [
"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 sub... |
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... | [
"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... |
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.n... | [
"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.sle... | [
"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 ... |
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:
... | [
"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 wi... |
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(*awaita... | [
"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(... | [
"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()
... | [
"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 in... |
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)
... | [
"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... |
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 ... | [
"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 un... |
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)
... | [
"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 ... |
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)
i... | [
"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 use... |
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 "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.