_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q238700 | SparseMemory._create_slice | train | def _create_slice(self, key):
"""Create a slice in a memory segment corresponding to a key."""
if isinstance(key, slice):
step = key.step
if step is None:
step = 1
if step != 1:
raise ArgumentError("You cannot slice with a step that i... | python | {
"resource": ""
} |
q238701 | SparseMemory._classify_segment | train | def _classify_segment(self, address, length):
"""Determine how a new data segment fits into our existing world
Params:
address (int): The address we wish to classify
length (int): The length of the segment
Returns:
int: One of SparseMemoryMap.prepended
... | python | {
"resource": ""
} |
q238702 | generate | train | def generate(env):
"""Add Builders and construction variables for ifort to an Environment."""
# ifort supports Fortran 90 and Fortran 95
# Additionally, ifort recognizes more file extensions.
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.Sour... | python | {
"resource": ""
} |
q238703 | Jobs.run | train | def run(self, postfunc=lambda: None):
"""Run the jobs.
postfunc() will be invoked after the jobs has run. It will be
invoked even if the jobs are interrupted by a keyboard
interrupt (well, in fact by a signal such as either SIGINT,
SIGTERM or SIGHUP). The execution of postfunc()... | python | {
"resource": ""
} |
q238704 | ConnectionAction.expired | train | def expired(self):
"""Boolean property if this action has expired
"""
if self.timeout is None:
return False
return monotonic() - self.start_time > self.timeout | python | {
"resource": ""
} |
q238705 | ConnectionManager.begin_connection | train | def begin_connection(self, connection_id, internal_id, callback, context, timeout):
"""Asynchronously begin a connection attempt
Args:
connection_id (int): The external connection id
internal_id (string): An internal identifier for the connection
callback (callable):... | python | {
"resource": ""
} |
q238706 | ConnectionManager.begin_operation | train | def begin_operation(self, conn_or_internal_id, op_name, callback, timeout):
"""Begin an operation on a connection
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
op_name (string): The name of the operation that we ... | python | {
"resource": ""
} |
q238707 | ConnectionManager._begin_operation_action | train | def _begin_operation_action(self, action):
"""Begin an attempted operation.
Args:
action (ConnectionAction): the action object describing what we are
operating on
"""
conn_key = action.data['id']
callback = action.data['callback']
if self._g... | python | {
"resource": ""
} |
q238708 | AsyncValidatingWSClient.allow_exception | train | def allow_exception(self, exc_class):
"""Allow raising this class of exceptions from commands.
When a command fails on the server side due to an exception, by
default it is turned into a string and raised on the client side as an
ExternalError. The original class name is sent but ignor... | python | {
"resource": ""
} |
q238709 | AsyncValidatingWSClient.start | train | async def start(self, name="websocket_client"):
"""Connect to the websocket server.
This method will spawn a background task in the designated event loop
that will run until stop() is called. You can control the name of the
background task for debugging purposes using the name paramete... | python | {
"resource": ""
} |
q238710 | AsyncValidatingWSClient.stop | train | async def stop(self):
"""Stop this websocket client and disconnect from the server.
This method is idempotent and may be called multiple times. If called
when there is no active connection, it will simply return.
"""
if self._connection_task is None:
return
... | python | {
"resource": ""
} |
q238711 | AsyncValidatingWSClient.send_command | train | async def send_command(self, command, args, validator, timeout=10.0):
"""Send a command and synchronously wait for a single response.
Args:
command (string): The command name
args (dict): Optional arguments.
validator (Verifier): A SchemaVerifier to verify the respon... | python | {
"resource": ""
} |
q238712 | AsyncValidatingWSClient._manage_connection | train | async def _manage_connection(self):
"""Internal coroutine for managing the client connection."""
try:
while True:
message = await self._con.recv()
try:
unpacked = unpack(message)
except Exception: # pylint:disable=broad-e... | python | {
"resource": ""
} |
q238713 | AsyncValidatingWSClient.register_event | train | def register_event(self, name, callback, validator):
"""Register a callback to receive events.
Every event with the matching name will have its payload validated
using validator and then will be passed to callback if validation
succeeds.
Callback must be a normal callback funct... | python | {
"resource": ""
} |
q238714 | AsyncValidatingWSClient.post_command | train | def post_command(self, command, args):
"""Post a command asynchronously and don't wait for a response.
There is no notification of any error that could happen during
command execution. A log message will be generated if an error
occurred. The command's response is discarded.
... | python | {
"resource": ""
} |
q238715 | copy_all_a | train | def copy_all_a(input_a, *other_inputs, **kwargs):
"""Copy all readings in input a into the output.
All other inputs are skipped so that after this function runs there are no
readings left in any of the input walkers when the function finishes, even
if it generated no output readings.
Returns:
... | python | {
"resource": ""
} |
q238716 | copy_count_a | train | def copy_count_a(input_a, *other_inputs, **kwargs):
"""Copy the latest reading from input a into the output.
All other inputs are skipped to that after this function
runs there are no readings left in any of the input walkers
even if no output is generated.
Returns:
list(IOTileReading)
... | python | {
"resource": ""
} |
q238717 | call_rpc | train | def call_rpc(*inputs, **kwargs):
"""Call an RPC based on the encoded value read from input b.
The response of the RPC must be a 4 byte value that is used as
the output of this call. The encoded RPC must be a 32 bit value
encoded as "BBH":
B: ignored, should be 0
B: the address of the t... | python | {
"resource": ""
} |
q238718 | trigger_streamer | train | def trigger_streamer(*inputs, **kwargs):
"""Trigger a streamer based on the index read from input b.
Returns:
list(IOTileReading)
"""
streamer_marker = kwargs['mark_streamer']
try:
reading = inputs[1].pop()
except StreamEmptyError:
return []
finally:
for in... | python | {
"resource": ""
} |
q238719 | subtract_afromb | train | def subtract_afromb(*inputs, **kwargs):
"""Subtract stream a from stream b.
Returns:
list(IOTileReading)
"""
try:
value_a = inputs[0].pop()
value_b = inputs[1].pop()
return [IOTileReading(0, 0, value_b.value - value_a.value)]
except StreamEmptyError:
return... | python | {
"resource": ""
} |
q238720 | _clean_intenum | train | def _clean_intenum(obj):
"""Remove all IntEnum classes from a map."""
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(va... | python | {
"resource": ""
} |
q238721 | EmulationMixin._track_change | train | def _track_change(self, name, value, formatter=None):
"""Track that a change happened.
This function is only needed for manually recording changes that are
not captured by changes to properties of this object that are tracked
automatically. Classes that inherit from `emulation_mixin` s... | python | {
"resource": ""
} |
q238722 | EmulationMixin.save_state | train | def save_state(self, out_path):
"""Save the current state of this emulated object to a file.
Args:
out_path (str): The path to save the dumped state of this emulated
object.
"""
state = self.dump_state()
# Remove all IntEnums from state since they c... | python | {
"resource": ""
} |
q238723 | EmulationMixin.load_state | train | def load_state(self, in_path):
"""Load the current state of this emulated object from a file.
The file should have been produced by a previous call to save_state.
Args:
in_path (str): The path to the saved state dump that you wish
to load.
"""
with ... | python | {
"resource": ""
} |
q238724 | EmulationMixin.load_scenario | train | def load_scenario(self, scenario_name, **kwargs):
"""Load a scenario into the emulated object.
Scenarios are specific states of an an object that can be customized
with keyword parameters. Typical examples are:
- data logger with full storage
- device with low battery indi... | python | {
"resource": ""
} |
q238725 | EmulationMixin.register_scenario | train | def register_scenario(self, scenario_name, handler):
"""Register a scenario handler for this object.
Scenario handlers are callable functions with no positional arguments
that can be called by name with the load_scenario function and should
prepare the emulated object into a known state... | python | {
"resource": ""
} |
q238726 | generate | train | def generate(env):
"""Add Builders and construction variables for aCC & cc to an Environment."""
cc.generate(env)
env['CXX'] = 'aCC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS +Z') | python | {
"resource": ""
} |
q238727 | SensorGraphOptimizer.add_pass | train | def add_pass(self, name, opt_pass, before=None, after=None):
"""Add an optimization pass to the optimizer.
Optimization passes have a name that allows them
to be enabled or disabled by name. By default all
optimization passed are enabled and unordered. You can
explicitly speci... | python | {
"resource": ""
} |
q238728 | SensorGraphOptimizer._order_pases | train | def _order_pases(self, passes):
"""Topologically sort optimization passes.
This ensures that the resulting passes are run in order
respecting before/after constraints.
Args:
passes (iterable): An iterable of pass names that should
be included in the optimiza... | python | {
"resource": ""
} |
q238729 | SensorGraphOptimizer.optimize | train | def optimize(self, sensor_graph, model):
"""Optimize a sensor graph by running optimization passes.
The passes are run one at a time and modify the sensor graph
for future passes.
Args:
sensor_graph (SensorGraph): The graph to be optimized
model (DeviceModel): T... | python | {
"resource": ""
} |
q238730 | get_calling_namespaces | train | def get_calling_namespaces():
"""Return the locals and globals for the function that called
into this module in the current call stack."""
try: 1//0
except ZeroDivisionError:
# Don't start iterating with the current stack-frame to
# prevent creating reference cycles (f_back is safe).
... | python | {
"resource": ""
} |
q238731 | annotate | train | def annotate(node):
"""Annotate a node with the stack frame describing the
SConscript file and line number that created it."""
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: wh... | python | {
"resource": ""
} |
q238732 | BuildDefaultGlobals | train | def BuildDefaultGlobals():
"""
Create a dictionary containing all the default globals for
SConstruct and SConscript files.
"""
global GlobalDict
if GlobalDict is None:
GlobalDict = {}
import SCons.Script
d = SCons.Script.__dict__
def not_a_module(m, d=d, mtype=t... | python | {
"resource": ""
} |
q238733 | SConsEnvironment._exceeds_version | train | def _exceeds_version(self, major, minor, v_major, v_minor):
"""Return 1 if 'major' and 'minor' are greater than the version
in 'v_major' and 'v_minor', and 0 otherwise."""
return (major > v_major or (major == v_major and minor > v_minor)) | python | {
"resource": ""
} |
q238734 | SConsEnvironment.EnsureSConsVersion | train | def EnsureSConsVersion(self, major, minor, revision=0):
"""Exit abnormally if the SCons version is not late enough."""
# split string to avoid replacement during build process
if SCons.__version__ == '__' + 'VERSION__':
SCons.Warnings.warn(SCons.Warnings.DevelopmentVersionWarning,
... | python | {
"resource": ""
} |
q238735 | SConsEnvironment.EnsurePythonVersion | train | def EnsurePythonVersion(self, major, minor):
"""Exit abnormally if the Python version is not late enough."""
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) | python | {
"resource": ""
} |
q238736 | validate_vars | train | def validate_vars(env):
"""Validate the PCH and PCHSTOP construction variables."""
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']):
... | python | {
"resource": ""
} |
q238737 | msvc_set_PCHPDBFLAGS | train | def msvc_set_PCHPDBFLAGS(env):
"""
Set appropriate PCHPDBFLAGS for the MSVC version being used.
"""
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 ""}'])
... | python | {
"resource": ""
} |
q238738 | pch_emitter | train | def pch_emitter(target, source, env):
"""Adds the object file target."""
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:
... | python | {
"resource": ""
} |
q238739 | object_emitter | train | def object_emitter(target, source, env, parent_emitter):
"""Sets up the PCH dependencies for an object file."""
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').
... | python | {
"resource": ""
} |
q238740 | msvc_batch_key | train | def msvc_batch_key(action, env, target, source):
"""
Returns a key to identify unique batches of sources for compilation.
If batching is enabled (via the $MSVC_BATCH setting), then all
target+source pairs that use the same action, defined by the same
environment, and have the same target and source... | python | {
"resource": ""
} |
q238741 | generate | train | def generate(env):
"""Add Builders and construction variables for MSVC++ to an Environment."""
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 allo... | python | {
"resource": ""
} |
q238742 | HardwareManagerResource.open | train | def open(self):
"""Open and potentially connect to a device."""
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:... | python | {
"resource": ""
} |
q238743 | HardwareManagerResource.close | train | def close(self):
"""Close and potentially disconnect from a device."""
if self.hwman.stream.connected:
self.hwman.disconnect()
self.hwman.close()
self.opened = False | python | {
"resource": ""
} |
q238744 | get_support_package | train | def get_support_package(tile):
"""Returns the support_package product."""
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... | python | {
"resource": ""
} |
q238745 | iter_support_files | train | def iter_support_files(tile):
"""Iterate over all files that go in the support wheel.
This method has two possible behaviors. If there is a 'support_package'
product defined, then this recursively enumerates all .py files inside
that folder and adds them all in the same hierarchy to the support wheel.... | python | {
"resource": ""
} |
q238746 | iter_python_modules | train | def iter_python_modules(tile):
"""Iterate over all python products in the given tile.
This will yield tuples where the first entry is the path to the module
containing the product the second entry is the appropriate
import string to include in an entry point, and the third entry is
the entry point ... | python | {
"resource": ""
} |
q238747 | generate_setup_py | train | def generate_setup_py(target, source, env):
"""Generate the setup.py file for this distribution."""
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] =... | python | {
"resource": ""
} |
q238748 | defaultMachine | train | def defaultMachine(use_rpm_default=True):
""" Return the canonicalized machine name. """
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()
r... | python | {
"resource": ""
} |
q238749 | defaultSystem | train | def defaultSystem():
""" Return the canonicalized system name. """
rsystem = platform.system()
# Try to lookup the string in the canon tables
if rsystem in os_canon:
rsystem = os_canon[rsystem][0]
return rsystem | python | {
"resource": ""
} |
q238750 | Task.prepare | train | def prepare(self):
"""
Called just before the task is executed.
This is mainly intended to give the target Nodes a chance to
unlink underlying files and make all necessary directories before
the Action is actually called to build the targets.
"""
global print_pre... | python | {
"resource": ""
} |
q238751 | Task.execute | train | def execute(self):
"""
Called to execute the task.
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff in
prepare(), executed() or failed().
"""
T = self.tm.trace
if T: T.write(self.t... | python | {
"resource": ""
} |
q238752 | Task.executed_without_callbacks | train | def executed_without_callbacks(self):
"""
Called when the task has been successfully executed
and the Taskmaster instance doesn't want to call
the Node's callback methods.
"""
T = self.tm.trace
if T: T.write(self.trace_message('Task.executed_without_callbacks()',
... | python | {
"resource": ""
} |
q238753 | Task.executed_with_callbacks | train | def executed_with_callbacks(self):
"""
Called when the task has been successfully executed and
the Taskmaster instance wants to call the Node's callback
methods.
This may have been a do-nothing operation (to preserve build
order), so we must check the node's state before... | python | {
"resource": ""
} |
q238754 | Task.fail_stop | train | def fail_stop(self):
"""
Explicit stop-the-build failure.
This sets failure status on the target nodes and all of
their dependent parent nodes.
Note: Although this function is normally invoked on nodes in
the executing state, it might also be invoked on up-to-date
... | python | {
"resource": ""
} |
q238755 | Task.fail_continue | train | def fail_continue(self):
"""
Explicit continue-the-build failure.
This sets failure status on the target nodes and all of
their dependent parent nodes.
Note: Although this function is normally invoked on nodes in
the executing state, it might also be invoked on up-to-da... | python | {
"resource": ""
} |
q238756 | Task.make_ready_all | train | def make_ready_all(self):
"""
Marks all targets in a task ready for execution.
This is used when the interface needs every target Node to be
visited--the canonical example being the "scons -c" option.
"""
T = self.tm.trace
if T: T.write(self.trace_message('Task.m... | python | {
"resource": ""
} |
q238757 | Task.make_ready_current | train | def make_ready_current(self):
"""
Marks all targets in a task ready for execution if any target
is not current.
This is the default behavior for building only what's necessary.
"""
global print_prepare
T = self.tm.trace
if T: T.write(self.trace_message(u'... | python | {
"resource": ""
} |
q238758 | Task.postprocess | train | def postprocess(self):
"""
Post-processes a task after it's been executed.
This examines all the targets just built (or not, we don't care
if the build was successful, or even if there was no build
because everything was up-to-date) to see if they have any
waiting parent... | python | {
"resource": ""
} |
q238759 | Task.exception_set | train | def exception_set(self, exception=None):
"""
Records an exception to be raised at the appropriate time.
This also changes the "exception_raise" attribute to point
to the method that will, in fact
"""
if not exception:
exception = sys.exc_info()
self.e... | python | {
"resource": ""
} |
q238760 | Task._exception_raise | train | def _exception_raise(self):
"""
Raises a pending exception that was recorded while getting a
Task ready for execution.
"""
exc = self.exc_info()[:]
try:
exc_type, exc_value, exc_traceback = exc
except ValueError:
exc_type, exc_value = exc
... | python | {
"resource": ""
} |
q238761 | Taskmaster.no_next_candidate | train | def no_next_candidate(self):
"""
Stops Taskmaster processing by not returning a next candidate.
Note that we have to clean-up the Taskmaster candidate list
because the cycle detection depends on the fact all nodes have
been processed somehow.
"""
while self.candi... | python | {
"resource": ""
} |
q238762 | Taskmaster._validate_pending_children | train | def _validate_pending_children(self):
"""
Validate the content of the pending_children set. Assert if an
internal error is found.
This function is used strictly for debugging the taskmaster by
checking that no invariants are violated. It is not used in
normal operation.
... | python | {
"resource": ""
} |
q238763 | Taskmaster.next_task | train | def next_task(self):
"""
Returns the next task to be executed.
This simply asks for the next Node to be evaluated, and then wraps
it in the specific Task subclass with which we were initialized.
"""
node = self._find_next_ready_node()
if node is None:
... | python | {
"resource": ""
} |
q238764 | Taskmaster.cleanup | train | def cleanup(self):
"""
Check for dependency cycles.
"""
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 n... | python | {
"resource": ""
} |
q238765 | DependencyResolverChain.instantiate_resolver | train | def instantiate_resolver(self, name, args):
"""Directly instantiate a dependency resolver by name with the given arguments
Args:
name (string): The name of the class that we want to instantiate
args (dict): The arguments to pass to the resolver factory
Returns:
... | python | {
"resource": ""
} |
q238766 | DependencyResolverChain.pull_release | train | def pull_release(self, name, version, destfolder=".", force=False):
"""Download and unpack a released iotile component by name and version range
If the folder that would be created already exists, this command fails unless
you pass force=True
Args:
name (string): The name o... | python | {
"resource": ""
} |
q238767 | DependencyResolverChain.update_dependency | train | def update_dependency(self, tile, depinfo, destdir=None):
"""Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the depe... | python | {
"resource": ""
} |
q238768 | DependencyResolverChain._check_dep | train | def _check_dep(self, depinfo, deptile, resolver):
"""Check if a dependency tile is up to date
Returns:
bool: True if it is up to date, False if it not and None if this resolver
cannot assess whether or not it is up to date.
"""
try:
settings = se... | python | {
"resource": ""
} |
q238769 | _log_future_exception | train | def _log_future_exception(future, logger):
"""Log any exception raised by future."""
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=Tru... | python | {
"resource": ""
} |
q238770 | BackgroundTask.create_subtask | train | def create_subtask(self, cor, name=None, stop_timeout=1.0):
"""Create and add a subtask from a coroutine.
This function will create a BackgroundTask and then
call self.add_subtask() on it.
Args:
cor (coroutine): The coroutine that should be wrapped
in a back... | python | {
"resource": ""
} |
q238771 | BackgroundTask.add_subtask | train | def add_subtask(self, subtask):
"""Link a subtask to this parent task.
This will cause stop() to block until the subtask has also
finished. Calling stop will not directly cancel the subtask.
It is expected that your finalizer for this parent task will
cancel or otherwise stop t... | python | {
"resource": ""
} |
q238772 | BackgroundTask.stop | train | async def stop(self):
"""Stop this task and wait until it and all its subtasks end.
This function will finalize this task either by using the finalizer
function passed during creation or by calling task.cancel() if no
finalizer was passed.
It will then call join() on this task ... | python | {
"resource": ""
} |
q238773 | BackgroundTask.stop_threadsafe | train | def stop_threadsafe(self):
"""Stop this task from another thread and wait for it to finish.
This method must not be called from within the BackgroundEventLoop but
will inject self.stop() into the event loop and block until it
returns.
Raises:
TimeoutExpiredError: If... | python | {
"resource": ""
} |
q238774 | BackgroundEventLoop.start | train | def start(self, aug='EventLoopThread'):
"""Ensure the background loop is running.
This method is safe to call multiple times. If the loop is already
running, it will not do anything.
"""
if self.stopping:
raise LoopStoppingError("Cannot perform action while loop is... | python | {
"resource": ""
} |
q238775 | BackgroundEventLoop.wait_for_interrupt | train | def wait_for_interrupt(self, check_interval=1.0, max_time=None):
"""Run the event loop until we receive a ctrl-c interrupt or max_time passes.
This method will wake up every 1 second by default to check for any
interrupt signals or if the maximum runtime has expired. This can be
set lo... | python | {
"resource": ""
} |
q238776 | BackgroundEventLoop.stop | train | def stop(self):
"""Synchronously stop the background loop from outside.
This method will block until the background loop is completely stopped
so it cannot be called from inside the loop itself.
This method is safe to call multiple times. If the loop is not
currently running i... | python | {
"resource": ""
} |
q238777 | BackgroundEventLoop._stop_internal | train | async def _stop_internal(self):
"""Cleanly stop the event loop after shutting down all tasks."""
# 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 asy... | python | {
"resource": ""
} |
q238778 | BackgroundEventLoop._loop_thread_main | train | def _loop_thread_main(self):
"""Main background thread running the event loop."""
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... | python | {
"resource": ""
} |
q238779 | BackgroundEventLoop.add_task | train | def add_task(self, cor, name=None, finalizer=None, stop_timeout=1.0, parent=None):
"""Schedule a task to run on the background event loop.
This method will start the given coroutine as a task and keep track
of it so that it can be properly shutdown which the event loop is
stopped.
... | python | {
"resource": ""
} |
q238780 | BackgroundEventLoop.run_coroutine | train | def run_coroutine(self, cor, *args, **kwargs):
"""Run a coroutine to completion and return its result.
This method may only be called outside of the event loop.
Attempting to call it from inside the event loop would deadlock
and will raise InternalError instead.
Args:
... | python | {
"resource": ""
} |
q238781 | BackgroundEventLoop.log_coroutine | train | def log_coroutine(self, cor, *args, **kwargs):
"""Run a coroutine logging any exception raised.
This routine will not block until the coroutine is finished
nor will it return any result. It will just log if any
exception is raised by the coroutine during operation.
It is safe ... | python | {
"resource": ""
} |
q238782 | link_cloud | train | def link_cloud(self, username=None, password=None, device_id=None):
"""Create and store a token for interacting with the IOTile Cloud API.
You will need to call link_cloud once for each virtualenv that
you create and want to use with any api calls that touch iotile cloud.
Note that this method is call... | python | {
"resource": ""
} |
q238783 | JSONKVStore._load_file | train | def _load_file(self):
"""Load all entries from json backing file
"""
if not os.path.exists(self.file):
return {}
with open(self.file, "r") as infile:
data = json.load(infile)
return data | python | {
"resource": ""
} |
q238784 | JSONKVStore._save_file | train | def _save_file(self, data):
"""Attempt to atomically save file by saving and then moving into position
The goal is to make it difficult for a crash to corrupt our data file since
the move operation can be made atomic if needed on mission critical filesystems.
"""
if platform.sy... | python | {
"resource": ""
} |
q238785 | JSONKVStore.remove | train | def remove(self, key):
"""Remove a key from the data store
Args:
key (string): The key to remove
Raises:
KeyError: if the key was not found
"""
data = self._load_file()
del data[key]
self._save_file(data) | python | {
"resource": ""
} |
q238786 | JSONKVStore.set | train | def set(self, key, value):
"""Set the value of a key
Args:
key (string): The key used to store this value
value (string): The value to store
"""
data = self._load_file()
data[key] = value
self._save_file(data) | python | {
"resource": ""
} |
q238787 | TriggerScope.trigger_chain | train | def trigger_chain(self):
"""Return a NodeInput tuple for creating a node.
Returns:
(StreamIdentifier, InputTrigger)
"""
trigger_stream = self.allocator.attach_stream(self.trigger_stream)
return (trigger_stream, self.trigger_cond) | python | {
"resource": ""
} |
q238788 | generate | train | def generate(env):
"""
Add Builders and construction variables for C compilers to an Environment.
"""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Default... | python | {
"resource": ""
} |
q238789 | process_mock_rpc | train | def process_mock_rpc(input_string):
"""Process a mock RPC argument.
Args:
input_string (str): The input string that should be in the format
<slot id>:<rpc id> = value
"""
spec, equals, value = input_string.partition(u'=')
if len(equals) == 0:
print("Could not parse moc... | python | {
"resource": ""
} |
q238790 | watch_printer | train | def watch_printer(watch, value):
"""Print a watched value.
Args:
watch (DataStream): The stream that was watched
value (IOTileReading): The value to was seen
"""
print("({: 8} s) {}: {}".format(value.raw_time, watch, value.value)) | python | {
"resource": ""
} |
q238791 | main | train | def main(argv=None):
"""Main entry point for iotile sensorgraph simulator.
This is the iotile-sgrun command line program. It takes
an optional set of command line parameters to allow for
testing.
Args:
argv (list of str): An optional set of command line
parameters. If not pas... | python | {
"resource": ""
} |
q238792 | VerifyDeviceStep._verify_tile_versions | train | def _verify_tile_versions(self, hw):
"""Verify that the tiles have the correct versions
"""
for tile, expected_tile_version in self._tile_versions.items():
actual_tile_version = str(hw.get(tile).tile_version())
if expected_tile_version != actual_tile_version:
... | python | {
"resource": ""
} |
q238793 | VerifyDeviceStep._verify_realtime_streams | train | def _verify_realtime_streams(self, hw):
"""Check that the realtime streams are being produced
"""
print("--> Testing realtime data (takes 2 seconds)")
time.sleep(2.1)
reports = [x for x in hw.iter_reports()]
reports_seen = {key: 0 for key in self._realtime_streams}
... | python | {
"resource": ""
} |
q238794 | _update_pot_file | train | def _update_pot_file(target, source, env):
""" Action function for `POTUpdate` builder """
import re
import os
import SCons.Action
nop = lambda target, source, env: 0
# Save scons cwd and os cwd (NOTE: they may be different. After the job, we
# revert each one to its original state).
sa... | python | {
"resource": ""
} |
q238795 | _scan_xgettext_from_files | train | def _scan_xgettext_from_files(target, source, env, files=None, path=None):
""" Parses `POTFILES.in`-like file and returns list of extracted file names.
"""
import re
import SCons.Util
import SCons.Node.FS
if files is None:
return 0
if not SCons.Util.is_List(files):
files = [... | python | {
"resource": ""
} |
q238796 | _pot_update_emitter | train | def _pot_update_emitter(target, source, env):
""" Emitter function for `POTUpdate` builder """
from SCons.Tool.GettextCommon import _POTargetFactory
import SCons.Util
import SCons.Node.FS
if 'XGETTEXTFROM' in env:
xfrom = env['XGETTEXTFROM']
else:
return target, source
if no... | python | {
"resource": ""
} |
q238797 | _POTUpdateBuilder | train | def _POTUpdateBuilder(env, **kw):
""" Creates `POTUpdate` builder object """
import SCons.Action
from SCons.Tool.GettextCommon import _POTargetFactory
kw['action'] = SCons.Action.Action(_update_pot_file, None)
kw['suffix'] = '$POTSUFFIX'
kw['target_factory'] = _POTargetFactory(env, alias='$POTUP... | python | {
"resource": ""
} |
q238798 | generate | train | def generate(env, **kw):
""" Generate `xgettext` tool """
import SCons.Util
from SCons.Tool.GettextCommon import RPaths, _detect_xgettext
try:
env['XGETTEXT'] = _detect_xgettext(env)
except:
env['XGETTEXT'] = 'xgettext'
# NOTE: sources="$SOURCES" would work as well. However, we ... | python | {
"resource": ""
} |
q238799 | generate | train | def generate(env):
"""Add Builders and construction variables for gcc to an Environment."""
if 'CC' not in env:
env['CC'] = env.Detect(compilers) or compilers[0]
cc.generate(env)
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
else:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.