id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
240,800
google/openhtf
openhtf/plugs/usb/shell_service.py
AsyncCommandHandle._reader_thread_proc
def _reader_thread_proc(self, timeout): """Read until the stream is closed.""" for data in self.stream.read_until_close(timeout_ms=timeout): if self.stdout is not None: self.stdout.write(data)
python
def _reader_thread_proc(self, timeout): for data in self.stream.read_until_close(timeout_ms=timeout): if self.stdout is not None: self.stdout.write(data)
[ "def", "_reader_thread_proc", "(", "self", ",", "timeout", ")", ":", "for", "data", "in", "self", ".", "stream", ".", "read_until_close", "(", "timeout_ms", "=", "timeout", ")", ":", "if", "self", ".", "stdout", "is", "not", "None", ":", "self", ".", "...
Read until the stream is closed.
[ "Read", "until", "the", "stream", "is", "closed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L145-L149
240,801
google/openhtf
openhtf/plugs/usb/shell_service.py
AsyncCommandHandle.wait
def wait(self, timeout_ms=None): """Block until this command has completed. Args: timeout_ms: Timeout, in milliseconds, to wait. Returns: Output of the command if it complete and self.stdout is a StringIO object or was passed in as None. Returns True if the command completed but stdout was provided (and was not a StringIO object). Returns None if the timeout expired before the command completed. Be careful to check the return value explicitly for None, as the output may be ''. """ closed = timeouts.loop_until_timeout_or_true( timeouts.PolledTimeout.from_millis(timeout_ms), self.stream.is_closed, .1) if closed: if hasattr(self.stdout, 'getvalue'): return self.stdout.getvalue() return True return None
python
def wait(self, timeout_ms=None): closed = timeouts.loop_until_timeout_or_true( timeouts.PolledTimeout.from_millis(timeout_ms), self.stream.is_closed, .1) if closed: if hasattr(self.stdout, 'getvalue'): return self.stdout.getvalue() return True return None
[ "def", "wait", "(", "self", ",", "timeout_ms", "=", "None", ")", ":", "closed", "=", "timeouts", ".", "loop_until_timeout_or_true", "(", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", ",", "self", ".", "stream", ".", "is_closed...
Block until this command has completed. Args: timeout_ms: Timeout, in milliseconds, to wait. Returns: Output of the command if it complete and self.stdout is a StringIO object or was passed in as None. Returns True if the command completed but stdout was provided (and was not a StringIO object). Returns None if the timeout expired before the command completed. Be careful to check the return value explicitly for None, as the output may be ''.
[ "Block", "until", "this", "command", "has", "completed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L169-L189
240,802
google/openhtf
openhtf/plugs/usb/shell_service.py
ShellService.command
def command(self, command, raw=False, timeout_ms=None): """Run the given command and return the output.""" return ''.join(self.streaming_command(command, raw, timeout_ms))
python
def command(self, command, raw=False, timeout_ms=None): return ''.join(self.streaming_command(command, raw, timeout_ms))
[ "def", "command", "(", "self", ",", "command", ",", "raw", "=", "False", ",", "timeout_ms", "=", "None", ")", ":", "return", "''", ".", "join", "(", "self", ".", "streaming_command", "(", "command", ",", "raw", ",", "timeout_ms", ")", ")" ]
Run the given command and return the output.
[ "Run", "the", "given", "command", "and", "return", "the", "output", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L223-L225
240,803
google/openhtf
openhtf/plugs/usb/shell_service.py
ShellService.streaming_command
def streaming_command(self, command, raw=False, timeout_ms=None): """Run the given command and yield the output as we receive it.""" if raw: command = self._to_raw_command(command) return self.adb_connection.streaming_command('shell', command, timeout_ms)
python
def streaming_command(self, command, raw=False, timeout_ms=None): if raw: command = self._to_raw_command(command) return self.adb_connection.streaming_command('shell', command, timeout_ms)
[ "def", "streaming_command", "(", "self", ",", "command", ",", "raw", "=", "False", ",", "timeout_ms", "=", "None", ")", ":", "if", "raw", ":", "command", "=", "self", ".", "_to_raw_command", "(", "command", ")", "return", "self", ".", "adb_connection", "...
Run the given command and yield the output as we receive it.
[ "Run", "the", "given", "command", "and", "yield", "the", "output", "as", "we", "receive", "it", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L227-L231
240,804
google/openhtf
openhtf/plugs/usb/shell_service.py
ShellService.async_command
def async_command(self, command, stdin=None, stdout=None, raw=False, timeout_ms=None): """Run the given command on the device asynchronously. Input will be read from stdin, output written to stdout. ADB doesn't distinguish between stdout and stdin on the device, so they get interleaved into stdout here. stdin and stdout should be file-like objects, so you could use sys.stdin and sys.stdout to emulate the 'adb shell' commandline. Args: command: The command to run, will be run with /bin/sh -c 'command' on the device. stdin: File-like object to read from to pipe to the command's stdin. Can be None, in which case nothing will be written to the command's stdin. stdout: File-like object to write the command's output to. Can be None, in which case the command's output will be buffered internally, and can be access via the return value of wait(). raw: If True, run the command as per RawCommand (see above). timeout_ms: Timeout for the command, in milliseconds. Returns: An AsyncCommandHandle instance that can be used to send/receive data to and from the command or wait on the command to finish. Raises: AdbStreamUnavailableError: If the remote devices doesn't support the shell: service. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) if raw: command = self._to_raw_command(command) stream = self.adb_connection.open_stream('shell:%s' % command, timeout) if not stream: raise usb_exceptions.AdbStreamUnavailableError( '%s does not support service: shell', self) if raw and stdin is not None: # Short delay to make sure the ioctl to set raw mode happens before we do # any writes to the stream, if we don't do this bad things happen... time.sleep(.1) return AsyncCommandHandle(stream, stdin, stdout, timeout, raw)
python
def async_command(self, command, stdin=None, stdout=None, raw=False, timeout_ms=None): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) if raw: command = self._to_raw_command(command) stream = self.adb_connection.open_stream('shell:%s' % command, timeout) if not stream: raise usb_exceptions.AdbStreamUnavailableError( '%s does not support service: shell', self) if raw and stdin is not None: # Short delay to make sure the ioctl to set raw mode happens before we do # any writes to the stream, if we don't do this bad things happen... time.sleep(.1) return AsyncCommandHandle(stream, stdin, stdout, timeout, raw)
[ "def", "async_command", "(", "self", ",", "command", ",", "stdin", "=", "None", ",", "stdout", "=", "None", ",", "raw", "=", "False", ",", "timeout_ms", "=", "None", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "...
Run the given command on the device asynchronously. Input will be read from stdin, output written to stdout. ADB doesn't distinguish between stdout and stdin on the device, so they get interleaved into stdout here. stdin and stdout should be file-like objects, so you could use sys.stdin and sys.stdout to emulate the 'adb shell' commandline. Args: command: The command to run, will be run with /bin/sh -c 'command' on the device. stdin: File-like object to read from to pipe to the command's stdin. Can be None, in which case nothing will be written to the command's stdin. stdout: File-like object to write the command's output to. Can be None, in which case the command's output will be buffered internally, and can be access via the return value of wait(). raw: If True, run the command as per RawCommand (see above). timeout_ms: Timeout for the command, in milliseconds. Returns: An AsyncCommandHandle instance that can be used to send/receive data to and from the command or wait on the command to finish. Raises: AdbStreamUnavailableError: If the remote devices doesn't support the shell: service.
[ "Run", "the", "given", "command", "on", "the", "device", "asynchronously", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L234-L273
240,805
google/openhtf
openhtf/util/conf.py
Configuration.load_flag_values
def load_flag_values(self, flags=None): """Load flag values given from command line flags. Args: flags: An argparse Namespace containing the command line flags. """ if flags is None: flags = self._flags for keyval in flags.config_value: k, v = keyval.split('=', 1) v = self._modules['yaml'].load(v) if isinstance(v, str) else v # Force any command line keys and values that are bytes to unicode. k = k.decode() if isinstance(k, bytes) else k v = v.decode() if isinstance(v, bytes) else v self._flag_values.setdefault(k, v)
python
def load_flag_values(self, flags=None): if flags is None: flags = self._flags for keyval in flags.config_value: k, v = keyval.split('=', 1) v = self._modules['yaml'].load(v) if isinstance(v, str) else v # Force any command line keys and values that are bytes to unicode. k = k.decode() if isinstance(k, bytes) else k v = v.decode() if isinstance(v, bytes) else v self._flag_values.setdefault(k, v)
[ "def", "load_flag_values", "(", "self", ",", "flags", "=", "None", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "self", ".", "_flags", "for", "keyval", "in", "flags", ".", "config_value", ":", "k", ",", "v", "=", "keyval", ".", "split", ...
Load flag values given from command line flags. Args: flags: An argparse Namespace containing the command line flags.
[ "Load", "flag", "values", "given", "from", "command", "line", "flags", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L255-L271
240,806
google/openhtf
openhtf/util/conf.py
Configuration.declare
def declare(self, name, description=None, **kwargs): """Declare a configuration key with the given name. Args: name: Configuration key to declare, must not have been already declared. description: If provided, use this as the description for this key. **kwargs: Other kwargs to pass to the Declaration, only default_value is currently supported. """ if not self._is_valid_key(name): raise self.InvalidKeyError( 'Invalid key name, must begin with a lowercase letter', name) if name in self._declarations: raise self.KeyAlreadyDeclaredError( 'Configuration key already declared', name) self._declarations[name] = self.Declaration( name, description=description, **kwargs)
python
def declare(self, name, description=None, **kwargs): if not self._is_valid_key(name): raise self.InvalidKeyError( 'Invalid key name, must begin with a lowercase letter', name) if name in self._declarations: raise self.KeyAlreadyDeclaredError( 'Configuration key already declared', name) self._declarations[name] = self.Declaration( name, description=description, **kwargs)
[ "def", "declare", "(", "self", ",", "name", ",", "description", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_is_valid_key", "(", "name", ")", ":", "raise", "self", ".", "InvalidKeyError", "(", "'Invalid key name, must begin w...
Declare a configuration key with the given name. Args: name: Configuration key to declare, must not have been already declared. description: If provided, use this as the description for this key. **kwargs: Other kwargs to pass to the Declaration, only default_value is currently supported.
[ "Declare", "a", "configuration", "key", "with", "the", "given", "name", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L337-L353
240,807
google/openhtf
openhtf/util/conf.py
Configuration.reset
def reset(self): """Reset the loaded state of the configuration to what it was at import. Note that this does *not* reset values set by commandline flags or loaded from --config-file (in fact, any values loaded from --config-file that have been overridden are reset to their value from --config-file). """ # Populate loaded_values with values from --config-file, if it was given. self._loaded_values = {} if self._flags.config_file is not None: self.load_from_file(self._flags.config_file, _allow_undeclared=True)
python
def reset(self): # Populate loaded_values with values from --config-file, if it was given. self._loaded_values = {} if self._flags.config_file is not None: self.load_from_file(self._flags.config_file, _allow_undeclared=True)
[ "def", "reset", "(", "self", ")", ":", "# Populate loaded_values with values from --config-file, if it was given.", "self", ".", "_loaded_values", "=", "{", "}", "if", "self", ".", "_flags", ".", "config_file", "is", "not", "None", ":", "self", ".", "load_from_file"...
Reset the loaded state of the configuration to what it was at import. Note that this does *not* reset values set by commandline flags or loaded from --config-file (in fact, any values loaded from --config-file that have been overridden are reset to their value from --config-file).
[ "Reset", "the", "loaded", "state", "of", "the", "configuration", "to", "what", "it", "was", "at", "import", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L356-L366
240,808
google/openhtf
openhtf/util/conf.py
Configuration.load_from_file
def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False): """Loads the configuration from a file. Parsed contents must be a single dict mapping config key to value. Args: yamlfile: The opened file object to load configuration from. See load_from_dict() for other args' descriptions. Raises: ConfigurationInvalidError: If configuration file can't be read, or can't be parsed as either YAML (or JSON, which is a subset of YAML). """ self._logger.info('Loading configuration from file: %s', yamlfile) try: parsed_yaml = self._modules['yaml'].safe_load(yamlfile.read()) except self._modules['yaml'].YAMLError: self._logger.exception('Problem parsing YAML') raise self.ConfigurationInvalidError( 'Failed to load from %s as YAML' % yamlfile) if not isinstance(parsed_yaml, dict): # Parsed YAML, but it's not a dict. raise self.ConfigurationInvalidError( 'YAML parsed, but wrong type, should be dict', parsed_yaml) self._logger.debug('Configuration loaded from file: %s', parsed_yaml) self.load_from_dict( parsed_yaml, _override=_override, _allow_undeclared=_allow_undeclared)
python
def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False): self._logger.info('Loading configuration from file: %s', yamlfile) try: parsed_yaml = self._modules['yaml'].safe_load(yamlfile.read()) except self._modules['yaml'].YAMLError: self._logger.exception('Problem parsing YAML') raise self.ConfigurationInvalidError( 'Failed to load from %s as YAML' % yamlfile) if not isinstance(parsed_yaml, dict): # Parsed YAML, but it's not a dict. raise self.ConfigurationInvalidError( 'YAML parsed, but wrong type, should be dict', parsed_yaml) self._logger.debug('Configuration loaded from file: %s', parsed_yaml) self.load_from_dict( parsed_yaml, _override=_override, _allow_undeclared=_allow_undeclared)
[ "def", "load_from_file", "(", "self", ",", "yamlfile", ",", "_override", "=", "True", ",", "_allow_undeclared", "=", "False", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Loading configuration from file: %s'", ",", "yamlfile", ")", "try", ":", "parsed...
Loads the configuration from a file. Parsed contents must be a single dict mapping config key to value. Args: yamlfile: The opened file object to load configuration from. See load_from_dict() for other args' descriptions. Raises: ConfigurationInvalidError: If configuration file can't be read, or can't be parsed as either YAML (or JSON, which is a subset of YAML).
[ "Loads", "the", "configuration", "from", "a", "file", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L368-L397
240,809
google/openhtf
openhtf/util/conf.py
Configuration.load_from_dict
def load_from_dict(self, dictionary, _override=True, _allow_undeclared=False): """Loads the config with values from a dictionary instead of a file. This is meant for testing and bin purposes and shouldn't be used in most applications. Args: dictionary: The dictionary containing config keys/values to update. _override: If True, new values will override previous values. _allow_undeclared: If True, silently load undeclared keys, otherwise warn and ignore the value. Typically used for loading config files before declarations have been evaluated. """ undeclared_keys = [] for key, value in self._modules['six'].iteritems(dictionary): # Warn in this case. We raise if you try to access a config key that # hasn't been declared, but we don't raise here so that you can use # configuration files that are supersets of required configuration for # any particular test station. if key not in self._declarations and not _allow_undeclared: undeclared_keys.append(key) continue if key in self._loaded_values: if _override: self._logger.info( 'Overriding previously loaded value for %s (%s) with value: %s', key, self._loaded_values[key], value) else: self._logger.info( 'Ignoring new value (%s), keeping previous value for %s: %s', value, key, self._loaded_values[key]) continue # Force any keys and values that are bytes to unicode. key = key.decode() if isinstance(key, bytes) else key value = value.decode() if isinstance(value, bytes) else value self._loaded_values[key] = value if undeclared_keys: self._logger.warning('Ignoring undeclared configuration keys: %s', undeclared_keys)
python
def load_from_dict(self, dictionary, _override=True, _allow_undeclared=False): undeclared_keys = [] for key, value in self._modules['six'].iteritems(dictionary): # Warn in this case. We raise if you try to access a config key that # hasn't been declared, but we don't raise here so that you can use # configuration files that are supersets of required configuration for # any particular test station. if key not in self._declarations and not _allow_undeclared: undeclared_keys.append(key) continue if key in self._loaded_values: if _override: self._logger.info( 'Overriding previously loaded value for %s (%s) with value: %s', key, self._loaded_values[key], value) else: self._logger.info( 'Ignoring new value (%s), keeping previous value for %s: %s', value, key, self._loaded_values[key]) continue # Force any keys and values that are bytes to unicode. key = key.decode() if isinstance(key, bytes) else key value = value.decode() if isinstance(value, bytes) else value self._loaded_values[key] = value if undeclared_keys: self._logger.warning('Ignoring undeclared configuration keys: %s', undeclared_keys)
[ "def", "load_from_dict", "(", "self", ",", "dictionary", ",", "_override", "=", "True", ",", "_allow_undeclared", "=", "False", ")", ":", "undeclared_keys", "=", "[", "]", "for", "key", ",", "value", "in", "self", ".", "_modules", "[", "'six'", "]", ".",...
Loads the config with values from a dictionary instead of a file. This is meant for testing and bin purposes and shouldn't be used in most applications. Args: dictionary: The dictionary containing config keys/values to update. _override: If True, new values will override previous values. _allow_undeclared: If True, silently load undeclared keys, otherwise warn and ignore the value. Typically used for loading config files before declarations have been evaluated.
[ "Loads", "the", "config", "with", "values", "from", "a", "dictionary", "instead", "of", "a", "file", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L405-L445
240,810
google/openhtf
openhtf/util/conf.py
Configuration._asdict
def _asdict(self): """Create a dictionary snapshot of the current config values.""" # Start with any default values we have, and override with loaded values, # and then override with flag values. retval = {key: self._declarations[key].default_value for key in self._declarations if self._declarations[key].has_default} retval.update(self._loaded_values) # Only update keys that are declared so we don't allow injecting # un-declared keys via commandline flags. for key, value in self._modules['six'].iteritems(self._flag_values): if key in self._declarations: retval[key] = value return retval
python
def _asdict(self): # Start with any default values we have, and override with loaded values, # and then override with flag values. retval = {key: self._declarations[key].default_value for key in self._declarations if self._declarations[key].has_default} retval.update(self._loaded_values) # Only update keys that are declared so we don't allow injecting # un-declared keys via commandline flags. for key, value in self._modules['six'].iteritems(self._flag_values): if key in self._declarations: retval[key] = value return retval
[ "def", "_asdict", "(", "self", ")", ":", "# Start with any default values we have, and override with loaded values,", "# and then override with flag values.", "retval", "=", "{", "key", ":", "self", ".", "_declarations", "[", "key", "]", ".", "default_value", "for", "key"...
Create a dictionary snapshot of the current config values.
[ "Create", "a", "dictionary", "snapshot", "of", "the", "current", "config", "values", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L448-L460
240,811
google/openhtf
openhtf/util/conf.py
Configuration.help_text
def help_text(self): """Return a string with all config keys and their descriptions.""" result = [] for name in sorted(self._declarations.keys()): result.append(name) result.append('-' * len(name)) decl = self._declarations[name] if decl.description: result.append(decl.description.strip()) else: result.append('(no description found)') if decl.has_default: result.append('') quotes = '"' if type(decl.default_value) is str else '' result.append(' default_value={quotes}{val}{quotes}'.format( quotes=quotes, val=decl.default_value)) result.append('') result.append('') return '\n'.join(result)
python
def help_text(self): result = [] for name in sorted(self._declarations.keys()): result.append(name) result.append('-' * len(name)) decl = self._declarations[name] if decl.description: result.append(decl.description.strip()) else: result.append('(no description found)') if decl.has_default: result.append('') quotes = '"' if type(decl.default_value) is str else '' result.append(' default_value={quotes}{val}{quotes}'.format( quotes=quotes, val=decl.default_value)) result.append('') result.append('') return '\n'.join(result)
[ "def", "help_text", "(", "self", ")", ":", "result", "=", "[", "]", "for", "name", "in", "sorted", "(", "self", ".", "_declarations", ".", "keys", "(", ")", ")", ":", "result", ".", "append", "(", "name", ")", "result", ".", "append", "(", "'-'", ...
Return a string with all config keys and their descriptions.
[ "Return", "a", "string", "with", "all", "config", "keys", "and", "their", "descriptions", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L463-L481
240,812
google/openhtf
openhtf/util/conf.py
Configuration.save_and_restore
def save_and_restore(self, _func=None, **config_values): """Decorator for saving conf state and restoring it after a function. This decorator is primarily for use in tests, where conf keys may be updated for individual test cases, but those values need to be reverted after the test case is done. Examples: conf.declare('my_conf_key') @conf.save_and_restore def MyTestFunc(): conf.load(my_conf_key='baz') SomeFuncUnderTestThatUsesMyConfKey() conf.load(my_conf_key='foo') MyTestFunc() print conf.my_conf_key # Prints 'foo', *NOT* 'baz' # Without the save_and_restore decorator, MyTestFunc() would have had the # side effect of altering the conf value of 'my_conf_key' to 'baz'. # Config keys can also be initialized for the context inline at decoration # time. This is the same as setting them at the beginning of the # function, but is a little clearer syntax if you know ahead of time what # config keys and values you need to set. @conf.save_and_restore(my_conf_key='baz') def MyOtherTestFunc(): print conf.my_conf_key # Prints 'baz' MyOtherTestFunc() print conf.my_conf_key # Prints 'foo' again, for the same reason. Args: _func: The function to wrap. The returned wrapper will invoke the function and restore the config to the state it was in at invocation. **config_values: Config keys can be set inline at decoration time, see examples. Note that config keys can't begin with underscore, so there can be no name collision with _func. Returns: Wrapper to replace _func, as per Python decorator semantics. """ functools = self._modules['functools'] # pylint: disable=redefined-outer-name if not _func: return functools.partial(self.save_and_restore, **config_values) @functools.wraps(_func) def _saving_wrapper(*args, **kwargs): saved_config = dict(self._loaded_values) try: self.load_from_dict(config_values) return _func(*args, **kwargs) finally: self._loaded_values = saved_config # pylint: disable=attribute-defined-outside-init return _saving_wrapper
python
def save_and_restore(self, _func=None, **config_values): functools = self._modules['functools'] # pylint: disable=redefined-outer-name if not _func: return functools.partial(self.save_and_restore, **config_values) @functools.wraps(_func) def _saving_wrapper(*args, **kwargs): saved_config = dict(self._loaded_values) try: self.load_from_dict(config_values) return _func(*args, **kwargs) finally: self._loaded_values = saved_config # pylint: disable=attribute-defined-outside-init return _saving_wrapper
[ "def", "save_and_restore", "(", "self", ",", "_func", "=", "None", ",", "*", "*", "config_values", ")", ":", "functools", "=", "self", ".", "_modules", "[", "'functools'", "]", "# pylint: disable=redefined-outer-name", "if", "not", "_func", ":", "return", "fun...
Decorator for saving conf state and restoring it after a function. This decorator is primarily for use in tests, where conf keys may be updated for individual test cases, but those values need to be reverted after the test case is done. Examples: conf.declare('my_conf_key') @conf.save_and_restore def MyTestFunc(): conf.load(my_conf_key='baz') SomeFuncUnderTestThatUsesMyConfKey() conf.load(my_conf_key='foo') MyTestFunc() print conf.my_conf_key # Prints 'foo', *NOT* 'baz' # Without the save_and_restore decorator, MyTestFunc() would have had the # side effect of altering the conf value of 'my_conf_key' to 'baz'. # Config keys can also be initialized for the context inline at decoration # time. This is the same as setting them at the beginning of the # function, but is a little clearer syntax if you know ahead of time what # config keys and values you need to set. @conf.save_and_restore(my_conf_key='baz') def MyOtherTestFunc(): print conf.my_conf_key # Prints 'baz' MyOtherTestFunc() print conf.my_conf_key # Prints 'foo' again, for the same reason. Args: _func: The function to wrap. The returned wrapper will invoke the function and restore the config to the state it was in at invocation. **config_values: Config keys can be set inline at decoration time, see examples. Note that config keys can't begin with underscore, so there can be no name collision with _func. Returns: Wrapper to replace _func, as per Python decorator semantics.
[ "Decorator", "for", "saving", "conf", "state", "and", "restoring", "it", "after", "a", "function", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L483-L542
240,813
google/openhtf
openhtf/util/conf.py
Configuration.inject_positional_args
def inject_positional_args(self, method): """Decorator for injecting positional arguments from the configuration. This decorator wraps the given method, so that any positional arguments are passed with corresponding values from the configuration. The name of the positional argument must match the configuration key. Keyword arguments are *NEVER* modified, even if their names match configuration keys. Avoid naming keyword args names that are also configuration keys to avoid confusion. Additional positional arguments may be used that do not appear in the configuration, but those arguments *MUST* be specified as keyword arguments upon invocation of the method. This is to avoid ambiguity in which positional arguments are getting which values. Args: method: The method to wrap. Returns: A wrapper that, when invoked, will call the wrapped method, passing in configuration values for positional arguments. """ inspect = self._modules['inspect'] argspec = inspect.getargspec(method) # Index in argspec.args of the first keyword argument. This index is a # negative number if there are any kwargs, or 0 if there are no kwargs. keyword_arg_index = -1 * len(argspec.defaults or []) arg_names = argspec.args[:keyword_arg_index or None] kwarg_names = argspec.args[len(arg_names):] functools = self._modules['functools'] # pylint: disable=redefined-outer-name # Create the actual method wrapper, all we do is update kwargs. Note we # don't pass any *args through because there can't be any - we've filled # them all in with values from the configuration. Any positional args that # are missing from the configuration *must* be explicitly specified as # kwargs. @functools.wraps(method) def method_wrapper(**kwargs): """Wrapper that pulls values from openhtf.util.conf.""" # Check for keyword args with names that are in the config so we can warn. for kwarg in kwarg_names: if kwarg in self: self._logger.warning('Keyword arg %s not set from configuration, but ' 'is a configuration key', kwarg) # Set positional args from configuration values. final_kwargs = {name: self[name] for name in arg_names if name in self} for overridden in set(kwargs) & set(final_kwargs): self._logger.warning('Overriding configuration value for kwarg %s (%s) ' 'with provided kwarg value: %s', overridden, self[overridden], kwargs[overridden]) final_kwargs.update(kwargs) if inspect.ismethod(method): name = '%s.%s' % (method.__self__.__class__.__name__, method.__name__) else: name = method.__name__ self._logger.debug('Invoking %s with %s', name, final_kwargs) return method(**final_kwargs) # We have to check for a 'self' parameter explicitly because Python doesn't # pass it as a keyword arg, it passes it as the first positional arg. if argspec.args[0] == 'self': @functools.wraps(method) def self_wrapper(self, **kwargs): # pylint: disable=invalid-name """Wrapper that pulls values from openhtf.util.conf.""" kwargs['self'] = self return method_wrapper(**kwargs) return self_wrapper return method_wrapper
python
def inject_positional_args(self, method): inspect = self._modules['inspect'] argspec = inspect.getargspec(method) # Index in argspec.args of the first keyword argument. This index is a # negative number if there are any kwargs, or 0 if there are no kwargs. keyword_arg_index = -1 * len(argspec.defaults or []) arg_names = argspec.args[:keyword_arg_index or None] kwarg_names = argspec.args[len(arg_names):] functools = self._modules['functools'] # pylint: disable=redefined-outer-name # Create the actual method wrapper, all we do is update kwargs. Note we # don't pass any *args through because there can't be any - we've filled # them all in with values from the configuration. Any positional args that # are missing from the configuration *must* be explicitly specified as # kwargs. @functools.wraps(method) def method_wrapper(**kwargs): """Wrapper that pulls values from openhtf.util.conf.""" # Check for keyword args with names that are in the config so we can warn. for kwarg in kwarg_names: if kwarg in self: self._logger.warning('Keyword arg %s not set from configuration, but ' 'is a configuration key', kwarg) # Set positional args from configuration values. final_kwargs = {name: self[name] for name in arg_names if name in self} for overridden in set(kwargs) & set(final_kwargs): self._logger.warning('Overriding configuration value for kwarg %s (%s) ' 'with provided kwarg value: %s', overridden, self[overridden], kwargs[overridden]) final_kwargs.update(kwargs) if inspect.ismethod(method): name = '%s.%s' % (method.__self__.__class__.__name__, method.__name__) else: name = method.__name__ self._logger.debug('Invoking %s with %s', name, final_kwargs) return method(**final_kwargs) # We have to check for a 'self' parameter explicitly because Python doesn't # pass it as a keyword arg, it passes it as the first positional arg. if argspec.args[0] == 'self': @functools.wraps(method) def self_wrapper(self, **kwargs): # pylint: disable=invalid-name """Wrapper that pulls values from openhtf.util.conf.""" kwargs['self'] = self return method_wrapper(**kwargs) return self_wrapper return method_wrapper
[ "def", "inject_positional_args", "(", "self", ",", "method", ")", ":", "inspect", "=", "self", ".", "_modules", "[", "'inspect'", "]", "argspec", "=", "inspect", ".", "getargspec", "(", "method", ")", "# Index in argspec.args of the first keyword argument. This index...
Decorator for injecting positional arguments from the configuration. This decorator wraps the given method, so that any positional arguments are passed with corresponding values from the configuration. The name of the positional argument must match the configuration key. Keyword arguments are *NEVER* modified, even if their names match configuration keys. Avoid naming keyword args names that are also configuration keys to avoid confusion. Additional positional arguments may be used that do not appear in the configuration, but those arguments *MUST* be specified as keyword arguments upon invocation of the method. This is to avoid ambiguity in which positional arguments are getting which values. Args: method: The method to wrap. Returns: A wrapper that, when invoked, will call the wrapped method, passing in configuration values for positional arguments.
[ "Decorator", "for", "injecting", "positional", "arguments", "from", "the", "configuration", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L544-L616
240,814
google/openhtf
openhtf/util/functions.py
call_once
def call_once(func): """Decorate a function to only allow it to be called once. Note that it doesn't make sense to only call a function once if it takes arguments (use @functools.lru_cache for that sort of thing), so this only works on callables that take no args. """ argspec = inspect.getargspec(func) if argspec.args or argspec.varargs or argspec.keywords: raise ValueError('Can only decorate functions with no args', func, argspec) @functools.wraps(func) def _wrapper(): # If we haven't been called yet, actually invoke func and save the result. if not _wrapper.HasRun(): _wrapper.MarkAsRun() _wrapper.return_value = func() return _wrapper.return_value _wrapper.has_run = False _wrapper.HasRun = lambda: _wrapper.has_run _wrapper.MarkAsRun = lambda: setattr(_wrapper, 'has_run', True) return _wrapper
python
def call_once(func): argspec = inspect.getargspec(func) if argspec.args or argspec.varargs or argspec.keywords: raise ValueError('Can only decorate functions with no args', func, argspec) @functools.wraps(func) def _wrapper(): # If we haven't been called yet, actually invoke func and save the result. if not _wrapper.HasRun(): _wrapper.MarkAsRun() _wrapper.return_value = func() return _wrapper.return_value _wrapper.has_run = False _wrapper.HasRun = lambda: _wrapper.has_run _wrapper.MarkAsRun = lambda: setattr(_wrapper, 'has_run', True) return _wrapper
[ "def", "call_once", "(", "func", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "if", "argspec", ".", "args", "or", "argspec", ".", "varargs", "or", "argspec", ".", "keywords", ":", "raise", "ValueError", "(", "'Can only decorate...
Decorate a function to only allow it to be called once. Note that it doesn't make sense to only call a function once if it takes arguments (use @functools.lru_cache for that sort of thing), so this only works on callables that take no args.
[ "Decorate", "a", "function", "to", "only", "allow", "it", "to", "be", "called", "once", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/functions.py#L23-L45
240,815
google/openhtf
openhtf/util/functions.py
call_at_most_every
def call_at_most_every(seconds, count=1): """Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window. """ def decorator(func): try: call_history = getattr(func, '_call_history') except AttributeError: call_history = collections.deque(maxlen=count) setattr(func, '_call_history', call_history) @functools.wraps(func) def _wrapper(*args, **kwargs): current_time = time.time() window_count = sum(ts > current_time - seconds for ts in call_history) if window_count >= count: # We need to sleep until the relevant call is outside the window. This # should only ever be the the first entry in call_history, but if we # somehow ended up with extra calls in the window, this recovers. time.sleep(call_history[window_count - count] - current_time + seconds) # Append this call, deque will automatically trim old calls using maxlen. call_history.append(time.time()) return func(*args, **kwargs) return _wrapper return decorator
python
def call_at_most_every(seconds, count=1): def decorator(func): try: call_history = getattr(func, '_call_history') except AttributeError: call_history = collections.deque(maxlen=count) setattr(func, '_call_history', call_history) @functools.wraps(func) def _wrapper(*args, **kwargs): current_time = time.time() window_count = sum(ts > current_time - seconds for ts in call_history) if window_count >= count: # We need to sleep until the relevant call is outside the window. This # should only ever be the the first entry in call_history, but if we # somehow ended up with extra calls in the window, this recovers. time.sleep(call_history[window_count - count] - current_time + seconds) # Append this call, deque will automatically trim old calls using maxlen. call_history.append(time.time()) return func(*args, **kwargs) return _wrapper return decorator
[ "def", "call_at_most_every", "(", "seconds", ",", "count", "=", "1", ")", ":", "def", "decorator", "(", "func", ")", ":", "try", ":", "call_history", "=", "getattr", "(", "func", ",", "'_call_history'", ")", "except", "AttributeError", ":", "call_history", ...
Call the decorated function at most count times every seconds seconds. The decorated function will sleep to ensure that at most count invocations occur within any 'seconds' second window.
[ "Call", "the", "decorated", "function", "at", "most", "count", "times", "every", "seconds", "seconds", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/functions.py#L47-L73
240,816
google/openhtf
openhtf/plugs/usb/__init__.py
_open_usb_handle
def _open_usb_handle(serial_number=None, **kwargs): """Open a UsbHandle subclass, based on configuration. If configuration 'remote_usb' is set, use it to connect to remote usb, otherwise attempt to connect locally.'remote_usb' is set to usb type, EtherSync or other. Example of Cambrionix unit in config: remote_usb: ethersync ethersync: mac_addr: 78:a5:04:ca:91:66 plug_port: 5 Args: serial_number: Optional serial number to connect to. **kwargs: Arguments to pass to respective handle's Open() method. Returns: Instance of UsbHandle. """ init_dependent_flags() remote_usb = conf.remote_usb if remote_usb: if remote_usb.strip() == 'ethersync': device = conf.ethersync try: mac_addr = device['mac_addr'] port = device['plug_port'] except (KeyError, TypeError): raise ValueError('Ethersync needs mac_addr and plug_port to be set') else: ethersync = cambrionix.EtherSync(mac_addr) serial_number = ethersync.get_usb_serial(port) return local_usb.LibUsbHandle.open(serial_number=serial_number, **kwargs)
python
def _open_usb_handle(serial_number=None, **kwargs): init_dependent_flags() remote_usb = conf.remote_usb if remote_usb: if remote_usb.strip() == 'ethersync': device = conf.ethersync try: mac_addr = device['mac_addr'] port = device['plug_port'] except (KeyError, TypeError): raise ValueError('Ethersync needs mac_addr and plug_port to be set') else: ethersync = cambrionix.EtherSync(mac_addr) serial_number = ethersync.get_usb_serial(port) return local_usb.LibUsbHandle.open(serial_number=serial_number, **kwargs)
[ "def", "_open_usb_handle", "(", "serial_number", "=", "None", ",", "*", "*", "kwargs", ")", ":", "init_dependent_flags", "(", ")", "remote_usb", "=", "conf", ".", "remote_usb", "if", "remote_usb", ":", "if", "remote_usb", ".", "strip", "(", ")", "==", "'et...
Open a UsbHandle subclass, based on configuration. If configuration 'remote_usb' is set, use it to connect to remote usb, otherwise attempt to connect locally.'remote_usb' is set to usb type, EtherSync or other. Example of Cambrionix unit in config: remote_usb: ethersync ethersync: mac_addr: 78:a5:04:ca:91:66 plug_port: 5 Args: serial_number: Optional serial number to connect to. **kwargs: Arguments to pass to respective handle's Open() method. Returns: Instance of UsbHandle.
[ "Open", "a", "UsbHandle", "subclass", "based", "on", "configuration", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/__init__.py#L62-L96
240,817
google/openhtf
openhtf/plugs/usb/__init__.py
AndroidTriggers._try_open
def _try_open(cls): """Try to open a USB handle.""" handle = None for usb_cls, subcls, protocol in [(adb_device.CLASS, adb_device.SUBCLASS, adb_device.PROTOCOL), (fastboot_device.CLASS, fastboot_device.SUBCLASS, fastboot_device.PROTOCOL)]: try: handle = local_usb.LibUsbHandle.open( serial_number=cls.serial_number, interface_class=usb_cls, interface_subclass=subcls, interface_protocol=protocol) cls.serial_number = handle.serial_number return True except usb_exceptions.DeviceNotFoundError: pass except usb_exceptions.MultipleInterfacesFoundError: _LOG.warning('Multiple Android devices found, ignoring!') finally: if handle: handle.close() return False
python
def _try_open(cls): handle = None for usb_cls, subcls, protocol in [(adb_device.CLASS, adb_device.SUBCLASS, adb_device.PROTOCOL), (fastboot_device.CLASS, fastboot_device.SUBCLASS, fastboot_device.PROTOCOL)]: try: handle = local_usb.LibUsbHandle.open( serial_number=cls.serial_number, interface_class=usb_cls, interface_subclass=subcls, interface_protocol=protocol) cls.serial_number = handle.serial_number return True except usb_exceptions.DeviceNotFoundError: pass except usb_exceptions.MultipleInterfacesFoundError: _LOG.warning('Multiple Android devices found, ignoring!') finally: if handle: handle.close() return False
[ "def", "_try_open", "(", "cls", ")", ":", "handle", "=", "None", "for", "usb_cls", ",", "subcls", ",", "protocol", "in", "[", "(", "adb_device", ".", "CLASS", ",", "adb_device", ".", "SUBCLASS", ",", "adb_device", ".", "PROTOCOL", ")", ",", "(", "fastb...
Try to open a USB handle.
[ "Try", "to", "open", "a", "USB", "handle", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/__init__.py#L164-L188
240,818
google/openhtf
openhtf/plugs/usb/fastboot_device.py
_retry_usb_function
def _retry_usb_function(count, func, *args, **kwargs): """Helper function to retry USB.""" helper = timeouts.RetryHelper(count) while True: try: return func(*args, **kwargs) except usb_exceptions.CommonUsbError: if not helper.retry_if_possible(): raise time.sleep(0.1) else: break
python
def _retry_usb_function(count, func, *args, **kwargs): helper = timeouts.RetryHelper(count) while True: try: return func(*args, **kwargs) except usb_exceptions.CommonUsbError: if not helper.retry_if_possible(): raise time.sleep(0.1) else: break
[ "def", "_retry_usb_function", "(", "count", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "helper", "=", "timeouts", ".", "RetryHelper", "(", "count", ")", "while", "True", ":", "try", ":", "return", "func", "(", "*", "args", ",",...
Helper function to retry USB.
[ "Helper", "function", "to", "retry", "USB", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_device.py#L112-L123
240,819
google/openhtf
openhtf/plugs/usb/fastboot_device.py
FastbootDevice.get_boot_config
def get_boot_config(self, name, info_cb=None): """Get bootconfig, either as full dict or specific value for key.""" result = {} def default_info_cb(msg): """Default Info CB.""" if not msg.message: return key, value = msg.message.split(':', 1) result[key.strip()] = value.strip() info_cb = info_cb or default_info_cb final_result = self.oem('bootconfig %s' % name, info_cb=info_cb) # Return INFO messages before the final OKAY message. if name in result: return result[name] return final_result
python
def get_boot_config(self, name, info_cb=None): result = {} def default_info_cb(msg): """Default Info CB.""" if not msg.message: return key, value = msg.message.split(':', 1) result[key.strip()] = value.strip() info_cb = info_cb or default_info_cb final_result = self.oem('bootconfig %s' % name, info_cb=info_cb) # Return INFO messages before the final OKAY message. if name in result: return result[name] return final_result
[ "def", "get_boot_config", "(", "self", ",", "name", ",", "info_cb", "=", "None", ")", ":", "result", "=", "{", "}", "def", "default_info_cb", "(", "msg", ")", ":", "\"\"\"Default Info CB.\"\"\"", "if", "not", "msg", ".", "message", ":", "return", "key", ...
Get bootconfig, either as full dict or specific value for key.
[ "Get", "bootconfig", "either", "as", "full", "dict", "or", "specific", "value", "for", "key", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_device.py#L49-L63
240,820
google/openhtf
openhtf/plugs/usb/local_usb.py
LibUsbHandle._device_to_sysfs_path
def _device_to_sysfs_path(device): """Convert device to corresponding sysfs path.""" return '%s-%s' % ( device.getBusNumber(), '.'.join([str(item) for item in device.GetPortNumberList()]))
python
def _device_to_sysfs_path(device): return '%s-%s' % ( device.getBusNumber(), '.'.join([str(item) for item in device.GetPortNumberList()]))
[ "def", "_device_to_sysfs_path", "(", "device", ")", ":", "return", "'%s-%s'", "%", "(", "device", ".", "getBusNumber", "(", ")", ",", "'.'", ".", "join", "(", "[", "str", "(", "item", ")", "for", "item", "in", "device", ".", "GetPortNumberList", "(", "...
Convert device to corresponding sysfs path.
[ "Convert", "device", "to", "corresponding", "sysfs", "path", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L112-L116
240,821
google/openhtf
openhtf/plugs/usb/local_usb.py
LibUsbHandle.open
def open(cls, **kwargs): """See iter_open, but raises if multiple or no matches found.""" handle_iter = cls.iter_open(**kwargs) try: handle = six.next(handle_iter) except StopIteration: # No matching interface, raise. raise usb_exceptions.DeviceNotFoundError( 'Open failed with args: %s', kwargs) try: multiple_handle = six.next(handle_iter) except StopIteration: # Exactly one matching device, return it. return handle # We have more than one device, close the ones we opened and bail. handle.close() multiple_handle.close() raise usb_exceptions.MultipleInterfacesFoundError(kwargs)
python
def open(cls, **kwargs): handle_iter = cls.iter_open(**kwargs) try: handle = six.next(handle_iter) except StopIteration: # No matching interface, raise. raise usb_exceptions.DeviceNotFoundError( 'Open failed with args: %s', kwargs) try: multiple_handle = six.next(handle_iter) except StopIteration: # Exactly one matching device, return it. return handle # We have more than one device, close the ones we opened and bail. handle.close() multiple_handle.close() raise usb_exceptions.MultipleInterfacesFoundError(kwargs)
[ "def", "open", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "handle_iter", "=", "cls", ".", "iter_open", "(", "*", "*", "kwargs", ")", "try", ":", "handle", "=", "six", ".", "next", "(", "handle_iter", ")", "except", "StopIteration", ":", "# No mat...
See iter_open, but raises if multiple or no matches found.
[ "See", "iter_open", "but", "raises", "if", "multiple", "or", "no", "matches", "found", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L158-L178
240,822
google/openhtf
openhtf/plugs/usb/local_usb.py
LibUsbHandle.iter_open
def iter_open(cls, name=None, interface_class=None, interface_subclass=None, interface_protocol=None, serial_number=None, port_path=None, default_timeout_ms=None): """Find and yield locally connected devices that match. Note that devices are opened (and interfaces claimd) as they are yielded. Any devices yielded must be Close()'d. Args: name: Name to give *all* returned handles, used for logging only. interface_class: USB interface_class to match. interface_subclass: USB interface_subclass to match. interface_protocol: USB interface_protocol to match. serial_number: USB serial_number to match. port_path: USB Port path to match, like X-X.X.X default_timeout_ms: Default timeout in milliseconds of reads/writes on the handles yielded. Yields: UsbHandle instances that match any non-None args given. Raises: LibusbWrappingError: When a libusb call errors during open. """ ctx = usb1.USBContext() try: devices = ctx.getDeviceList(skip_on_error=True) except libusb1.USBError as exception: raise usb_exceptions.LibusbWrappingError( exception, 'Open(name=%s, class=%s, subclass=%s, protocol=%s, ' 'serial=%s, port=%s) failed', name, interface_class, interface_subclass, interface_protocol, serial_number, port_path) for device in devices: try: if (serial_number is not None and device.getSerialNumber() != serial_number): continue if (port_path is not None and cls._device_to_sysfs_path(device) != port_path): continue for setting in device.iterSettings(): if (interface_class is not None and setting.getClass() != interface_class): continue if (interface_subclass is not None and setting.getSubClass() != interface_subclass): continue if (interface_protocol is not None and setting.getProtocol() != interface_protocol): continue yield cls(device, setting, name=name, default_timeout_ms=default_timeout_ms) except libusb1.USBError as exception: if (exception.value != libusb1.libusb_error.forward_dict['LIBUSB_ERROR_ACCESS']): raise
python
def iter_open(cls, name=None, interface_class=None, interface_subclass=None, interface_protocol=None, serial_number=None, port_path=None, default_timeout_ms=None): ctx = usb1.USBContext() try: devices = ctx.getDeviceList(skip_on_error=True) except libusb1.USBError as exception: raise usb_exceptions.LibusbWrappingError( exception, 'Open(name=%s, class=%s, subclass=%s, protocol=%s, ' 'serial=%s, port=%s) failed', name, interface_class, interface_subclass, interface_protocol, serial_number, port_path) for device in devices: try: if (serial_number is not None and device.getSerialNumber() != serial_number): continue if (port_path is not None and cls._device_to_sysfs_path(device) != port_path): continue for setting in device.iterSettings(): if (interface_class is not None and setting.getClass() != interface_class): continue if (interface_subclass is not None and setting.getSubClass() != interface_subclass): continue if (interface_protocol is not None and setting.getProtocol() != interface_protocol): continue yield cls(device, setting, name=name, default_timeout_ms=default_timeout_ms) except libusb1.USBError as exception: if (exception.value != libusb1.libusb_error.forward_dict['LIBUSB_ERROR_ACCESS']): raise
[ "def", "iter_open", "(", "cls", ",", "name", "=", "None", ",", "interface_class", "=", "None", ",", "interface_subclass", "=", "None", ",", "interface_protocol", "=", "None", ",", "serial_number", "=", "None", ",", "port_path", "=", "None", ",", "default_tim...
Find and yield locally connected devices that match. Note that devices are opened (and interfaces claimd) as they are yielded. Any devices yielded must be Close()'d. Args: name: Name to give *all* returned handles, used for logging only. interface_class: USB interface_class to match. interface_subclass: USB interface_subclass to match. interface_protocol: USB interface_protocol to match. serial_number: USB serial_number to match. port_path: USB Port path to match, like X-X.X.X default_timeout_ms: Default timeout in milliseconds of reads/writes on the handles yielded. Yields: UsbHandle instances that match any non-None args given. Raises: LibusbWrappingError: When a libusb call errors during open.
[ "Find", "and", "yield", "locally", "connected", "devices", "that", "match", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L182-L241
240,823
google/openhtf
examples/all_the_things.py
hello_world
def hello_world(test, example, prompts): """A hello world test phase.""" test.logger.info('Hello World!') test.measurements.widget_type = prompts.prompt( 'What\'s the widget type? (Hint: try `MyWidget` to PASS)', text_input=True) if test.measurements.widget_type == 'raise': raise Exception() test.measurements.widget_color = 'Black' test.measurements.widget_size = 3 test.measurements.specified_as_args = 'Measurement args specified directly' test.logger.info('Plug value: %s', example.increment())
python
def hello_world(test, example, prompts): test.logger.info('Hello World!') test.measurements.widget_type = prompts.prompt( 'What\'s the widget type? (Hint: try `MyWidget` to PASS)', text_input=True) if test.measurements.widget_type == 'raise': raise Exception() test.measurements.widget_color = 'Black' test.measurements.widget_size = 3 test.measurements.specified_as_args = 'Measurement args specified directly' test.logger.info('Plug value: %s', example.increment())
[ "def", "hello_world", "(", "test", ",", "example", ",", "prompts", ")", ":", "test", ".", "logger", ".", "info", "(", "'Hello World!'", ")", "test", ".", "measurements", ".", "widget_type", "=", "prompts", ".", "prompt", "(", "'What\\'s the widget type? (Hint:...
A hello world test phase.
[ "A", "hello", "world", "test", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/all_the_things.py#L55-L66
240,824
google/openhtf
examples/all_the_things.py
set_measurements
def set_measurements(test): """Test phase that sets a measurement.""" test.measurements.level_none = 0 time.sleep(1) test.measurements.level_some = 8 time.sleep(1) test.measurements.level_all = 9 time.sleep(1) level_all = test.get_measurement('level_all') assert level_all.value == 9
python
def set_measurements(test): test.measurements.level_none = 0 time.sleep(1) test.measurements.level_some = 8 time.sleep(1) test.measurements.level_all = 9 time.sleep(1) level_all = test.get_measurement('level_all') assert level_all.value == 9
[ "def", "set_measurements", "(", "test", ")", ":", "test", ".", "measurements", ".", "level_none", "=", "0", "time", ".", "sleep", "(", "1", ")", "test", ".", "measurements", ".", "level_some", "=", "8", "time", ".", "sleep", "(", "1", ")", "test", "....
Test phase that sets a measurement.
[ "Test", "phase", "that", "sets", "a", "measurement", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/all_the_things.py#L75-L84
240,825
google/openhtf
openhtf/util/data.py
pprint_diff
def pprint_diff(first, second, first_name='first', second_name='second'): """Compare the pprint representation of two objects and yield diff lines.""" return difflib.unified_diff( pprint.pformat(first).splitlines(), pprint.pformat(second).splitlines(), fromfile=first_name, tofile=second_name, lineterm='')
python
def pprint_diff(first, second, first_name='first', second_name='second'): return difflib.unified_diff( pprint.pformat(first).splitlines(), pprint.pformat(second).splitlines(), fromfile=first_name, tofile=second_name, lineterm='')
[ "def", "pprint_diff", "(", "first", ",", "second", ",", "first_name", "=", "'first'", ",", "second_name", "=", "'second'", ")", ":", "return", "difflib", ".", "unified_diff", "(", "pprint", ".", "pformat", "(", "first", ")", ".", "splitlines", "(", ")", ...
Compare the pprint representation of two objects and yield diff lines.
[ "Compare", "the", "pprint", "representation", "of", "two", "objects", "and", "yield", "diff", "lines", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L42-L47
240,826
google/openhtf
openhtf/util/data.py
equals_log_diff
def equals_log_diff(expected, actual, level=logging.ERROR): """Compare two string blobs, error log diff if they don't match.""" if expected == actual: return True # Output the diff first. logging.log(level, '***** Data mismatch: *****') for line in difflib.unified_diff( expected.splitlines(), actual.splitlines(), fromfile='expected', tofile='actual', lineterm=''): logging.log(level, line) logging.log(level, '^^^^^ Data diff ^^^^^')
python
def equals_log_diff(expected, actual, level=logging.ERROR): if expected == actual: return True # Output the diff first. logging.log(level, '***** Data mismatch: *****') for line in difflib.unified_diff( expected.splitlines(), actual.splitlines(), fromfile='expected', tofile='actual', lineterm=''): logging.log(level, line) logging.log(level, '^^^^^ Data diff ^^^^^')
[ "def", "equals_log_diff", "(", "expected", ",", "actual", ",", "level", "=", "logging", ".", "ERROR", ")", ":", "if", "expected", "==", "actual", ":", "return", "True", "# Output the diff first.", "logging", ".", "log", "(", "level", ",", "'***** Data mismatch...
Compare two string blobs, error log diff if they don't match.
[ "Compare", "two", "string", "blobs", "error", "log", "diff", "if", "they", "don", "t", "match", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L50-L61
240,827
google/openhtf
openhtf/util/data.py
assert_records_equal_nonvolatile
def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0): """Compare two test_record tuples, ignoring any volatile fields. 'Volatile' fields include any fields that are expected to differ between successive runs of the same test, mainly timestamps. All other fields are recursively compared. """ if isinstance(first, dict) and isinstance(second, dict): if set(first) != set(second): logging.error('%sMismatching keys:', ' ' * indent) logging.error('%s %s', ' ' * indent, list(first.keys())) logging.error('%s %s', ' ' * indent, list(second.keys())) assert set(first) == set(second) for key in first: if key in volatile_fields: continue try: assert_records_equal_nonvolatile(first[key], second[key], volatile_fields, indent + 2) except AssertionError: logging.error('%sKey: %s ^', ' ' * indent, key) raise elif hasattr(first, '_asdict') and hasattr(second, '_asdict'): # Compare namedtuples as dicts so we get more useful output. assert_records_equal_nonvolatile(first._asdict(), second._asdict(), volatile_fields, indent) elif hasattr(first, '__iter__') and hasattr(second, '__iter__'): for idx, (fir, sec) in enumerate(itertools.izip(first, second)): try: assert_records_equal_nonvolatile(fir, sec, volatile_fields, indent + 2) except AssertionError: logging.error('%sIndex: %s ^', ' ' * indent, idx) raise elif (isinstance(first, records.RecordClass) and isinstance(second, records.RecordClass)): assert_records_equal_nonvolatile( {slot: getattr(first, slot) for slot in first.__slots__}, {slot: getattr(second, slot) for slot in second.__slots__}, volatile_fields, indent) elif first != second: logging.error('%sRaw: "%s" != "%s"', ' ' * indent, first, second) assert first == second
python
def assert_records_equal_nonvolatile(first, second, volatile_fields, indent=0): if isinstance(first, dict) and isinstance(second, dict): if set(first) != set(second): logging.error('%sMismatching keys:', ' ' * indent) logging.error('%s %s', ' ' * indent, list(first.keys())) logging.error('%s %s', ' ' * indent, list(second.keys())) assert set(first) == set(second) for key in first: if key in volatile_fields: continue try: assert_records_equal_nonvolatile(first[key], second[key], volatile_fields, indent + 2) except AssertionError: logging.error('%sKey: %s ^', ' ' * indent, key) raise elif hasattr(first, '_asdict') and hasattr(second, '_asdict'): # Compare namedtuples as dicts so we get more useful output. assert_records_equal_nonvolatile(first._asdict(), second._asdict(), volatile_fields, indent) elif hasattr(first, '__iter__') and hasattr(second, '__iter__'): for idx, (fir, sec) in enumerate(itertools.izip(first, second)): try: assert_records_equal_nonvolatile(fir, sec, volatile_fields, indent + 2) except AssertionError: logging.error('%sIndex: %s ^', ' ' * indent, idx) raise elif (isinstance(first, records.RecordClass) and isinstance(second, records.RecordClass)): assert_records_equal_nonvolatile( {slot: getattr(first, slot) for slot in first.__slots__}, {slot: getattr(second, slot) for slot in second.__slots__}, volatile_fields, indent) elif first != second: logging.error('%sRaw: "%s" != "%s"', ' ' * indent, first, second) assert first == second
[ "def", "assert_records_equal_nonvolatile", "(", "first", ",", "second", ",", "volatile_fields", ",", "indent", "=", "0", ")", ":", "if", "isinstance", "(", "first", ",", "dict", ")", "and", "isinstance", "(", "second", ",", "dict", ")", ":", "if", "set", ...
Compare two test_record tuples, ignoring any volatile fields. 'Volatile' fields include any fields that are expected to differ between successive runs of the same test, mainly timestamps. All other fields are recursively compared.
[ "Compare", "two", "test_record", "tuples", "ignoring", "any", "volatile", "fields", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L64-L105
240,828
google/openhtf
openhtf/util/data.py
convert_to_base_types
def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple, json_safe=True): """Recursively convert objects into base types. This is used to convert some special types of objects used internally into base types for more friendly output via mechanisms such as JSON. It is used for sending internal objects via the network and outputting test records. Specifically, the conversions that are performed: - If an object has an as_base_types() method, immediately return the result without any recursion; this can be used with caching in the object to prevent unnecessary conversions. - If an object has an _asdict() method, use that to convert it to a dict and recursively converting its contents. - mutablerecords Record instances are converted to dicts that map attribute name to value. Optional attributes with a value of None are skipped. - Enum instances are converted to strings via their .name attribute. - Real and integral numbers are converted to built-in types. - Byte and unicode strings are left alone (instances of six.string_types). - Other non-None values are converted to strings via str(). The return value contains only the Python built-in types: dict, list, tuple, str, unicode, int, float, long, bool, and NoneType (unless tuple_type is set to something else). If tuples should be converted to lists (e.g. for an encoding that does not differentiate between the two), pass 'tuple_type=list' as an argument. If `json_safe` is True, then the float 'inf', '-inf', and 'nan' values will be converted to strings. This ensures that the returned dictionary can be passed to json.dumps to create valid JSON. Otherwise, json.dumps may return values such as NaN which are not valid JSON. """ # Because it's *really* annoying to pass a single string accidentally. assert not isinstance(ignore_keys, six.string_types), 'Pass a real iterable!' if hasattr(obj, 'as_base_types'): return obj.as_base_types() if hasattr(obj, '_asdict'): obj = obj._asdict() elif isinstance(obj, records.RecordClass): obj = {attr: getattr(obj, attr) for attr in type(obj).all_attribute_names if (getattr(obj, attr, None) is not None or attr in type(obj).required_attributes)} elif isinstance(obj, Enum): obj = obj.name if type(obj) in PASSTHROUGH_TYPES: return obj # Recursively convert values in dicts, lists, and tuples. if isinstance(obj, dict): return {convert_to_base_types(k, ignore_keys, tuple_type): convert_to_base_types(v, ignore_keys, tuple_type) for k, v in six.iteritems(obj) if k not in ignore_keys} elif isinstance(obj, list): return [convert_to_base_types(val, ignore_keys, tuple_type, json_safe) for val in obj] elif isinstance(obj, tuple): return tuple_type( convert_to_base_types(value, ignore_keys, tuple_type, json_safe) for value in obj) # Convert numeric types (e.g. numpy ints and floats) into built-in types. elif isinstance(obj, numbers.Integral): return long(obj) elif isinstance(obj, numbers.Real): as_float = float(obj) if json_safe and (math.isinf(as_float) or math.isnan(as_float)): return str(as_float) return as_float # Convert all other types to strings. try: return str(obj) except: logging.warning('Problem casting object of type %s to str.', type(obj)) raise
python
def convert_to_base_types(obj, ignore_keys=tuple(), tuple_type=tuple, json_safe=True): # Because it's *really* annoying to pass a single string accidentally. assert not isinstance(ignore_keys, six.string_types), 'Pass a real iterable!' if hasattr(obj, 'as_base_types'): return obj.as_base_types() if hasattr(obj, '_asdict'): obj = obj._asdict() elif isinstance(obj, records.RecordClass): obj = {attr: getattr(obj, attr) for attr in type(obj).all_attribute_names if (getattr(obj, attr, None) is not None or attr in type(obj).required_attributes)} elif isinstance(obj, Enum): obj = obj.name if type(obj) in PASSTHROUGH_TYPES: return obj # Recursively convert values in dicts, lists, and tuples. if isinstance(obj, dict): return {convert_to_base_types(k, ignore_keys, tuple_type): convert_to_base_types(v, ignore_keys, tuple_type) for k, v in six.iteritems(obj) if k not in ignore_keys} elif isinstance(obj, list): return [convert_to_base_types(val, ignore_keys, tuple_type, json_safe) for val in obj] elif isinstance(obj, tuple): return tuple_type( convert_to_base_types(value, ignore_keys, tuple_type, json_safe) for value in obj) # Convert numeric types (e.g. numpy ints and floats) into built-in types. elif isinstance(obj, numbers.Integral): return long(obj) elif isinstance(obj, numbers.Real): as_float = float(obj) if json_safe and (math.isinf(as_float) or math.isnan(as_float)): return str(as_float) return as_float # Convert all other types to strings. try: return str(obj) except: logging.warning('Problem casting object of type %s to str.', type(obj)) raise
[ "def", "convert_to_base_types", "(", "obj", ",", "ignore_keys", "=", "tuple", "(", ")", ",", "tuple_type", "=", "tuple", ",", "json_safe", "=", "True", ")", ":", "# Because it's *really* annoying to pass a single string accidentally.", "assert", "not", "isinstance", "...
Recursively convert objects into base types. This is used to convert some special types of objects used internally into base types for more friendly output via mechanisms such as JSON. It is used for sending internal objects via the network and outputting test records. Specifically, the conversions that are performed: - If an object has an as_base_types() method, immediately return the result without any recursion; this can be used with caching in the object to prevent unnecessary conversions. - If an object has an _asdict() method, use that to convert it to a dict and recursively converting its contents. - mutablerecords Record instances are converted to dicts that map attribute name to value. Optional attributes with a value of None are skipped. - Enum instances are converted to strings via their .name attribute. - Real and integral numbers are converted to built-in types. - Byte and unicode strings are left alone (instances of six.string_types). - Other non-None values are converted to strings via str(). The return value contains only the Python built-in types: dict, list, tuple, str, unicode, int, float, long, bool, and NoneType (unless tuple_type is set to something else). If tuples should be converted to lists (e.g. for an encoding that does not differentiate between the two), pass 'tuple_type=list' as an argument. If `json_safe` is True, then the float 'inf', '-inf', and 'nan' values will be converted to strings. This ensures that the returned dictionary can be passed to json.dumps to create valid JSON. Otherwise, json.dumps may return values such as NaN which are not valid JSON.
[ "Recursively", "convert", "objects", "into", "base", "types", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L108-L186
240,829
google/openhtf
openhtf/util/data.py
total_size
def total_size(obj): """Returns the approximate total memory footprint an object.""" seen = set() def sizeof(current_obj): try: return _sizeof(current_obj) except Exception: # pylint: disable=broad-except # Not sure what just happened, but let's assume it's a reference. return struct.calcsize('P') def _sizeof(current_obj): """Do a depth-first acyclic traversal of all reachable objects.""" if id(current_obj) in seen: # A rough approximation of the size cost of an additional reference. return struct.calcsize('P') seen.add(id(current_obj)) size = sys.getsizeof(current_obj) if isinstance(current_obj, dict): size += sum(map(sizeof, itertools.chain.from_iterable( six.iteritems(current_obj)))) elif (isinstance(current_obj, collections.Iterable) and not isinstance(current_obj, six.string_types)): size += sum(sizeof(item) for item in current_obj) elif isinstance(current_obj, records.RecordClass): size += sum(sizeof(getattr(current_obj, attr)) for attr in current_obj.__slots__) return size return sizeof(obj)
python
def total_size(obj): seen = set() def sizeof(current_obj): try: return _sizeof(current_obj) except Exception: # pylint: disable=broad-except # Not sure what just happened, but let's assume it's a reference. return struct.calcsize('P') def _sizeof(current_obj): """Do a depth-first acyclic traversal of all reachable objects.""" if id(current_obj) in seen: # A rough approximation of the size cost of an additional reference. return struct.calcsize('P') seen.add(id(current_obj)) size = sys.getsizeof(current_obj) if isinstance(current_obj, dict): size += sum(map(sizeof, itertools.chain.from_iterable( six.iteritems(current_obj)))) elif (isinstance(current_obj, collections.Iterable) and not isinstance(current_obj, six.string_types)): size += sum(sizeof(item) for item in current_obj) elif isinstance(current_obj, records.RecordClass): size += sum(sizeof(getattr(current_obj, attr)) for attr in current_obj.__slots__) return size return sizeof(obj)
[ "def", "total_size", "(", "obj", ")", ":", "seen", "=", "set", "(", ")", "def", "sizeof", "(", "current_obj", ")", ":", "try", ":", "return", "_sizeof", "(", "current_obj", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "# Not sure what jus...
Returns the approximate total memory footprint an object.
[ "Returns", "the", "approximate", "total", "memory", "footprint", "an", "object", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/data.py#L189-L218
240,830
google/openhtf
openhtf/output/callbacks/__init__.py
OutputToFile.open_output_file
def open_output_file(self, test_record): """Open file based on pattern.""" # Ignore keys for the log filename to not convert larger data structures. record_dict = data.convert_to_base_types( test_record, ignore_keys=('code_info', 'phases', 'log_records')) pattern = self.filename_pattern if isinstance(pattern, six.string_types) or callable(pattern): output_file = self.open_file(util.format_string(pattern, record_dict)) try: yield output_file finally: output_file.close() elif hasattr(self.filename_pattern, 'write'): yield self.filename_pattern else: raise ValueError( 'filename_pattern must be string, callable, or File-like object')
python
def open_output_file(self, test_record): # Ignore keys for the log filename to not convert larger data structures. record_dict = data.convert_to_base_types( test_record, ignore_keys=('code_info', 'phases', 'log_records')) pattern = self.filename_pattern if isinstance(pattern, six.string_types) or callable(pattern): output_file = self.open_file(util.format_string(pattern, record_dict)) try: yield output_file finally: output_file.close() elif hasattr(self.filename_pattern, 'write'): yield self.filename_pattern else: raise ValueError( 'filename_pattern must be string, callable, or File-like object')
[ "def", "open_output_file", "(", "self", ",", "test_record", ")", ":", "# Ignore keys for the log filename to not convert larger data structures.", "record_dict", "=", "data", ".", "convert_to_base_types", "(", "test_record", ",", "ignore_keys", "=", "(", "'code_info'", ",",...
Open file based on pattern.
[ "Open", "file", "based", "on", "pattern", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/__init__.py#L82-L98
240,831
google/openhtf
pylint_plugins/mutablerecords_plugin.py
mutable_record_transform
def mutable_record_transform(cls): """Transform mutable records usage by updating locals.""" if not (len(cls.bases) > 0 and isinstance(cls.bases[0], astroid.Call) and cls.bases[0].func.as_string() == 'mutablerecords.Record'): return try: # Add required attributes. if len(cls.bases[0].args) >= 2: for a in cls.bases[0].args[1].elts: cls.locals[a] = [None] # Add optional attributes. if len(cls.bases[0].args) >= 3: for a,b in cls.bases[0].args[2].items: cls.locals[a.value] = [None] except: raise SyntaxError('Invalid mutablerecords syntax')
python
def mutable_record_transform(cls): if not (len(cls.bases) > 0 and isinstance(cls.bases[0], astroid.Call) and cls.bases[0].func.as_string() == 'mutablerecords.Record'): return try: # Add required attributes. if len(cls.bases[0].args) >= 2: for a in cls.bases[0].args[1].elts: cls.locals[a] = [None] # Add optional attributes. if len(cls.bases[0].args) >= 3: for a,b in cls.bases[0].args[2].items: cls.locals[a.value] = [None] except: raise SyntaxError('Invalid mutablerecords syntax')
[ "def", "mutable_record_transform", "(", "cls", ")", ":", "if", "not", "(", "len", "(", "cls", ".", "bases", ")", ">", "0", "and", "isinstance", "(", "cls", ".", "bases", "[", "0", "]", ",", "astroid", ".", "Call", ")", "and", "cls", ".", "bases", ...
Transform mutable records usage by updating locals.
[ "Transform", "mutable", "records", "usage", "by", "updating", "locals", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/mutablerecords_plugin.py#L25-L44
240,832
google/openhtf
openhtf/util/__init__.py
_log_every_n_to_logger
def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name """Logs the given message every n calls to a logger. Args: n: Number of calls before logging. logger: The logger to which to log. level: The logging level (e.g. logging.INFO). message: A message to log *args: Any format args for the message. Returns: A method that logs and returns True every n calls. """ logger = logger or logging.getLogger() def _gen(): # pylint: disable=missing-docstring while True: for _ in range(n): yield False logger.log(level, message, *args) yield True gen = _gen() return lambda: six.next(gen)
python
def _log_every_n_to_logger(n, logger, level, message, *args): # pylint: disable=invalid-name logger = logger or logging.getLogger() def _gen(): # pylint: disable=missing-docstring while True: for _ in range(n): yield False logger.log(level, message, *args) yield True gen = _gen() return lambda: six.next(gen)
[ "def", "_log_every_n_to_logger", "(", "n", ",", "logger", ",", "level", ",", "message", ",", "*", "args", ")", ":", "# pylint: disable=invalid-name", "logger", "=", "logger", "or", "logging", ".", "getLogger", "(", ")", "def", "_gen", "(", ")", ":", "# pyl...
Logs the given message every n calls to a logger. Args: n: Number of calls before logging. logger: The logger to which to log. level: The logging level (e.g. logging.INFO). message: A message to log *args: Any format args for the message. Returns: A method that logs and returns True every n calls.
[ "Logs", "the", "given", "message", "every", "n", "calls", "to", "a", "logger", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L29-L49
240,833
google/openhtf
openhtf/util/__init__.py
log_every_n
def log_every_n(n, level, message, *args): # pylint: disable=invalid-name """Logs a message every n calls. See _log_every_n_to_logger.""" return _log_every_n_to_logger(n, None, level, message, *args)
python
def log_every_n(n, level, message, *args): # pylint: disable=invalid-name return _log_every_n_to_logger(n, None, level, message, *args)
[ "def", "log_every_n", "(", "n", ",", "level", ",", "message", ",", "*", "args", ")", ":", "# pylint: disable=invalid-name", "return", "_log_every_n_to_logger", "(", "n", ",", "None", ",", "level", ",", "message", ",", "*", "args", ")" ]
Logs a message every n calls. See _log_every_n_to_logger.
[ "Logs", "a", "message", "every", "n", "calls", ".", "See", "_log_every_n_to_logger", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L52-L54
240,834
google/openhtf
openhtf/util/__init__.py
partial_format
def partial_format(target, **kwargs): """Formats a string without requiring all values to be present. This function allows substitutions to be gradually made in several steps rather than all at once. Similar to string.Template.safe_substitute. """ output = target[:] for tag, var in re.findall(r'(\{(.*?)\})', output): root = var.split('.')[0] # dot notation root = root.split('[')[0] # dict notation if root in kwargs: output = output.replace(tag, tag.format(**{root: kwargs[root]})) return output
python
def partial_format(target, **kwargs): output = target[:] for tag, var in re.findall(r'(\{(.*?)\})', output): root = var.split('.')[0] # dot notation root = root.split('[')[0] # dict notation if root in kwargs: output = output.replace(tag, tag.format(**{root: kwargs[root]})) return output
[ "def", "partial_format", "(", "target", ",", "*", "*", "kwargs", ")", ":", "output", "=", "target", "[", ":", "]", "for", "tag", ",", "var", "in", "re", ".", "findall", "(", "r'(\\{(.*?)\\})'", ",", "output", ")", ":", "root", "=", "var", ".", "spl...
Formats a string without requiring all values to be present. This function allows substitutions to be gradually made in several steps rather than all at once. Similar to string.Template.safe_substitute.
[ "Formats", "a", "string", "without", "requiring", "all", "values", "to", "be", "present", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L96-L110
240,835
google/openhtf
openhtf/util/__init__.py
SubscribableStateMixin.asdict_with_event
def asdict_with_event(self): """Get a dict representation of this object and an update event. Returns: state: Dict representation of this object. update_event: An event that is guaranteed to be set if an update has been triggered since the returned dict was generated. """ event = threading.Event() with self._lock: self._update_events.add(event) return self._asdict(), event
python
def asdict_with_event(self): event = threading.Event() with self._lock: self._update_events.add(event) return self._asdict(), event
[ "def", "asdict_with_event", "(", "self", ")", ":", "event", "=", "threading", ".", "Event", "(", ")", "with", "self", ".", "_lock", ":", "self", ".", "_update_events", ".", "add", "(", "event", ")", "return", "self", ".", "_asdict", "(", ")", ",", "e...
Get a dict representation of this object and an update event. Returns: state: Dict representation of this object. update_event: An event that is guaranteed to be set if an update has been triggered since the returned dict was generated.
[ "Get", "a", "dict", "representation", "of", "this", "object", "and", "an", "update", "event", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L158-L169
240,836
google/openhtf
openhtf/util/__init__.py
SubscribableStateMixin.notify_update
def notify_update(self): """Notify any update events that there was an update.""" with self._lock: for event in self._update_events: event.set() self._update_events.clear()
python
def notify_update(self): with self._lock: for event in self._update_events: event.set() self._update_events.clear()
[ "def", "notify_update", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "for", "event", "in", "self", ".", "_update_events", ":", "event", ".", "set", "(", ")", "self", ".", "_update_events", ".", "clear", "(", ")" ]
Notify any update events that there was an update.
[ "Notify", "any", "update", "events", "that", "there", "was", "an", "update", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/__init__.py#L171-L176
240,837
google/openhtf
openhtf/output/servers/web_gui_server.py
bind_port
def bind_port(requested_port): """Bind sockets to an available port, returning sockets and the bound port.""" sockets = tornado.netutil.bind_sockets(requested_port) if requested_port != 0: return sockets, requested_port # Get the actual port number. for s in sockets: host, port = s.getsockname()[:2] if host == '0.0.0.0': return sockets, port raise RuntimeError('Could not determine the bound port.')
python
def bind_port(requested_port): sockets = tornado.netutil.bind_sockets(requested_port) if requested_port != 0: return sockets, requested_port # Get the actual port number. for s in sockets: host, port = s.getsockname()[:2] if host == '0.0.0.0': return sockets, port raise RuntimeError('Could not determine the bound port.')
[ "def", "bind_port", "(", "requested_port", ")", ":", "sockets", "=", "tornado", ".", "netutil", ".", "bind_sockets", "(", "requested_port", ")", "if", "requested_port", "!=", "0", ":", "return", "sockets", ",", "requested_port", "# Get the actual port number.", "f...
Bind sockets to an available port, returning sockets and the bound port.
[ "Bind", "sockets", "to", "an", "available", "port", "returning", "sockets", "and", "the", "bound", "port", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/web_gui_server.py#L47-L60
240,838
google/openhtf
openhtf/util/timeouts.py
loop_until_timeout_or_valid
def loop_until_timeout_or_valid(timeout_s, function, validation_fn, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns valid or a timeout is reached. Note: The function may return anything which, when passed to validation_fn, evaluates to implicit True. This function will loop calling the function as long as the result of validation_fn(function_result) returns something which evaluates to False. We ensure function is called at least once regardless of timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. validation_fn: The validation function called on the function result to determine whether to keep looping. sleep_s: The number of seconds to wait after calling the function. Returns: Whatever the function returned last. """ if timeout_s is None or not hasattr(timeout_s, 'has_expired'): timeout_s = PolledTimeout(timeout_s) while True: # Calls the function at least once result = function() if validation_fn(result) or timeout_s.has_expired(): return result time.sleep(sleep_s)
python
def loop_until_timeout_or_valid(timeout_s, function, validation_fn, sleep_s=1): # pylint: disable=invalid-name if timeout_s is None or not hasattr(timeout_s, 'has_expired'): timeout_s = PolledTimeout(timeout_s) while True: # Calls the function at least once result = function() if validation_fn(result) or timeout_s.has_expired(): return result time.sleep(sleep_s)
[ "def", "loop_until_timeout_or_valid", "(", "timeout_s", ",", "function", ",", "validation_fn", ",", "sleep_s", "=", "1", ")", ":", "# pylint: disable=invalid-name", "if", "timeout_s", "is", "None", "or", "not", "hasattr", "(", "timeout_s", ",", "'has_expired'", ")...
Loops until the specified function returns valid or a timeout is reached. Note: The function may return anything which, when passed to validation_fn, evaluates to implicit True. This function will loop calling the function as long as the result of validation_fn(function_result) returns something which evaluates to False. We ensure function is called at least once regardless of timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. validation_fn: The validation function called on the function result to determine whether to keep looping. sleep_s: The number of seconds to wait after calling the function. Returns: Whatever the function returned last.
[ "Loops", "until", "the", "specified", "function", "returns", "valid", "or", "a", "timeout", "is", "reached", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L122-L151
240,839
google/openhtf
openhtf/util/timeouts.py
loop_until_timeout_or_true
def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to return something which evaluates to False. We ensure this method is called at least once regardless of timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. sleep_s: The number of seconds to wait after calling the function. Returns: Whatever the function returned last. """ return loop_until_timeout_or_valid(timeout_s, function, lambda x: x, sleep_s)
python
def loop_until_timeout_or_true(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name return loop_until_timeout_or_valid(timeout_s, function, lambda x: x, sleep_s)
[ "def", "loop_until_timeout_or_true", "(", "timeout_s", ",", "function", ",", "sleep_s", "=", "1", ")", ":", "# pylint: disable=invalid-name", "return", "loop_until_timeout_or_valid", "(", "timeout_s", ",", "function", ",", "lambda", "x", ":", "x", ",", "sleep_s", ...
Loops until the specified function returns True or a timeout is reached. Note: The function may return anything which evaluates to implicit True. This function will loop calling it as long as it continues to return something which evaluates to False. We ensure this method is called at least once regardless of timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. sleep_s: The number of seconds to wait after calling the function. Returns: Whatever the function returned last.
[ "Loops", "until", "the", "specified", "function", "returns", "True", "or", "a", "timeout", "is", "reached", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L154-L172
240,840
google/openhtf
openhtf/util/timeouts.py
loop_until_timeout_or_not_none
def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name """Loops until the specified function returns non-None or until a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. sleep_s: The number of seconds to wait after calling the function. Returns: Whatever the function returned last. """ return loop_until_timeout_or_valid( timeout_s, function, lambda x: x is not None, sleep_s)
python
def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name return loop_until_timeout_or_valid( timeout_s, function, lambda x: x is not None, sleep_s)
[ "def", "loop_until_timeout_or_not_none", "(", "timeout_s", ",", "function", ",", "sleep_s", "=", "1", ")", ":", "# pylint: disable=invalid-name", "return", "loop_until_timeout_or_valid", "(", "timeout_s", ",", "function", ",", "lambda", "x", ":", "x", "is", "not", ...
Loops until the specified function returns non-None or until a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. sleep_s: The number of seconds to wait after calling the function. Returns: Whatever the function returned last.
[ "Loops", "until", "the", "specified", "function", "returns", "non", "-", "None", "or", "until", "a", "timeout", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L175-L189
240,841
google/openhtf
openhtf/util/timeouts.py
loop_until_true_else_raise
def loop_until_true_else_raise(timeout_s, function, invert=False, message=None, sleep_s=1): """Repeatedly call the given function until truthy, or raise on a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. invert: If True, wait for the callable to return falsey instead of truthy. message: Optional custom error message to use on a timeout. sleep_s: Seconds to sleep between call attempts. Returns: The final return value of the function. Raises: RuntimeError if the timeout is reached before the function returns truthy. """ def validate(x): return bool(x) != invert result = loop_until_timeout_or_valid(timeout_s, function, validate, sleep_s=1) if validate(result): return result if message is not None: raise RuntimeError(message) name = '(unknown)' if hasattr(function, '__name__'): name = function.__name__ elif (isinstance(function, functools.partial) and hasattr(function.func, '__name__')): name = function.func.__name__ raise RuntimeError( 'Function %s failed to return %s within %d seconds.' % (name, 'falsey' if invert else 'truthy', timeout_s))
python
def loop_until_true_else_raise(timeout_s, function, invert=False, message=None, sleep_s=1): def validate(x): return bool(x) != invert result = loop_until_timeout_or_valid(timeout_s, function, validate, sleep_s=1) if validate(result): return result if message is not None: raise RuntimeError(message) name = '(unknown)' if hasattr(function, '__name__'): name = function.__name__ elif (isinstance(function, functools.partial) and hasattr(function.func, '__name__')): name = function.func.__name__ raise RuntimeError( 'Function %s failed to return %s within %d seconds.' % (name, 'falsey' if invert else 'truthy', timeout_s))
[ "def", "loop_until_true_else_raise", "(", "timeout_s", ",", "function", ",", "invert", "=", "False", ",", "message", "=", "None", ",", "sleep_s", "=", "1", ")", ":", "def", "validate", "(", "x", ")", ":", "return", "bool", "(", "x", ")", "!=", "invert"...
Repeatedly call the given function until truthy, or raise on a timeout. Args: timeout_s: The number of seconds to wait until a timeout condition is reached. As a convenience, this accepts None to mean never timeout. Can also be passed a PolledTimeout object instead of an integer. function: The function to call each iteration. invert: If True, wait for the callable to return falsey instead of truthy. message: Optional custom error message to use on a timeout. sleep_s: Seconds to sleep between call attempts. Returns: The final return value of the function. Raises: RuntimeError if the timeout is reached before the function returns truthy.
[ "Repeatedly", "call", "the", "given", "function", "until", "truthy", "or", "raise", "on", "a", "timeout", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L192-L232
240,842
google/openhtf
openhtf/util/timeouts.py
execute_forever
def execute_forever(method, interval_s): # pylint: disable=invalid-name """Executes a method forever at the specified interval. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object. """ interval = Interval(method) interval.start(interval_s) return interval
python
def execute_forever(method, interval_s): # pylint: disable=invalid-name interval = Interval(method) interval.start(interval_s) return interval
[ "def", "execute_forever", "(", "method", ",", "interval_s", ")", ":", "# pylint: disable=invalid-name", "interval", "=", "Interval", "(", "method", ")", "interval", ".", "start", "(", "interval_s", ")", "return", "interval" ]
Executes a method forever at the specified interval. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object.
[ "Executes", "a", "method", "forever", "at", "the", "specified", "interval", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L316-L328
240,843
google/openhtf
openhtf/util/timeouts.py
execute_until_false
def execute_until_false(method, interval_s): # pylint: disable=invalid-name """Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object. """ interval = Interval(method, stop_if_false=True) interval.start(interval_s) return interval
python
def execute_until_false(method, interval_s): # pylint: disable=invalid-name interval = Interval(method, stop_if_false=True) interval.start(interval_s) return interval
[ "def", "execute_until_false", "(", "method", ",", "interval_s", ")", ":", "# pylint: disable=invalid-name", "interval", "=", "Interval", "(", "method", ",", "stop_if_false", "=", "True", ")", "interval", ".", "start", "(", "interval_s", ")", "return", "interval" ]
Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object.
[ "Executes", "a", "method", "forever", "until", "the", "method", "returns", "a", "false", "value", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L331-L343
240,844
google/openhtf
openhtf/util/timeouts.py
retry_until_true_or_limit_reached
def retry_until_true_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit is hit or True is returned.""" return retry_until_valid_or_limit_reached( method, limit, lambda x: x, sleep_s, catch_exceptions)
python
def retry_until_true_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): return retry_until_valid_or_limit_reached( method, limit, lambda x: x, sleep_s, catch_exceptions)
[ "def", "retry_until_true_or_limit_reached", "(", "method", ",", "limit", ",", "sleep_s", "=", "1", ",", "catch_exceptions", "=", "(", ")", ")", ":", "return", "retry_until_valid_or_limit_reached", "(", "method", ",", "limit", ",", "lambda", "x", ":", "x", ",",...
Executes a method until the retry limit is hit or True is returned.
[ "Executes", "a", "method", "until", "the", "retry", "limit", "is", "hit", "or", "True", "is", "returned", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L347-L351
240,845
google/openhtf
openhtf/util/timeouts.py
retry_until_not_none_or_limit_reached
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit is hit or not None is returned.""" return retry_until_valid_or_limit_reached( method, limit, lambda x: x is not None, sleep_s, catch_exceptions)
python
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1, catch_exceptions=()): return retry_until_valid_or_limit_reached( method, limit, lambda x: x is not None, sleep_s, catch_exceptions)
[ "def", "retry_until_not_none_or_limit_reached", "(", "method", ",", "limit", ",", "sleep_s", "=", "1", ",", "catch_exceptions", "=", "(", ")", ")", ":", "return", "retry_until_valid_or_limit_reached", "(", "method", ",", "limit", ",", "lambda", "x", ":", "x", ...
Executes a method until the retry limit is hit or not None is returned.
[ "Executes", "a", "method", "until", "the", "retry", "limit", "is", "hit", "or", "not", "None", "is", "returned", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L354-L358
240,846
google/openhtf
openhtf/util/timeouts.py
retry_until_valid_or_limit_reached
def retry_until_valid_or_limit_reached(method, limit, validation_fn, sleep_s=1, catch_exceptions=()): """Executes a method until the retry limit or validation_fn returns True. The method is always called once so the effective lower limit for 'limit' is 1. Passing in a number less than 1 will still result it the method being called once. Args: method: The method to execute should take no arguments. limit: The number of times to try this method. Must be >0. validation_fn: The validation function called on the function result to determine whether to keep looping. sleep_s: The time to sleep in between invocations. catch_exceptions: Tuple of exception types to catch and count as failures. Returns: Whatever the method last returned, implicit False would indicate the method never succeeded. """ assert limit > 0, 'Limit must be greater than 0' def _execute_method(helper): try: return method() except catch_exceptions: if not helper.remaining: raise return None helper = RetryHelper(limit - 1) result = _execute_method(helper) while not validation_fn(result) and helper.retry_if_possible(): time.sleep(sleep_s) result = _execute_method(helper) return result
python
def retry_until_valid_or_limit_reached(method, limit, validation_fn, sleep_s=1, catch_exceptions=()): assert limit > 0, 'Limit must be greater than 0' def _execute_method(helper): try: return method() except catch_exceptions: if not helper.remaining: raise return None helper = RetryHelper(limit - 1) result = _execute_method(helper) while not validation_fn(result) and helper.retry_if_possible(): time.sleep(sleep_s) result = _execute_method(helper) return result
[ "def", "retry_until_valid_or_limit_reached", "(", "method", ",", "limit", ",", "validation_fn", ",", "sleep_s", "=", "1", ",", "catch_exceptions", "=", "(", ")", ")", ":", "assert", "limit", ">", "0", ",", "'Limit must be greater than 0'", "def", "_execute_method"...
Executes a method until the retry limit or validation_fn returns True. The method is always called once so the effective lower limit for 'limit' is 1. Passing in a number less than 1 will still result it the method being called once. Args: method: The method to execute should take no arguments. limit: The number of times to try this method. Must be >0. validation_fn: The validation function called on the function result to determine whether to keep looping. sleep_s: The time to sleep in between invocations. catch_exceptions: Tuple of exception types to catch and count as failures. Returns: Whatever the method last returned, implicit False would indicate the method never succeeded.
[ "Executes", "a", "method", "until", "the", "retry", "limit", "or", "validation_fn", "returns", "True", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L361-L395
240,847
google/openhtf
openhtf/util/timeouts.py
take_at_least_n_seconds
def take_at_least_n_seconds(time_s): """A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting. Args: time_s: The number of seconds this block should take. If it doesn't take at least this time, then this method blocks during __exit__. Yields: To do some actions then on completion waits the remaining time. """ timeout = PolledTimeout(time_s) yield while not timeout.has_expired(): time.sleep(timeout.remaining)
python
def take_at_least_n_seconds(time_s): timeout = PolledTimeout(time_s) yield while not timeout.has_expired(): time.sleep(timeout.remaining)
[ "def", "take_at_least_n_seconds", "(", "time_s", ")", ":", "timeout", "=", "PolledTimeout", "(", "time_s", ")", "yield", "while", "not", "timeout", ".", "has_expired", "(", ")", ":", "time", ".", "sleep", "(", "timeout", ".", "remaining", ")" ]
A context manager which ensures it takes at least time_s to execute. Example: with take_at_least_n_seconds(5): do.Something() do.SomethingElse() # if Something and SomethingElse took 3 seconds, the with block with sleep # for 2 seconds before exiting. Args: time_s: The number of seconds this block should take. If it doesn't take at least this time, then this method blocks during __exit__. Yields: To do some actions then on completion waits the remaining time.
[ "A", "context", "manager", "which", "ensures", "it", "takes", "at", "least", "time_s", "to", "execute", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L401-L419
240,848
google/openhtf
openhtf/util/timeouts.py
take_at_most_n_seconds
def take_at_most_n_seconds(time_s, func, *args, **kwargs): """A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call the function with. **kwargs: Keyword arguments to call the function with. Returns: True if the function finished in less than time_s seconds. """ thread = threading.Thread(target=func, args=args, kwargs=kwargs) thread.start() thread.join(time_s) if thread.is_alive(): return False return True
python
def take_at_most_n_seconds(time_s, func, *args, **kwargs): thread = threading.Thread(target=func, args=args, kwargs=kwargs) thread.start() thread.join(time_s) if thread.is_alive(): return False return True
[ "def", "take_at_most_n_seconds", "(", "time_s", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "func", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "thr...
A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call the function with. **kwargs: Keyword arguments to call the function with. Returns: True if the function finished in less than time_s seconds.
[ "A", "function", "that", "returns", "whether", "a", "function", "call", "took", "less", "than", "time_s", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L422-L440
240,849
google/openhtf
openhtf/util/timeouts.py
execute_after_delay
def execute_after_delay(time_s, func, *args, **kwargs): """A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledTimeout with no expiration, then this method simply returns immediately and does nothing. Args: time_s: Delay in seconds to wait before executing func, may be a PolledTimeout object. func: Function to call. *args: Arguments to call the function with. **kwargs: Keyword arguments to call the function with. """ timeout = PolledTimeout.from_seconds(time_s) def target(): time.sleep(timeout.remaining) try: func(*args, **kwargs) except Exception: # pylint: disable=broad-except _LOG.exception('Error executing %s after %s expires.', func, timeout) if timeout.remaining is not None: thread = threading.Thread(target=target) thread.start()
python
def execute_after_delay(time_s, func, *args, **kwargs): timeout = PolledTimeout.from_seconds(time_s) def target(): time.sleep(timeout.remaining) try: func(*args, **kwargs) except Exception: # pylint: disable=broad-except _LOG.exception('Error executing %s after %s expires.', func, timeout) if timeout.remaining is not None: thread = threading.Thread(target=target) thread.start()
[ "def", "execute_after_delay", "(", "time_s", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "PolledTimeout", ".", "from_seconds", "(", "time_s", ")", "def", "target", "(", ")", ":", "time", ".", "sleep", "(", "timeout...
A function that executes the given function after a delay. Executes func in a separate thread after a delay, so that this function returns immediately. Note that any exceptions raised by func will be ignored (but logged). Also, if time_s is a PolledTimeout with no expiration, then this method simply returns immediately and does nothing. Args: time_s: Delay in seconds to wait before executing func, may be a PolledTimeout object. func: Function to call. *args: Arguments to call the function with. **kwargs: Keyword arguments to call the function with.
[ "A", "function", "that", "executes", "the", "given", "function", "after", "a", "delay", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L443-L468
240,850
google/openhtf
openhtf/util/timeouts.py
PolledTimeout.from_millis
def from_millis(cls, timeout_ms): """Create a new PolledTimeout if needed. If timeout_ms is already a PolledTimeout, just return it, otherwise create a new PolledTimeout with the given timeout in milliseconds. Args: timeout_ms: PolledTimeout object, or number of milliseconds to use for creating a new one. Returns: A PolledTimeout object that will expire in timeout_ms milliseconds, which may be timeout_ms itself, or a newly allocated PolledTimeout. """ if hasattr(timeout_ms, 'has_expired'): return timeout_ms if timeout_ms is None: return cls(None) return cls(timeout_ms / 1000.0)
python
def from_millis(cls, timeout_ms): if hasattr(timeout_ms, 'has_expired'): return timeout_ms if timeout_ms is None: return cls(None) return cls(timeout_ms / 1000.0)
[ "def", "from_millis", "(", "cls", ",", "timeout_ms", ")", ":", "if", "hasattr", "(", "timeout_ms", ",", "'has_expired'", ")", ":", "return", "timeout_ms", "if", "timeout_ms", "is", "None", ":", "return", "cls", "(", "None", ")", "return", "cls", "(", "ti...
Create a new PolledTimeout if needed. If timeout_ms is already a PolledTimeout, just return it, otherwise create a new PolledTimeout with the given timeout in milliseconds. Args: timeout_ms: PolledTimeout object, or number of milliseconds to use for creating a new one. Returns: A PolledTimeout object that will expire in timeout_ms milliseconds, which may be timeout_ms itself, or a newly allocated PolledTimeout.
[ "Create", "a", "new", "PolledTimeout", "if", "needed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L41-L59
240,851
google/openhtf
openhtf/util/timeouts.py
Interval.start
def start(self, interval_s): """Starts executing the method at the specified interval. Args: interval_s: The amount of time between executions of the method. Returns: False if the interval was already running. """ if self.running: return False self.stopped.clear() def _execute(): # Always execute immediately once if not self.method() and self.stop_if_false: return while not self.stopped.wait(interval_s): if not self.method() and self.stop_if_false: return self.thread = threading.Thread(target=_execute) self.thread.daemon = True self.thread.start() return True
python
def start(self, interval_s): if self.running: return False self.stopped.clear() def _execute(): # Always execute immediately once if not self.method() and self.stop_if_false: return while not self.stopped.wait(interval_s): if not self.method() and self.stop_if_false: return self.thread = threading.Thread(target=_execute) self.thread.daemon = True self.thread.start() return True
[ "def", "start", "(", "self", ",", "interval_s", ")", ":", "if", "self", ".", "running", ":", "return", "False", "self", ".", "stopped", ".", "clear", "(", ")", "def", "_execute", "(", ")", ":", "# Always execute immediately once", "if", "not", "self", "....
Starts executing the method at the specified interval. Args: interval_s: The amount of time between executions of the method. Returns: False if the interval was already running.
[ "Starts", "executing", "the", "method", "at", "the", "specified", "interval", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L257-L281
240,852
google/openhtf
openhtf/util/timeouts.py
Interval.stop
def stop(self, timeout_s=None): """Stops the interval. If a timeout is provided and stop returns False then the thread is effectively abandoned in whatever state it was in (presumably dead-locked). Args: timeout_s: The time in seconds to wait on the thread to finish. By default it's forever. Returns: False if a timeout was provided and we timed out. """ self.stopped.set() if self.thread: self.thread.join(timeout_s) return not self.thread.isAlive() else: return True
python
def stop(self, timeout_s=None): self.stopped.set() if self.thread: self.thread.join(timeout_s) return not self.thread.isAlive() else: return True
[ "def", "stop", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "self", ".", "stopped", ".", "set", "(", ")", "if", "self", ".", "thread", ":", "self", ".", "thread", ".", "join", "(", "timeout_s", ")", "return", "not", "self", ".", "thread", ...
Stops the interval. If a timeout is provided and stop returns False then the thread is effectively abandoned in whatever state it was in (presumably dead-locked). Args: timeout_s: The time in seconds to wait on the thread to finish. By default it's forever. Returns: False if a timeout was provided and we timed out.
[ "Stops", "the", "interval", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L283-L300
240,853
google/openhtf
openhtf/util/timeouts.py
Interval.join
def join(self, timeout_s=None): """Joins blocking until the interval ends or until timeout is reached. Args: timeout_s: The time in seconds to wait, defaults to forever. Returns: True if the interval is still running and we reached the timeout. """ if not self.thread: return False self.thread.join(timeout_s) return self.running
python
def join(self, timeout_s=None): if not self.thread: return False self.thread.join(timeout_s) return self.running
[ "def", "join", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "if", "not", "self", ".", "thread", ":", "return", "False", "self", ".", "thread", ".", "join", "(", "timeout_s", ")", "return", "self", ".", "running" ]
Joins blocking until the interval ends or until timeout is reached. Args: timeout_s: The time in seconds to wait, defaults to forever. Returns: True if the interval is still running and we reached the timeout.
[ "Joins", "blocking", "until", "the", "interval", "ends", "or", "until", "timeout", "is", "reached", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/timeouts.py#L302-L313
240,854
google/openhtf
pylint_plugins/conf_plugin.py
transform_declare
def transform_declare(node): """Transform conf.declare calls by stashing the declared names.""" global CURRENT_ROOT if not (isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name == 'conf' and node.func.attrname == 'declare'): return conf_key_name = None if node.args: conf_key_name = node.args[0].value else: for keyword in node.keywords: if keyword.arg == 'name': # Assume the name is an astroid.Const(str), so it has a str value. conf_key_name = keyword.value.value break assert conf_key_name != None, "Invalid conf.declare() syntax" if CONF_NODE: # Keep track of the current root, refreshing the locals if it changes. if not CURRENT_ROOT or CURRENT_ROOT != node.root(): CURRENT_ROOT = node.root() CONF_NODE.locals = CONF_LOCALS CONF_NODE.locals[conf_key_name] = [None] else: CONF_LOCALS[conf_key_name] = [None]
python
def transform_declare(node): global CURRENT_ROOT if not (isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name == 'conf' and node.func.attrname == 'declare'): return conf_key_name = None if node.args: conf_key_name = node.args[0].value else: for keyword in node.keywords: if keyword.arg == 'name': # Assume the name is an astroid.Const(str), so it has a str value. conf_key_name = keyword.value.value break assert conf_key_name != None, "Invalid conf.declare() syntax" if CONF_NODE: # Keep track of the current root, refreshing the locals if it changes. if not CURRENT_ROOT or CURRENT_ROOT != node.root(): CURRENT_ROOT = node.root() CONF_NODE.locals = CONF_LOCALS CONF_NODE.locals[conf_key_name] = [None] else: CONF_LOCALS[conf_key_name] = [None]
[ "def", "transform_declare", "(", "node", ")", ":", "global", "CURRENT_ROOT", "if", "not", "(", "isinstance", "(", "node", ".", "func", ",", "astroid", ".", "Attribute", ")", "and", "isinstance", "(", "node", ".", "func", ".", "expr", ",", "astroid", ".",...
Transform conf.declare calls by stashing the declared names.
[ "Transform", "conf", ".", "declare", "calls", "by", "stashing", "the", "declared", "names", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L30-L59
240,855
google/openhtf
pylint_plugins/conf_plugin.py
transform_conf_module
def transform_conf_module(cls): """Transform usages of the conf module by updating locals.""" global CONF_NODE if cls.name == 'openhtf.conf': # Put all the attributes in Configuration into the openhtf.conf node. cls._locals.update(cls.locals['Configuration'][0].locals) # Store reference to this node for future use. CONF_NODE = cls CONF_LOCALS.update(cls.locals)
python
def transform_conf_module(cls): global CONF_NODE if cls.name == 'openhtf.conf': # Put all the attributes in Configuration into the openhtf.conf node. cls._locals.update(cls.locals['Configuration'][0].locals) # Store reference to this node for future use. CONF_NODE = cls CONF_LOCALS.update(cls.locals)
[ "def", "transform_conf_module", "(", "cls", ")", ":", "global", "CONF_NODE", "if", "cls", ".", "name", "==", "'openhtf.conf'", ":", "# Put all the attributes in Configuration into the openhtf.conf node.", "cls", ".", "_locals", ".", "update", "(", "cls", ".", "locals"...
Transform usages of the conf module by updating locals.
[ "Transform", "usages", "of", "the", "conf", "module", "by", "updating", "locals", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L62-L72
240,856
google/openhtf
pylint_plugins/conf_plugin.py
register
def register(linter): """Register all transforms with the linter.""" MANAGER.register_transform(astroid.Call, transform_declare) MANAGER.register_transform(astroid.Module, transform_conf_module)
python
def register(linter): MANAGER.register_transform(astroid.Call, transform_declare) MANAGER.register_transform(astroid.Module, transform_conf_module)
[ "def", "register", "(", "linter", ")", ":", "MANAGER", ".", "register_transform", "(", "astroid", ".", "Call", ",", "transform_declare", ")", "MANAGER", ".", "register_transform", "(", "astroid", ".", "Module", ",", "transform_conf_module", ")" ]
Register all transforms with the linter.
[ "Register", "all", "transforms", "with", "the", "linter", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/pylint_plugins/conf_plugin.py#L75-L78
240,857
google/openhtf
openhtf/plugs/user_input.py
ConsolePrompt.run
def run(self): """Main logic for this thread to execute.""" if platform.system() == 'Windows': # Windows doesn't support file-like objects for select(), so fall back # to raw_input(). response = input(''.join((self._message, os.linesep, PROMPT))) self._answered = True self._callback(response) return # First, display the prompt to the console. console_output.cli_print(self._message, color=self._color, end=os.linesep, logger=None) console_output.cli_print(PROMPT, color=self._color, end='', logger=None) sys.stdout.flush() # Before reading, clear any lingering buffered terminal input. termios.tcflush(sys.stdin, termios.TCIFLUSH) line = '' while not self._stop_event.is_set(): inputs, _, _ = select.select([sys.stdin], [], [], 0.001) if sys.stdin in inputs: new = os.read(sys.stdin.fileno(), 1024) if not new: # Hit EOF! # They hit ^D (to insert EOF). Tell them to hit ^C if they # want to actually quit. print('Hit ^C (Ctrl+c) to exit.') break line += new.decode('utf-8') if '\n' in line: response = line[:line.find('\n')] self._answered = True self._callback(response) return
python
def run(self): if platform.system() == 'Windows': # Windows doesn't support file-like objects for select(), so fall back # to raw_input(). response = input(''.join((self._message, os.linesep, PROMPT))) self._answered = True self._callback(response) return # First, display the prompt to the console. console_output.cli_print(self._message, color=self._color, end=os.linesep, logger=None) console_output.cli_print(PROMPT, color=self._color, end='', logger=None) sys.stdout.flush() # Before reading, clear any lingering buffered terminal input. termios.tcflush(sys.stdin, termios.TCIFLUSH) line = '' while not self._stop_event.is_set(): inputs, _, _ = select.select([sys.stdin], [], [], 0.001) if sys.stdin in inputs: new = os.read(sys.stdin.fileno(), 1024) if not new: # Hit EOF! # They hit ^D (to insert EOF). Tell them to hit ^C if they # want to actually quit. print('Hit ^C (Ctrl+c) to exit.') break line += new.decode('utf-8') if '\n' in line: response = line[:line.find('\n')] self._answered = True self._callback(response) return
[ "def", "run", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "# Windows doesn't support file-like objects for select(), so fall back", "# to raw_input().", "response", "=", "input", "(", "''", ".", "join", "(", "(", "self...
Main logic for this thread to execute.
[ "Main", "logic", "for", "this", "thread", "to", "execute", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L90-L127
240,858
google/openhtf
openhtf/plugs/user_input.py
UserInput._asdict
def _asdict(self): """Return a dictionary representation of the current prompt.""" with self._cond: if self._prompt is None: return return {'id': self._prompt.id, 'message': self._prompt.message, 'text-input': self._prompt.text_input}
python
def _asdict(self): with self._cond: if self._prompt is None: return return {'id': self._prompt.id, 'message': self._prompt.message, 'text-input': self._prompt.text_input}
[ "def", "_asdict", "(", "self", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_prompt", "is", "None", ":", "return", "return", "{", "'id'", ":", "self", ".", "_prompt", ".", "id", ",", "'message'", ":", "self", ".", "_prompt", "."...
Return a dictionary representation of the current prompt.
[ "Return", "a", "dictionary", "representation", "of", "the", "current", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L146-L153
240,859
google/openhtf
openhtf/plugs/user_input.py
UserInput.remove_prompt
def remove_prompt(self): """Remove the prompt.""" with self._cond: self._prompt = None if self._console_prompt: self._console_prompt.Stop() self._console_prompt = None self.notify_update()
python
def remove_prompt(self): with self._cond: self._prompt = None if self._console_prompt: self._console_prompt.Stop() self._console_prompt = None self.notify_update()
[ "def", "remove_prompt", "(", "self", ")", ":", "with", "self", ".", "_cond", ":", "self", ".", "_prompt", "=", "None", "if", "self", ".", "_console_prompt", ":", "self", ".", "_console_prompt", ".", "Stop", "(", ")", "self", ".", "_console_prompt", "=", ...
Remove the prompt.
[ "Remove", "the", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L158-L165
240,860
google/openhtf
openhtf/plugs/user_input.py
UserInput.prompt
def prompt(self, message, text_input=False, timeout_s=None, cli_color=''): """Display a prompt and wait for a response. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. timeout_s: Seconds to wait before raising a PromptUnansweredError. cli_color: An ANSI color code, or the empty string. Returns: A string response, or the empty string if text_input was False. Raises: MultiplePromptsError: There was already an existing prompt. PromptUnansweredError: Timed out waiting for the user to respond. """ self.start_prompt(message, text_input, cli_color) return self.wait_for_prompt(timeout_s)
python
def prompt(self, message, text_input=False, timeout_s=None, cli_color=''): self.start_prompt(message, text_input, cli_color) return self.wait_for_prompt(timeout_s)
[ "def", "prompt", "(", "self", ",", "message", ",", "text_input", "=", "False", ",", "timeout_s", "=", "None", ",", "cli_color", "=", "''", ")", ":", "self", ".", "start_prompt", "(", "message", ",", "text_input", ",", "cli_color", ")", "return", "self", ...
Display a prompt and wait for a response. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. timeout_s: Seconds to wait before raising a PromptUnansweredError. cli_color: An ANSI color code, or the empty string. Returns: A string response, or the empty string if text_input was False. Raises: MultiplePromptsError: There was already an existing prompt. PromptUnansweredError: Timed out waiting for the user to respond.
[ "Display", "a", "prompt", "and", "wait", "for", "a", "response", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L167-L184
240,861
google/openhtf
openhtf/plugs/user_input.py
UserInput.start_prompt
def start_prompt(self, message, text_input=False, cli_color=''): """Display a prompt. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. cli_color: An ANSI color code, or the empty string. Raises: MultiplePromptsError: There was already an existing prompt. Returns: A string uniquely identifying the prompt. """ with self._cond: if self._prompt: raise MultiplePromptsError prompt_id = uuid.uuid4().hex _LOG.debug('Displaying prompt (%s): "%s"%s', prompt_id, message, ', Expects text input.' if text_input else '') self._response = None self._prompt = Prompt( id=prompt_id, message=message, text_input=text_input) if sys.stdin.isatty(): self._console_prompt = ConsolePrompt( message, functools.partial(self.respond, prompt_id), cli_color) self._console_prompt.start() self.notify_update() return prompt_id
python
def start_prompt(self, message, text_input=False, cli_color=''): with self._cond: if self._prompt: raise MultiplePromptsError prompt_id = uuid.uuid4().hex _LOG.debug('Displaying prompt (%s): "%s"%s', prompt_id, message, ', Expects text input.' if text_input else '') self._response = None self._prompt = Prompt( id=prompt_id, message=message, text_input=text_input) if sys.stdin.isatty(): self._console_prompt = ConsolePrompt( message, functools.partial(self.respond, prompt_id), cli_color) self._console_prompt.start() self.notify_update() return prompt_id
[ "def", "start_prompt", "(", "self", ",", "message", ",", "text_input", "=", "False", ",", "cli_color", "=", "''", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_prompt", ":", "raise", "MultiplePromptsError", "prompt_id", "=", "uuid", "...
Display a prompt. Args: message: A string to be presented to the user. text_input: A boolean indicating whether the user must respond with text. cli_color: An ANSI color code, or the empty string. Raises: MultiplePromptsError: There was already an existing prompt. Returns: A string uniquely identifying the prompt.
[ "Display", "a", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L186-L216
240,862
google/openhtf
openhtf/plugs/user_input.py
UserInput.wait_for_prompt
def wait_for_prompt(self, timeout_s=None): """Wait for the user to respond to the current prompt. Args: timeout_s: Seconds to wait before raising a PromptUnansweredError. Returns: A string response, or the empty string if text_input was False. Raises: PromptUnansweredError: Timed out waiting for the user to respond. """ with self._cond: if self._prompt: if timeout_s is None: self._cond.wait(3600 * 24 * 365) else: self._cond.wait(timeout_s) if self._response is None: raise PromptUnansweredError return self._response
python
def wait_for_prompt(self, timeout_s=None): with self._cond: if self._prompt: if timeout_s is None: self._cond.wait(3600 * 24 * 365) else: self._cond.wait(timeout_s) if self._response is None: raise PromptUnansweredError return self._response
[ "def", "wait_for_prompt", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_prompt", ":", "if", "timeout_s", "is", "None", ":", "self", ".", "_cond", ".", "wait", "(", "3600", "*", "24", "...
Wait for the user to respond to the current prompt. Args: timeout_s: Seconds to wait before raising a PromptUnansweredError. Returns: A string response, or the empty string if text_input was False. Raises: PromptUnansweredError: Timed out waiting for the user to respond.
[ "Wait", "for", "the", "user", "to", "respond", "to", "the", "current", "prompt", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L218-L238
240,863
google/openhtf
openhtf/plugs/user_input.py
UserInput.respond
def respond(self, prompt_id, response): """Respond to the prompt with the given ID. If there is no active prompt or the given ID doesn't match the active prompt, do nothing. Args: prompt_id: A string uniquely identifying the prompt. response: A string response to the given prompt. Returns: True if the prompt with the given ID was active, otherwise False. """ _LOG.debug('Responding to prompt (%s): "%s"', prompt_id, response) with self._cond: if not (self._prompt and self._prompt.id == prompt_id): return False self._response = response self.last_response = (prompt_id, response) self.remove_prompt() self._cond.notifyAll() return True
python
def respond(self, prompt_id, response): _LOG.debug('Responding to prompt (%s): "%s"', prompt_id, response) with self._cond: if not (self._prompt and self._prompt.id == prompt_id): return False self._response = response self.last_response = (prompt_id, response) self.remove_prompt() self._cond.notifyAll() return True
[ "def", "respond", "(", "self", ",", "prompt_id", ",", "response", ")", ":", "_LOG", ".", "debug", "(", "'Responding to prompt (%s): \"%s\"'", ",", "prompt_id", ",", "response", ")", "with", "self", ".", "_cond", ":", "if", "not", "(", "self", ".", "_prompt...
Respond to the prompt with the given ID. If there is no active prompt or the given ID doesn't match the active prompt, do nothing. Args: prompt_id: A string uniquely identifying the prompt. response: A string response to the given prompt. Returns: True if the prompt with the given ID was active, otherwise False.
[ "Respond", "to", "the", "prompt", "with", "the", "given", "ID", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/user_input.py#L240-L261
240,864
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutionOutcome.is_terminal
def is_terminal(self): """True if this result will stop the test.""" return (self.raised_exception or self.is_timeout or self.phase_result == openhtf.PhaseResult.STOP)
python
def is_terminal(self): return (self.raised_exception or self.is_timeout or self.phase_result == openhtf.PhaseResult.STOP)
[ "def", "is_terminal", "(", "self", ")", ":", "return", "(", "self", ".", "raised_exception", "or", "self", ".", "is_timeout", "or", "self", ".", "phase_result", "==", "openhtf", ".", "PhaseResult", ".", "STOP", ")" ]
True if this result will stop the test.
[ "True", "if", "this", "result", "will", "stop", "the", "test", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L119-L122
240,865
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutorThread._thread_proc
def _thread_proc(self): """Execute the encompassed phase and save the result.""" # Call the phase, save the return value, or default it to CONTINUE. phase_return = self._phase_desc(self._test_state) if phase_return is None: phase_return = openhtf.PhaseResult.CONTINUE # If phase_return is invalid, this will raise, and _phase_execution_outcome # will get set to the InvalidPhaseResultError in _thread_exception instead. self._phase_execution_outcome = PhaseExecutionOutcome(phase_return)
python
def _thread_proc(self): # Call the phase, save the return value, or default it to CONTINUE. phase_return = self._phase_desc(self._test_state) if phase_return is None: phase_return = openhtf.PhaseResult.CONTINUE # If phase_return is invalid, this will raise, and _phase_execution_outcome # will get set to the InvalidPhaseResultError in _thread_exception instead. self._phase_execution_outcome = PhaseExecutionOutcome(phase_return)
[ "def", "_thread_proc", "(", "self", ")", ":", "# Call the phase, save the return value, or default it to CONTINUE.", "phase_return", "=", "self", ".", "_phase_desc", "(", "self", ".", "_test_state", ")", "if", "phase_return", "is", "None", ":", "phase_return", "=", "o...
Execute the encompassed phase and save the result.
[ "Execute", "the", "encompassed", "phase", "and", "save", "the", "result", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L152-L161
240,866
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutorThread.join_or_die
def join_or_die(self): """Wait for thread to finish, returning a PhaseExecutionOutcome instance.""" if self._phase_desc.options.timeout_s is not None: self.join(self._phase_desc.options.timeout_s) else: self.join(DEFAULT_PHASE_TIMEOUT_S) # We got a return value or an exception and handled it. if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome): return self._phase_execution_outcome # Check for timeout, indicated by None for # PhaseExecutionOutcome.phase_result. if self.is_alive(): self.kill() return PhaseExecutionOutcome(None) # Phase was killed. return PhaseExecutionOutcome(threads.ThreadTerminationError())
python
def join_or_die(self): if self._phase_desc.options.timeout_s is not None: self.join(self._phase_desc.options.timeout_s) else: self.join(DEFAULT_PHASE_TIMEOUT_S) # We got a return value or an exception and handled it. if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome): return self._phase_execution_outcome # Check for timeout, indicated by None for # PhaseExecutionOutcome.phase_result. if self.is_alive(): self.kill() return PhaseExecutionOutcome(None) # Phase was killed. return PhaseExecutionOutcome(threads.ThreadTerminationError())
[ "def", "join_or_die", "(", "self", ")", ":", "if", "self", ".", "_phase_desc", ".", "options", ".", "timeout_s", "is", "not", "None", ":", "self", ".", "join", "(", "self", ".", "_phase_desc", ".", "options", ".", "timeout_s", ")", "else", ":", "self",...
Wait for thread to finish, returning a PhaseExecutionOutcome instance.
[ "Wait", "for", "thread", "to", "finish", "returning", "a", "PhaseExecutionOutcome", "instance", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L172-L190
240,867
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutor.execute_phase
def execute_phase(self, phase): """Executes a phase or skips it, yielding PhaseExecutionOutcome instances. Args: phase: Phase to execute. Returns: The final PhaseExecutionOutcome that wraps the phase return value (or exception) of the final phase run. All intermediary results, if any, are REPEAT and handled internally. Returning REPEAT here means the phase hit its limit for repetitions. """ repeat_count = 1 repeat_limit = phase.options.repeat_limit or sys.maxsize while not self._stopping.is_set(): is_last_repeat = repeat_count >= repeat_limit phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat) if phase_execution_outcome.is_repeat and not is_last_repeat: repeat_count += 1 continue return phase_execution_outcome # We've been cancelled, so just 'timeout' the phase. return PhaseExecutionOutcome(None)
python
def execute_phase(self, phase): repeat_count = 1 repeat_limit = phase.options.repeat_limit or sys.maxsize while not self._stopping.is_set(): is_last_repeat = repeat_count >= repeat_limit phase_execution_outcome = self._execute_phase_once(phase, is_last_repeat) if phase_execution_outcome.is_repeat and not is_last_repeat: repeat_count += 1 continue return phase_execution_outcome # We've been cancelled, so just 'timeout' the phase. return PhaseExecutionOutcome(None)
[ "def", "execute_phase", "(", "self", ",", "phase", ")", ":", "repeat_count", "=", "1", "repeat_limit", "=", "phase", ".", "options", ".", "repeat_limit", "or", "sys", ".", "maxsize", "while", "not", "self", ".", "_stopping", ".", "is_set", "(", ")", ":",...
Executes a phase or skips it, yielding PhaseExecutionOutcome instances. Args: phase: Phase to execute. Returns: The final PhaseExecutionOutcome that wraps the phase return value (or exception) of the final phase run. All intermediary results, if any, are REPEAT and handled internally. Returning REPEAT here means the phase hit its limit for repetitions.
[ "Executes", "a", "phase", "or", "skips", "it", "yielding", "PhaseExecutionOutcome", "instances", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L211-L235
240,868
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutor._execute_phase_once
def _execute_phase_once(self, phase_desc, is_last_repeat): """Executes the given phase, returning a PhaseExecutionOutcome.""" # Check this before we create a PhaseState and PhaseRecord. if phase_desc.options.run_if and not phase_desc.options.run_if(): _LOG.debug('Phase %s skipped due to run_if returning falsey.', phase_desc.name) return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP) override_result = None with self.test_state.running_phase_context(phase_desc) as phase_state: _LOG.debug('Executing phase %s', phase_desc.name) with self._current_phase_thread_lock: # Checking _stopping must be in the lock context, otherwise there is a # race condition: this thread checks _stopping and then switches to # another thread where stop() sets _stopping and checks # _current_phase_thread (which would not be set yet). In that case, the # new phase thread will be still be started. if self._stopping.is_set(): # PhaseRecord will be written at this point, so ensure that it has a # Killed result. result = PhaseExecutionOutcome(threads.ThreadTerminationError()) phase_state.result = result return result phase_thread = PhaseExecutorThread(phase_desc, self.test_state) phase_thread.start() self._current_phase_thread = phase_thread phase_state.result = phase_thread.join_or_die() if phase_state.result.is_repeat and is_last_repeat: _LOG.error('Phase returned REPEAT, exceeding repeat_limit.') phase_state.hit_repeat_limit = True override_result = PhaseExecutionOutcome(openhtf.PhaseResult.STOP) self._current_phase_thread = None # Refresh the result in case a validation for a partially set measurement # raised an exception. result = override_result or phase_state.result _LOG.debug('Phase %s finished with result %s', phase_desc.name, result.phase_result) return result
python
def _execute_phase_once(self, phase_desc, is_last_repeat): # Check this before we create a PhaseState and PhaseRecord. if phase_desc.options.run_if and not phase_desc.options.run_if(): _LOG.debug('Phase %s skipped due to run_if returning falsey.', phase_desc.name) return PhaseExecutionOutcome(openhtf.PhaseResult.SKIP) override_result = None with self.test_state.running_phase_context(phase_desc) as phase_state: _LOG.debug('Executing phase %s', phase_desc.name) with self._current_phase_thread_lock: # Checking _stopping must be in the lock context, otherwise there is a # race condition: this thread checks _stopping and then switches to # another thread where stop() sets _stopping and checks # _current_phase_thread (which would not be set yet). In that case, the # new phase thread will be still be started. if self._stopping.is_set(): # PhaseRecord will be written at this point, so ensure that it has a # Killed result. result = PhaseExecutionOutcome(threads.ThreadTerminationError()) phase_state.result = result return result phase_thread = PhaseExecutorThread(phase_desc, self.test_state) phase_thread.start() self._current_phase_thread = phase_thread phase_state.result = phase_thread.join_or_die() if phase_state.result.is_repeat and is_last_repeat: _LOG.error('Phase returned REPEAT, exceeding repeat_limit.') phase_state.hit_repeat_limit = True override_result = PhaseExecutionOutcome(openhtf.PhaseResult.STOP) self._current_phase_thread = None # Refresh the result in case a validation for a partially set measurement # raised an exception. result = override_result or phase_state.result _LOG.debug('Phase %s finished with result %s', phase_desc.name, result.phase_result) return result
[ "def", "_execute_phase_once", "(", "self", ",", "phase_desc", ",", "is_last_repeat", ")", ":", "# Check this before we create a PhaseState and PhaseRecord.", "if", "phase_desc", ".", "options", ".", "run_if", "and", "not", "phase_desc", ".", "options", ".", "run_if", ...
Executes the given phase, returning a PhaseExecutionOutcome.
[ "Executes", "the", "given", "phase", "returning", "a", "PhaseExecutionOutcome", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L237-L276
240,869
google/openhtf
openhtf/core/phase_executor.py
PhaseExecutor.stop
def stop(self, timeout_s=None): """Stops execution of the current phase, if any. It will raise a ThreadTerminationError, which will cause the test to stop executing and terminate with an ERROR state. Args: timeout_s: int or None, timeout in seconds to wait for the phase to stop. """ self._stopping.set() with self._current_phase_thread_lock: phase_thread = self._current_phase_thread if not phase_thread: return if phase_thread.is_alive(): phase_thread.kill() _LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread) timeout = timeouts.PolledTimeout.from_seconds(timeout_s) while phase_thread.is_alive() and not timeout.has_expired(): time.sleep(0.1) _LOG.debug('Cancelled phase %s exit', "didn't" if phase_thread.is_alive() else 'did') # Clear the currently running phase, whether it finished or timed out. self.test_state.stop_running_phase()
python
def stop(self, timeout_s=None): self._stopping.set() with self._current_phase_thread_lock: phase_thread = self._current_phase_thread if not phase_thread: return if phase_thread.is_alive(): phase_thread.kill() _LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread) timeout = timeouts.PolledTimeout.from_seconds(timeout_s) while phase_thread.is_alive() and not timeout.has_expired(): time.sleep(0.1) _LOG.debug('Cancelled phase %s exit', "didn't" if phase_thread.is_alive() else 'did') # Clear the currently running phase, whether it finished or timed out. self.test_state.stop_running_phase()
[ "def", "stop", "(", "self", ",", "timeout_s", "=", "None", ")", ":", "self", ".", "_stopping", ".", "set", "(", ")", "with", "self", ".", "_current_phase_thread_lock", ":", "phase_thread", "=", "self", ".", "_current_phase_thread", "if", "not", "phase_thread...
Stops execution of the current phase, if any. It will raise a ThreadTerminationError, which will cause the test to stop executing and terminate with an ERROR state. Args: timeout_s: int or None, timeout in seconds to wait for the phase to stop.
[ "Stops", "execution", "of", "the", "current", "phase", "if", "any", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_executor.py#L281-L306
240,870
google/openhtf
openhtf/core/phase_group.py
load_code_info
def load_code_info(phases_or_groups): """Recursively load code info for a PhaseGroup or list of phases or groups.""" if isinstance(phases_or_groups, PhaseGroup): return phases_or_groups.load_code_info() ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.load_code_info()) else: ret.append( mutablerecords.CopyRecord( phase, code_info=test_record.CodeInfo.for_function(phase.func))) return ret
python
def load_code_info(phases_or_groups): if isinstance(phases_or_groups, PhaseGroup): return phases_or_groups.load_code_info() ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.load_code_info()) else: ret.append( mutablerecords.CopyRecord( phase, code_info=test_record.CodeInfo.for_function(phase.func))) return ret
[ "def", "load_code_info", "(", "phases_or_groups", ")", ":", "if", "isinstance", "(", "phases_or_groups", ",", "PhaseGroup", ")", ":", "return", "phases_or_groups", ".", "load_code_info", "(", ")", "ret", "=", "[", "]", "for", "phase", "in", "phases_or_groups", ...
Recursively load code info for a PhaseGroup or list of phases or groups.
[ "Recursively", "load", "code", "info", "for", "a", "PhaseGroup", "or", "list", "of", "phases", "or", "groups", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L192-L204
240,871
google/openhtf
openhtf/core/phase_group.py
flatten_phases_and_groups
def flatten_phases_and_groups(phases_or_groups): """Recursively flatten nested lists for the list of phases or groups.""" if isinstance(phases_or_groups, PhaseGroup): phases_or_groups = [phases_or_groups] ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.flatten()) elif isinstance(phase, collections.Iterable): ret.extend(flatten_phases_and_groups(phase)) else: ret.append(phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)) return ret
python
def flatten_phases_and_groups(phases_or_groups): if isinstance(phases_or_groups, PhaseGroup): phases_or_groups = [phases_or_groups] ret = [] for phase in phases_or_groups: if isinstance(phase, PhaseGroup): ret.append(phase.flatten()) elif isinstance(phase, collections.Iterable): ret.extend(flatten_phases_and_groups(phase)) else: ret.append(phase_descriptor.PhaseDescriptor.wrap_or_copy(phase)) return ret
[ "def", "flatten_phases_and_groups", "(", "phases_or_groups", ")", ":", "if", "isinstance", "(", "phases_or_groups", ",", "PhaseGroup", ")", ":", "phases_or_groups", "=", "[", "phases_or_groups", "]", "ret", "=", "[", "]", "for", "phase", "in", "phases_or_groups", ...
Recursively flatten nested lists for the list of phases or groups.
[ "Recursively", "flatten", "nested", "lists", "for", "the", "list", "of", "phases", "or", "groups", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L207-L219
240,872
google/openhtf
openhtf/core/phase_group.py
optionally_with_args
def optionally_with_args(phase, **kwargs): """Apply only the args that the phase knows. If the phase has a **kwargs-style argument, it counts as knowing all args. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply with_args to. **kwargs: arguments to apply to the phase. Returns: phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated args. """ if isinstance(phase, PhaseGroup): return phase.with_args(**kwargs) if isinstance(phase, collections.Iterable): return [optionally_with_args(p, **kwargs) for p in phase] if not isinstance(phase, phase_descriptor.PhaseDescriptor): phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase) return phase.with_known_args(**kwargs)
python
def optionally_with_args(phase, **kwargs): if isinstance(phase, PhaseGroup): return phase.with_args(**kwargs) if isinstance(phase, collections.Iterable): return [optionally_with_args(p, **kwargs) for p in phase] if not isinstance(phase, phase_descriptor.PhaseDescriptor): phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase) return phase.with_known_args(**kwargs)
[ "def", "optionally_with_args", "(", "phase", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "phase", ",", "PhaseGroup", ")", ":", "return", "phase", ".", "with_args", "(", "*", "*", "kwargs", ")", "if", "isinstance", "(", "phase", ",", "co...
Apply only the args that the phase knows. If the phase has a **kwargs-style argument, it counts as knowing all args. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply with_args to. **kwargs: arguments to apply to the phase. Returns: phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated args.
[ "Apply", "only", "the", "args", "that", "the", "phase", "knows", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L222-L244
240,873
google/openhtf
openhtf/core/phase_group.py
optionally_with_plugs
def optionally_with_plugs(phase, **subplugs): """Apply only the with_plugs that the phase knows. This will determine the subset of plug overrides for only plugs the phase actually has. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply the plug changes to. **subplugs: mapping from plug name to derived plug class, the subplugs to apply. Raises: openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid replacement for the specified plug name. Returns: phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated plugs. """ if isinstance(phase, PhaseGroup): return phase.with_plugs(**subplugs) if isinstance(phase, collections.Iterable): return [optionally_with_plugs(p, **subplugs) for p in phase] if not isinstance(phase, phase_descriptor.PhaseDescriptor): phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase) return phase.with_known_plugs(**subplugs)
python
def optionally_with_plugs(phase, **subplugs): if isinstance(phase, PhaseGroup): return phase.with_plugs(**subplugs) if isinstance(phase, collections.Iterable): return [optionally_with_plugs(p, **subplugs) for p in phase] if not isinstance(phase, phase_descriptor.PhaseDescriptor): phase = phase_descriptor.PhaseDescriptor.wrap_or_copy(phase) return phase.with_known_plugs(**subplugs)
[ "def", "optionally_with_plugs", "(", "phase", ",", "*", "*", "subplugs", ")", ":", "if", "isinstance", "(", "phase", ",", "PhaseGroup", ")", ":", "return", "phase", ".", "with_plugs", "(", "*", "*", "subplugs", ")", "if", "isinstance", "(", "phase", ",",...
Apply only the with_plugs that the phase knows. This will determine the subset of plug overrides for only plugs the phase actually has. Args: phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or iterable of those, the phase or phase group (or iterable) to apply the plug changes to. **subplugs: mapping from plug name to derived plug class, the subplugs to apply. Raises: openhtf.plugs.InvalidPlugError: if a specified subplug class is not a valid replacement for the specified plug name. Returns: phase_descriptor.PhaseDescriptor or PhaseGroup or iterable with the updated plugs.
[ "Apply", "only", "the", "with_plugs", "that", "the", "phase", "knows", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L247-L275
240,874
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.convert_if_not
def convert_if_not(cls, phases_or_groups): """Convert list of phases or groups into a new PhaseGroup if not already.""" if isinstance(phases_or_groups, PhaseGroup): return mutablerecords.CopyRecord(phases_or_groups) flattened = flatten_phases_and_groups(phases_or_groups) return cls(main=flattened)
python
def convert_if_not(cls, phases_or_groups): if isinstance(phases_or_groups, PhaseGroup): return mutablerecords.CopyRecord(phases_or_groups) flattened = flatten_phases_and_groups(phases_or_groups) return cls(main=flattened)
[ "def", "convert_if_not", "(", "cls", ",", "phases_or_groups", ")", ":", "if", "isinstance", "(", "phases_or_groups", ",", "PhaseGroup", ")", ":", "return", "mutablerecords", ".", "CopyRecord", "(", "phases_or_groups", ")", "flattened", "=", "flatten_phases_and_group...
Convert list of phases or groups into a new PhaseGroup if not already.
[ "Convert", "list", "of", "phases", "or", "groups", "into", "a", "new", "PhaseGroup", "if", "not", "already", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L79-L85
240,875
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.with_context
def with_context(cls, setup_phases, teardown_phases): """Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from the created function. teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the teardown for the PhaseGroup returned from the created function. Returns: Function that takes *phases and returns a PhaseGroup with the predefined setup and teardown phases, with *phases as the main phases. """ setup = flatten_phases_and_groups(setup_phases) teardown = flatten_phases_and_groups(teardown_phases) def _context_wrapper(*phases): return cls(setup=setup, main=flatten_phases_and_groups(phases), teardown=teardown) return _context_wrapper
python
def with_context(cls, setup_phases, teardown_phases): setup = flatten_phases_and_groups(setup_phases) teardown = flatten_phases_and_groups(teardown_phases) def _context_wrapper(*phases): return cls(setup=setup, main=flatten_phases_and_groups(phases), teardown=teardown) return _context_wrapper
[ "def", "with_context", "(", "cls", ",", "setup_phases", ",", "teardown_phases", ")", ":", "setup", "=", "flatten_phases_and_groups", "(", "setup_phases", ")", "teardown", "=", "flatten_phases_and_groups", "(", "teardown_phases", ")", "def", "_context_wrapper", "(", ...
Create PhaseGroup creator function with setup and teardown phases. Args: setup_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the setup for the PhaseGroup returned from the created function. teardown_phases: list of phase_descriptor.PhaseDescriptors/PhaseGroups/ callables/iterables, phases to run during the teardown for the PhaseGroup returned from the created function. Returns: Function that takes *phases and returns a PhaseGroup with the predefined setup and teardown phases, with *phases as the main phases.
[ "Create", "PhaseGroup", "creator", "function", "with", "setup", "and", "teardown", "phases", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L88-L110
240,876
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.combine
def combine(self, other, name=None): """Combine with another PhaseGroup and return the result.""" return PhaseGroup( setup=self.setup + other.setup, main=self.main + other.main, teardown=self.teardown + other.teardown, name=name)
python
def combine(self, other, name=None): return PhaseGroup( setup=self.setup + other.setup, main=self.main + other.main, teardown=self.teardown + other.teardown, name=name)
[ "def", "combine", "(", "self", ",", "other", ",", "name", "=", "None", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "self", ".", "setup", "+", "other", ".", "setup", ",", "main", "=", "self", ".", "main", "+", "other", ".", "main", ",", "...
Combine with another PhaseGroup and return the result.
[ "Combine", "with", "another", "PhaseGroup", "and", "return", "the", "result", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L122-L128
240,877
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.wrap
def wrap(self, main_phases, name=None): """Returns PhaseGroup with additional main phases.""" new_main = list(self.main) if isinstance(main_phases, collections.Iterable): new_main.extend(main_phases) else: new_main.append(main_phases) return PhaseGroup( setup=self.setup, main=new_main, teardown=self.teardown, name=name)
python
def wrap(self, main_phases, name=None): new_main = list(self.main) if isinstance(main_phases, collections.Iterable): new_main.extend(main_phases) else: new_main.append(main_phases) return PhaseGroup( setup=self.setup, main=new_main, teardown=self.teardown, name=name)
[ "def", "wrap", "(", "self", ",", "main_phases", ",", "name", "=", "None", ")", ":", "new_main", "=", "list", "(", "self", ".", "main", ")", "if", "isinstance", "(", "main_phases", ",", "collections", ".", "Iterable", ")", ":", "new_main", ".", "extend"...
Returns PhaseGroup with additional main phases.
[ "Returns", "PhaseGroup", "with", "additional", "main", "phases", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L130-L141
240,878
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.flatten
def flatten(self): """Internally flatten out nested iterables.""" return PhaseGroup( setup=flatten_phases_and_groups(self.setup), main=flatten_phases_and_groups(self.main), teardown=flatten_phases_and_groups(self.teardown), name=self.name)
python
def flatten(self): return PhaseGroup( setup=flatten_phases_and_groups(self.setup), main=flatten_phases_and_groups(self.main), teardown=flatten_phases_and_groups(self.teardown), name=self.name)
[ "def", "flatten", "(", "self", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "flatten_phases_and_groups", "(", "self", ".", "setup", ")", ",", "main", "=", "flatten_phases_and_groups", "(", "self", ".", "main", ")", ",", "teardown", "=", "flatten_phas...
Internally flatten out nested iterables.
[ "Internally", "flatten", "out", "nested", "iterables", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L175-L181
240,879
google/openhtf
openhtf/core/phase_group.py
PhaseGroup.load_code_info
def load_code_info(self): """Load coded info for all contained phases.""" return PhaseGroup( setup=load_code_info(self.setup), main=load_code_info(self.main), teardown=load_code_info(self.teardown), name=self.name)
python
def load_code_info(self): return PhaseGroup( setup=load_code_info(self.setup), main=load_code_info(self.main), teardown=load_code_info(self.teardown), name=self.name)
[ "def", "load_code_info", "(", "self", ")", ":", "return", "PhaseGroup", "(", "setup", "=", "load_code_info", "(", "self", ".", "setup", ")", ",", "main", "=", "load_code_info", "(", "self", ".", "main", ")", ",", "teardown", "=", "load_code_info", "(", "...
Load coded info for all contained phases.
[ "Load", "coded", "info", "for", "all", "contained", "phases", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_group.py#L183-L189
240,880
google/openhtf
openhtf/output/servers/pub_sub.py
PubSub.publish
def publish(cls, message, client_filter=None): """Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message sent to them. """ with cls._lock: for client in cls.subscribers: if (not client_filter) or client_filter(client): client.send(message)
python
def publish(cls, message, client_filter=None): with cls._lock: for client in cls.subscribers: if (not client_filter) or client_filter(client): client.send(message)
[ "def", "publish", "(", "cls", ",", "message", ",", "client_filter", "=", "None", ")", ":", "with", "cls", ".", "_lock", ":", "for", "client", "in", "cls", ".", "subscribers", ":", "if", "(", "not", "client_filter", ")", "or", "client_filter", "(", "cli...
Publish messages to subscribers. Args: message: The message to publish. client_filter: A filter function to call passing in each client. Only clients for whom the function returns True will have the message sent to them.
[ "Publish", "messages", "to", "subscribers", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/pub_sub.py#L43-L55
240,881
google/openhtf
examples/repeat.py
FailTwicePlug.run
def run(self): """Increments counter and raises an exception for first two runs.""" self.count += 1 print('FailTwicePlug: Run number %s' % (self.count)) if self.count < 3: raise RuntimeError('Fails a couple times') return True
python
def run(self): self.count += 1 print('FailTwicePlug: Run number %s' % (self.count)) if self.count < 3: raise RuntimeError('Fails a couple times') return True
[ "def", "run", "(", "self", ")", ":", "self", ".", "count", "+=", "1", "print", "(", "'FailTwicePlug: Run number %s'", "%", "(", "self", ".", "count", ")", ")", "if", "self", ".", "count", "<", "3", ":", "raise", "RuntimeError", "(", "'Fails a couple time...
Increments counter and raises an exception for first two runs.
[ "Increments", "counter", "and", "raises", "an", "exception", "for", "first", "two", "runs", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/repeat.py#L41-L48
240,882
google/openhtf
openhtf/core/phase_descriptor.py
PhaseOptions.format_strings
def format_strings(self, **kwargs): """String substitution of name.""" return mutablerecords.CopyRecord( self, name=util.format_string(self.name, kwargs))
python
def format_strings(self, **kwargs): return mutablerecords.CopyRecord( self, name=util.format_string(self.name, kwargs))
[ "def", "format_strings", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "mutablerecords", ".", "CopyRecord", "(", "self", ",", "name", "=", "util", ".", "format_string", "(", "self", ".", "name", ",", "kwargs", ")", ")" ]
String substitution of name.
[ "String", "substitution", "of", "name", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L96-L99
240,883
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor.wrap_or_copy
def wrap_or_copy(cls, func, **options): """Return a new PhaseDescriptor from the given function or instance. We want to return a new copy so that you can reuse a phase with different options, plugs, measurements, etc. Args: func: A phase function or PhaseDescriptor instance. **options: Options to update on the result. Raises: PhaseWrapError: if func is a openhtf.PhaseGroup. Returns: A new PhaseDescriptor object. """ if isinstance(func, openhtf.PhaseGroup): raise PhaseWrapError('Cannot wrap PhaseGroup <%s> as a phase.' % ( func.name or 'Unnamed')) if isinstance(func, cls): # We want to copy so that a phase can be reused with different options # or kwargs. See with_args() below for more details. retval = mutablerecords.CopyRecord(func) else: retval = cls(func) retval.options.update(**options) return retval
python
def wrap_or_copy(cls, func, **options): if isinstance(func, openhtf.PhaseGroup): raise PhaseWrapError('Cannot wrap PhaseGroup <%s> as a phase.' % ( func.name or 'Unnamed')) if isinstance(func, cls): # We want to copy so that a phase can be reused with different options # or kwargs. See with_args() below for more details. retval = mutablerecords.CopyRecord(func) else: retval = cls(func) retval.options.update(**options) return retval
[ "def", "wrap_or_copy", "(", "cls", ",", "func", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "func", ",", "openhtf", ".", "PhaseGroup", ")", ":", "raise", "PhaseWrapError", "(", "'Cannot wrap PhaseGroup <%s> as a phase.'", "%", "(", "func", "...
Return a new PhaseDescriptor from the given function or instance. We want to return a new copy so that you can reuse a phase with different options, plugs, measurements, etc. Args: func: A phase function or PhaseDescriptor instance. **options: Options to update on the result. Raises: PhaseWrapError: if func is a openhtf.PhaseGroup. Returns: A new PhaseDescriptor object.
[ "Return", "a", "new", "PhaseDescriptor", "from", "the", "given", "function", "or", "instance", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L135-L161
240,884
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor.with_known_args
def with_known_args(self, **kwargs): """Send only known keyword-arguments to the phase when called.""" argspec = inspect.getargspec(self.func) stored = {} for key, arg in six.iteritems(kwargs): if key in argspec.args or argspec.keywords: stored[key] = arg if stored: return self.with_args(**stored) return self
python
def with_known_args(self, **kwargs): argspec = inspect.getargspec(self.func) stored = {} for key, arg in six.iteritems(kwargs): if key in argspec.args or argspec.keywords: stored[key] = arg if stored: return self.with_args(**stored) return self
[ "def", "with_known_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "self", ".", "func", ")", "stored", "=", "{", "}", "for", "key", ",", "arg", "in", "six", ".", "iteritems", "(", "kwargs", ...
Send only known keyword-arguments to the phase when called.
[ "Send", "only", "known", "keyword", "-", "arguments", "to", "the", "phase", "when", "called", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L179-L188
240,885
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor.with_args
def with_args(self, **kwargs): """Send these keyword-arguments to the phase when called.""" # Make a copy so we can have multiple of the same phase with different args # in the same test. new_info = mutablerecords.CopyRecord(self) new_info.options = new_info.options.format_strings(**kwargs) new_info.extra_kwargs.update(kwargs) new_info.measurements = [m.with_args(**kwargs) for m in self.measurements] return new_info
python
def with_args(self, **kwargs): # Make a copy so we can have multiple of the same phase with different args # in the same test. new_info = mutablerecords.CopyRecord(self) new_info.options = new_info.options.format_strings(**kwargs) new_info.extra_kwargs.update(kwargs) new_info.measurements = [m.with_args(**kwargs) for m in self.measurements] return new_info
[ "def", "with_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Make a copy so we can have multiple of the same phase with different args", "# in the same test.", "new_info", "=", "mutablerecords", ".", "CopyRecord", "(", "self", ")", "new_info", ".", "options", ...
Send these keyword-arguments to the phase when called.
[ "Send", "these", "keyword", "-", "arguments", "to", "the", "phase", "when", "called", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L190-L198
240,886
google/openhtf
openhtf/core/phase_descriptor.py
PhaseDescriptor._apply_with_plugs
def _apply_with_plugs(self, subplugs, error_on_unknown): """Substitute plugs for placeholders for this phase. Args: subplugs: dict of plug name to plug class, plug classes to replace. error_on_unknown: bool, if True, then error when an unknown plug name is provided. Raises: openhtf.plugs.InvalidPlugError if for one of the plug names one of the following is true: - error_on_unknown is True and the plug name is not registered. - The new plug subclass is not a subclass of the original. - The original plug class is not a placeholder or automatic placeholder. Returns: PhaseDescriptor with updated plugs. """ plugs_by_name = {plug.name: plug for plug in self.plugs} new_plugs = dict(plugs_by_name) for name, sub_class in six.iteritems(subplugs): original_plug = plugs_by_name.get(name) accept_substitute = True if original_plug is None: if not error_on_unknown: continue accept_substitute = False elif isinstance(original_plug.cls, openhtf.plugs.PlugPlaceholder): accept_substitute = issubclass(sub_class, original_plug.cls.base_class) else: # Check __dict__ to see if the attribute is explicitly defined in the # class, rather than being defined in a parent class. accept_substitute = ('auto_placeholder' in original_plug.cls.__dict__ and original_plug.cls.auto_placeholder and issubclass(sub_class, original_plug.cls)) if not accept_substitute: raise openhtf.plugs.InvalidPlugError( 'Could not find valid placeholder for substitute plug %s ' 'required for phase %s' % (name, self.name)) new_plugs[name] = mutablerecords.CopyRecord(original_plug, cls=sub_class) return mutablerecords.CopyRecord( self, plugs=list(new_plugs.values()), options=self.options.format_strings(**subplugs), measurements=[m.with_args(**subplugs) for m in self.measurements])
python
def _apply_with_plugs(self, subplugs, error_on_unknown): plugs_by_name = {plug.name: plug for plug in self.plugs} new_plugs = dict(plugs_by_name) for name, sub_class in six.iteritems(subplugs): original_plug = plugs_by_name.get(name) accept_substitute = True if original_plug is None: if not error_on_unknown: continue accept_substitute = False elif isinstance(original_plug.cls, openhtf.plugs.PlugPlaceholder): accept_substitute = issubclass(sub_class, original_plug.cls.base_class) else: # Check __dict__ to see if the attribute is explicitly defined in the # class, rather than being defined in a parent class. accept_substitute = ('auto_placeholder' in original_plug.cls.__dict__ and original_plug.cls.auto_placeholder and issubclass(sub_class, original_plug.cls)) if not accept_substitute: raise openhtf.plugs.InvalidPlugError( 'Could not find valid placeholder for substitute plug %s ' 'required for phase %s' % (name, self.name)) new_plugs[name] = mutablerecords.CopyRecord(original_plug, cls=sub_class) return mutablerecords.CopyRecord( self, plugs=list(new_plugs.values()), options=self.options.format_strings(**subplugs), measurements=[m.with_args(**subplugs) for m in self.measurements])
[ "def", "_apply_with_plugs", "(", "self", ",", "subplugs", ",", "error_on_unknown", ")", ":", "plugs_by_name", "=", "{", "plug", ".", "name", ":", "plug", "for", "plug", "in", "self", ".", "plugs", "}", "new_plugs", "=", "dict", "(", "plugs_by_name", ")", ...
Substitute plugs for placeholders for this phase. Args: subplugs: dict of plug name to plug class, plug classes to replace. error_on_unknown: bool, if True, then error when an unknown plug name is provided. Raises: openhtf.plugs.InvalidPlugError if for one of the plug names one of the following is true: - error_on_unknown is True and the plug name is not registered. - The new plug subclass is not a subclass of the original. - The original plug class is not a placeholder or automatic placeholder. Returns: PhaseDescriptor with updated plugs.
[ "Substitute", "plugs", "for", "placeholders", "for", "this", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/phase_descriptor.py#L208-L255
240,887
google/openhtf
openhtf/plugs/usb/usb_handle.py
requires_open_handle
def requires_open_handle(method): # pylint: disable=invalid-name """Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method: A class method on a subclass of UsbHandle Raises: HandleClosedError: If this handle has been closed. Returns: A wrapper around method that ensures the handle is open before calling through to the wrapped method. """ @functools.wraps(method) def wrapper_requiring_open_handle(self, *args, **kwargs): """The wrapper to be returned.""" if self.is_closed(): raise usb_exceptions.HandleClosedError() return method(self, *args, **kwargs) return wrapper_requiring_open_handle
python
def requires_open_handle(method): # pylint: disable=invalid-name @functools.wraps(method) def wrapper_requiring_open_handle(self, *args, **kwargs): """The wrapper to be returned.""" if self.is_closed(): raise usb_exceptions.HandleClosedError() return method(self, *args, **kwargs) return wrapper_requiring_open_handle
[ "def", "requires_open_handle", "(", "method", ")", ":", "# pylint: disable=invalid-name", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper_requiring_open_handle", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"The wra...
Decorator to ensure a handle is open for certain methods. Subclasses should decorate their Read() and Write() with this rather than checking their own internal state, keeping all "is this handle open" logic in is_closed(). Args: method: A class method on a subclass of UsbHandle Raises: HandleClosedError: If this handle has been closed. Returns: A wrapper around method that ensures the handle is open before calling through to the wrapped method.
[ "Decorator", "to", "ensure", "a", "handle", "is", "open", "for", "certain", "methods", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle.py#L36-L59
240,888
google/openhtf
openhtf/plugs/usb/usb_handle_stub.py
StubUsbHandle._dotify
def _dotify(cls, data): """Add dots.""" return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
python
def _dotify(cls, data): return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
[ "def", "_dotify", "(", "cls", ",", "data", ")", ":", "return", "''", ".", "join", "(", "char", "if", "char", "in", "cls", ".", "PRINTABLE_DATA", "else", "'.'", "for", "char", "in", "data", ")" ]
Add dots.
[ "Add", "dots", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L36-L38
240,889
google/openhtf
openhtf/plugs/usb/usb_handle_stub.py
StubUsbHandle.write
def write(self, data, dummy=None): """Stub Write method.""" assert not self.closed if self.expected_write_data is None: return expected_data = self.expected_write_data.pop(0) if expected_data != data: raise ValueError('Expected %s, got %s (%s)' % ( self._dotify(expected_data), binascii.hexlify(data), self._dotify(data)))
python
def write(self, data, dummy=None): assert not self.closed if self.expected_write_data is None: return expected_data = self.expected_write_data.pop(0) if expected_data != data: raise ValueError('Expected %s, got %s (%s)' % ( self._dotify(expected_data), binascii.hexlify(data), self._dotify(data)))
[ "def", "write", "(", "self", ",", "data", ",", "dummy", "=", "None", ")", ":", "assert", "not", "self", ".", "closed", "if", "self", ".", "expected_write_data", "is", "None", ":", "return", "expected_data", "=", "self", ".", "expected_write_data", ".", "...
Stub Write method.
[ "Stub", "Write", "method", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L40-L50
240,890
google/openhtf
openhtf/plugs/usb/usb_handle_stub.py
StubUsbHandle.read
def read(self, length, dummy=None): """Stub Read method.""" assert not self.closed data = self.expected_read_data.pop(0) if length < len(data): raise ValueError( 'Overflow packet length. Read %d bytes, got %d bytes: %s', length, len(data), self._dotify(data)) return data
python
def read(self, length, dummy=None): assert not self.closed data = self.expected_read_data.pop(0) if length < len(data): raise ValueError( 'Overflow packet length. Read %d bytes, got %d bytes: %s', length, len(data), self._dotify(data)) return data
[ "def", "read", "(", "self", ",", "length", ",", "dummy", "=", "None", ")", ":", "assert", "not", "self", ".", "closed", "data", "=", "self", ".", "expected_read_data", ".", "pop", "(", "0", ")", "if", "length", "<", "len", "(", "data", ")", ":", ...
Stub Read method.
[ "Stub", "Read", "method", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/usb_handle_stub.py#L52-L60
240,891
google/openhtf
openhtf/plugs/cambrionix/__init__.py
EtherSync.get_usb_serial
def get_usb_serial(self, port_num): """Get the device serial number Args: port_num: port number on the Cambrionix unit Return: usb device serial number """ port = self.port_map[str(port_num)] arg = ''.join(['DEVICE INFO,', self._addr, '.', port]) cmd = (['esuit64', '-t', arg]) info = subprocess.check_output(cmd, stderr=subprocess.STDOUT) serial = None if "SERIAL" in info: serial_info = info.split('SERIAL:')[1] serial = serial_info.split('\n')[0].strip() use_info = info.split('BY')[1].split(' ')[1] if use_info == 'NO': cmd = (['esuit64', '-t', 'AUTO USE ALL']) subprocess.check_output(cmd, stderr=subprocess.STDOUT) time.sleep(50.0/1000.0) else: raise ValueError('No USB device detected') return serial
python
def get_usb_serial(self, port_num): port = self.port_map[str(port_num)] arg = ''.join(['DEVICE INFO,', self._addr, '.', port]) cmd = (['esuit64', '-t', arg]) info = subprocess.check_output(cmd, stderr=subprocess.STDOUT) serial = None if "SERIAL" in info: serial_info = info.split('SERIAL:')[1] serial = serial_info.split('\n')[0].strip() use_info = info.split('BY')[1].split(' ')[1] if use_info == 'NO': cmd = (['esuit64', '-t', 'AUTO USE ALL']) subprocess.check_output(cmd, stderr=subprocess.STDOUT) time.sleep(50.0/1000.0) else: raise ValueError('No USB device detected') return serial
[ "def", "get_usb_serial", "(", "self", ",", "port_num", ")", ":", "port", "=", "self", ".", "port_map", "[", "str", "(", "port_num", ")", "]", "arg", "=", "''", ".", "join", "(", "[", "'DEVICE INFO,'", ",", "self", ".", "_addr", ",", "'.'", ",", "po...
Get the device serial number Args: port_num: port number on the Cambrionix unit Return: usb device serial number
[ "Get", "the", "device", "serial", "number" ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L47-L72
240,892
google/openhtf
openhtf/plugs/cambrionix/__init__.py
EtherSync.open_usb_handle
def open_usb_handle(self, port_num): """open usb port Args: port_num: port number on the Cambrionix unit Return: usb handle """ serial = self.get_usb_serial(port_num) return local_usb.LibUsbHandle.open(serial_number=serial)
python
def open_usb_handle(self, port_num): serial = self.get_usb_serial(port_num) return local_usb.LibUsbHandle.open(serial_number=serial)
[ "def", "open_usb_handle", "(", "self", ",", "port_num", ")", ":", "serial", "=", "self", ".", "get_usb_serial", "(", "port_num", ")", "return", "local_usb", ".", "LibUsbHandle", ".", "open", "(", "serial_number", "=", "serial", ")" ]
open usb port Args: port_num: port number on the Cambrionix unit Return: usb handle
[ "open", "usb", "port" ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/cambrionix/__init__.py#L74-L84
240,893
google/openhtf
openhtf/util/console_output.py
_printed_len
def _printed_len(some_string): """Compute the visible length of the string when printed.""" return len([x for x in ANSI_ESC_RE.sub('', some_string) if x in string.printable])
python
def _printed_len(some_string): return len([x for x in ANSI_ESC_RE.sub('', some_string) if x in string.printable])
[ "def", "_printed_len", "(", "some_string", ")", ":", "return", "len", "(", "[", "x", "for", "x", "in", "ANSI_ESC_RE", ".", "sub", "(", "''", ",", "some_string", ")", "if", "x", "in", "string", ".", "printable", "]", ")" ]
Compute the visible length of the string when printed.
[ "Compute", "the", "visible", "length", "of", "the", "string", "when", "printed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L65-L68
240,894
google/openhtf
openhtf/util/console_output.py
banner_print
def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG): """Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. width: Total width for the resulting banner. file: A file object to which the banner text will be written. Intended for use with CLI output file objects like sys.stdout. logger: A logger to use, or None to disable logging. Example: >>> banner_print('Foo Bar Baz') ======================== Foo Bar Baz ======================= """ if logger: logger.debug(ANSI_ESC_RE.sub('', msg)) if CLI_QUIET: return lpad = int(math.ceil((width - _printed_len(msg) - 2) / 2.0)) * '=' rpad = int(math.floor((width - _printed_len(msg) - 2) / 2.0)) * '=' file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format( sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad, reset=colorama.Style.RESET_ALL)) file.flush()
python
def banner_print(msg, color='', width=60, file=sys.stdout, logger=_LOG): if logger: logger.debug(ANSI_ESC_RE.sub('', msg)) if CLI_QUIET: return lpad = int(math.ceil((width - _printed_len(msg) - 2) / 2.0)) * '=' rpad = int(math.floor((width - _printed_len(msg) - 2) / 2.0)) * '=' file.write('{sep}{color}{lpad} {msg} {rpad}{reset}{sep}{sep}'.format( sep=_linesep_for_file(file), color=color, lpad=lpad, msg=msg, rpad=rpad, reset=colorama.Style.RESET_ALL)) file.flush()
[ "def", "banner_print", "(", "msg", ",", "color", "=", "''", ",", "width", "=", "60", ",", "file", "=", "sys", ".", "stdout", ",", "logger", "=", "_LOG", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "ANSI_ESC_RE", ".", "sub", "(", "...
Print the message as a banner with a fixed width. Also logs the message (un-bannered) to the given logger at the debug level. Args: msg: The message to print. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. width: Total width for the resulting banner. file: A file object to which the banner text will be written. Intended for use with CLI output file objects like sys.stdout. logger: A logger to use, or None to disable logging. Example: >>> banner_print('Foo Bar Baz') ======================== Foo Bar Baz =======================
[ "Print", "the", "message", "as", "a", "banner", "with", "a", "fixed", "width", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L78-L109
240,895
google/openhtf
openhtf/util/console_output.py
bracket_print
def bracket_print(msg, color='', width=8, file=sys.stdout): """Prints the message in brackets in the specified color and end the line. Args: msg: The message to put inside the brackets (a brief status message). color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. width: Total desired width of the bracketed message. file: A file object to which the bracketed text will be written. Intended for use with CLI output file objects like sys.stdout. """ if CLI_QUIET: return lpad = int(math.ceil((width - 2 - _printed_len(msg)) / 2.0)) * ' ' rpad = int(math.floor((width - 2 - _printed_len(msg)) / 2.0)) * ' ' file.write('[{lpad}{bright}{color}{msg}{reset}{rpad}]'.format( lpad=lpad, bright=colorama.Style.BRIGHT, color=color, msg=msg, reset=colorama.Style.RESET_ALL, rpad=rpad)) file.write(colorama.Style.RESET_ALL) file.write(_linesep_for_file(file)) file.flush()
python
def bracket_print(msg, color='', width=8, file=sys.stdout): if CLI_QUIET: return lpad = int(math.ceil((width - 2 - _printed_len(msg)) / 2.0)) * ' ' rpad = int(math.floor((width - 2 - _printed_len(msg)) / 2.0)) * ' ' file.write('[{lpad}{bright}{color}{msg}{reset}{rpad}]'.format( lpad=lpad, bright=colorama.Style.BRIGHT, color=color, msg=msg, reset=colorama.Style.RESET_ALL, rpad=rpad)) file.write(colorama.Style.RESET_ALL) file.write(_linesep_for_file(file)) file.flush()
[ "def", "bracket_print", "(", "msg", ",", "color", "=", "''", ",", "width", "=", "8", ",", "file", "=", "sys", ".", "stdout", ")", ":", "if", "CLI_QUIET", ":", "return", "lpad", "=", "int", "(", "math", ".", "ceil", "(", "(", "width", "-", "2", ...
Prints the message in brackets in the specified color and end the line. Args: msg: The message to put inside the brackets (a brief status message). color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. width: Total desired width of the bracketed message. file: A file object to which the bracketed text will be written. Intended for use with CLI output file objects like sys.stdout.
[ "Prints", "the", "message", "in", "brackets", "in", "the", "specified", "color", "and", "end", "the", "line", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L112-L133
240,896
google/openhtf
openhtf/util/console_output.py
cli_print
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG): """Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the test record for later inspection. Args: msg: The message to print/log. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. end: A custom line-ending string to print instead of newline. file: A file object to which the baracketed text will be written. Intended for use with CLI output file objects like sys.stdout. logger: A logger to use, or None to disable logging. """ if logger: logger.debug('-> {}'.format(msg)) if CLI_QUIET: return if end is None: end = _linesep_for_file(file) file.write('{color}{msg}{reset}{end}'.format( color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end))
python
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG): if logger: logger.debug('-> {}'.format(msg)) if CLI_QUIET: return if end is None: end = _linesep_for_file(file) file.write('{color}{msg}{reset}{end}'.format( color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end))
[ "def", "cli_print", "(", "msg", ",", "color", "=", "''", ",", "end", "=", "None", ",", "file", "=", "sys", ".", "stdout", ",", "logger", "=", "_LOG", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "'-> {}'", ".", "format", "(", "msg"...
Print the message to file and also log it. This function is intended as a 'tee' mechanism to enable the CLI interface as a first-class citizen, while ensuring that everything the operator sees also has an analogous logging entry in the test record for later inspection. Args: msg: The message to print/log. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together in order to get any set of effects you want. end: A custom line-ending string to print instead of newline. file: A file object to which the baracketed text will be written. Intended for use with CLI output file objects like sys.stdout. logger: A logger to use, or None to disable logging.
[ "Print", "the", "message", "to", "file", "and", "also", "log", "it", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L136-L160
240,897
google/openhtf
openhtf/util/console_output.py
error_print
def error_print(msg, color=colorama.Fore.RED, file=sys.stderr): """Print the error message to the file in the specified color. Args: msg: The error message to be printed. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together here, but note that style strings will not be applied. file: A file object to which the baracketed text will be written. Intended for use with CLI output file objects, specifically sys.stderr. """ if CLI_QUIET: return file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format( sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color, normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_ALL)) file.flush()
python
def error_print(msg, color=colorama.Fore.RED, file=sys.stderr): if CLI_QUIET: return file.write('{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'.format( sep=_linesep_for_file(file), bright=colorama.Style.BRIGHT, color=color, normal=colorama.Style.NORMAL, msg=msg, reset=colorama.Style.RESET_ALL)) file.flush()
[ "def", "error_print", "(", "msg", ",", "color", "=", "colorama", ".", "Fore", ".", "RED", ",", "file", "=", "sys", ".", "stderr", ")", ":", "if", "CLI_QUIET", ":", "return", "file", ".", "write", "(", "'{sep}{bright}{color}Error: {normal}{msg}{sep}{reset}'", ...
Print the error message to the file in the specified color. Args: msg: The error message to be printed. color: Optional colorama color string to be applied to the message. You can concatenate colorama color strings together here, but note that style strings will not be applied. file: A file object to which the baracketed text will be written. Intended for use with CLI output file objects, specifically sys.stderr.
[ "Print", "the", "error", "message", "to", "the", "file", "in", "the", "specified", "color", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L163-L179
240,898
google/openhtf
openhtf/util/console_output.py
action_result_context
def action_result_context(action_text, width=60, status_width=8, succeed_text='OK', fail_text='FAIL', unknown_text='????', file=sys.stdout, logger=_LOG): """A contextmanager that prints actions and results to the CLI. When entering the context, the action will be printed, and when the context is exited, the result will be printed. The object yielded by the context is used to mark the action as a success or failure, and a raise from inside the context will also result in the action being marked fail. If the result is left unset, then indicative text ("????") will be printed as the result. Args: action_text: Text to be displayed that describes the action being taken. width: Total width for each line of output. status_width: Width of the just the status message portion of each line. succeed_text: Status message displayed when the action succeeds. fail_text: Status message displayed when the action fails. unknown_text: Status message displayed when the result is left unset. file: Specific file object to write to write CLI output to. logger: A logger to use, or None to disable logging. Example usage: with action_result_context('Doing an action that will succeed...') as act: time.sleep(2) act.succeed() with action_result_context('Doing an action with unset result...') as act: time.sleep(2) with action_result_context('Doing an action that will fail...') as act: time.sleep(2) act.fail() with action_result_context('Doing an action that will raise...') as act: time.sleep(2) import textwrap raise RuntimeError(textwrap.dedent('''\ Uh oh, looks like there was a raise in the mix. If you see this message, it means you are running the console_output module directly rather than using it as a library. Things to try: * Not running it as a module. * Running it as a module and enjoying the preview text. * Getting another coffee.''')) Example output: Doing an action that will succeed... [ OK ] Doing an action with unset result... [ ???? ] Doing an action that will fail... [ FAIL ] Doing an action that will raise... [ FAIL ] ... """ if logger: logger.debug('Action - %s', action_text) if not CLI_QUIET: file.write(''.join((action_text, '\r'))) file.flush() spacing = (width - status_width - _printed_len(action_text)) * ' ' result = ActionResult() try: yield result except Exception as err: if logger: logger.debug('Result - %s [ %s ]', action_text, fail_text) if not CLI_QUIET: file.write(''.join((action_text, spacing))) bracket_print(fail_text, width=status_width, color=colorama.Fore.RED, file=file) if not isinstance(err, ActionFailedError): raise return result_text = succeed_text if result.success else unknown_text result_color = colorama.Fore.GREEN if result.success else colorama.Fore.YELLOW if logger: logger.debug('Result - %s [ %s ]', action_text, result_text) if not CLI_QUIET: file.write(''.join((action_text, spacing))) bracket_print(result_text, width=status_width, color=result_color, file=file)
python
def action_result_context(action_text, width=60, status_width=8, succeed_text='OK', fail_text='FAIL', unknown_text='????', file=sys.stdout, logger=_LOG): if logger: logger.debug('Action - %s', action_text) if not CLI_QUIET: file.write(''.join((action_text, '\r'))) file.flush() spacing = (width - status_width - _printed_len(action_text)) * ' ' result = ActionResult() try: yield result except Exception as err: if logger: logger.debug('Result - %s [ %s ]', action_text, fail_text) if not CLI_QUIET: file.write(''.join((action_text, spacing))) bracket_print(fail_text, width=status_width, color=colorama.Fore.RED, file=file) if not isinstance(err, ActionFailedError): raise return result_text = succeed_text if result.success else unknown_text result_color = colorama.Fore.GREEN if result.success else colorama.Fore.YELLOW if logger: logger.debug('Result - %s [ %s ]', action_text, result_text) if not CLI_QUIET: file.write(''.join((action_text, spacing))) bracket_print(result_text, width=status_width, color=result_color, file=file)
[ "def", "action_result_context", "(", "action_text", ",", "width", "=", "60", ",", "status_width", "=", "8", ",", "succeed_text", "=", "'OK'", ",", "fail_text", "=", "'FAIL'", ",", "unknown_text", "=", "'????'", ",", "file", "=", "sys", ".", "stdout", ",", ...
A contextmanager that prints actions and results to the CLI. When entering the context, the action will be printed, and when the context is exited, the result will be printed. The object yielded by the context is used to mark the action as a success or failure, and a raise from inside the context will also result in the action being marked fail. If the result is left unset, then indicative text ("????") will be printed as the result. Args: action_text: Text to be displayed that describes the action being taken. width: Total width for each line of output. status_width: Width of the just the status message portion of each line. succeed_text: Status message displayed when the action succeeds. fail_text: Status message displayed when the action fails. unknown_text: Status message displayed when the result is left unset. file: Specific file object to write to write CLI output to. logger: A logger to use, or None to disable logging. Example usage: with action_result_context('Doing an action that will succeed...') as act: time.sleep(2) act.succeed() with action_result_context('Doing an action with unset result...') as act: time.sleep(2) with action_result_context('Doing an action that will fail...') as act: time.sleep(2) act.fail() with action_result_context('Doing an action that will raise...') as act: time.sleep(2) import textwrap raise RuntimeError(textwrap.dedent('''\ Uh oh, looks like there was a raise in the mix. If you see this message, it means you are running the console_output module directly rather than using it as a library. Things to try: * Not running it as a module. * Running it as a module and enjoying the preview text. * Getting another coffee.''')) Example output: Doing an action that will succeed... [ OK ] Doing an action with unset result... [ ???? ] Doing an action that will fail... [ FAIL ] Doing an action that will raise... [ FAIL ] ...
[ "A", "contextmanager", "that", "prints", "actions", "and", "results", "to", "the", "CLI", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/console_output.py#L204-L290
240,899
google/openhtf
openhtf/util/exceptions.py
reraise
def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name """reraises an exception for exception translation. This is primarily used for when you immediately reraise an exception that is thrown in a library, so that your client will not have to depend on various exceptions defined in the library implementation that is being abstracted. The advantage of this helper function is somewhat preserve traceback information although it is polluted by the reraise frame. Example Code: def A(): raise Exception('Whoops') def main(): try: A() except Exception as e: exceptions.reraise(ValueError) main() Traceback (most recent call last): File "exception.py", line 53, in <module> main() File "exception.py", line 49, in main reraise(ValueError) File "exception.py", line 47, in main A() File "exception.py", line 42, in A raise Exception('Whoops') ValueError: line 49 When this code is run, the additional stack frames for calling A() and raising within A() are printed out in exception, whereas a bare exception translation would lose this information. As long as you ignore the reraise stack frame, the stack trace is okay looking. Generally this can be fixed by hacking on CPython to allow modification of traceback objects ala https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is fixed in Python 3 anyways and that method is the definition of hackery. Args: exc_type: (Exception) Exception class to create. message: (str) Optional message to place in exception instance. Usually not needed as the original exception probably has a message that will be printed out in the modified stacktrace. *args: Args to pass to exception constructor. **kwargs: Kwargs to pass to exception constructor. """ last_lineno = inspect.currentframe().f_back.f_lineno line_msg = 'line %s: ' % last_lineno if message: line_msg += str(message) raise exc_type(line_msg, *args, **kwargs).raise_with_traceback(sys.exc_info()[2])
python
def reraise(exc_type, message=None, *args, **kwargs): # pylint: disable=invalid-name last_lineno = inspect.currentframe().f_back.f_lineno line_msg = 'line %s: ' % last_lineno if message: line_msg += str(message) raise exc_type(line_msg, *args, **kwargs).raise_with_traceback(sys.exc_info()[2])
[ "def", "reraise", "(", "exc_type", ",", "message", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name", "last_lineno", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", ".", "f_lineno", "line_msg", ...
reraises an exception for exception translation. This is primarily used for when you immediately reraise an exception that is thrown in a library, so that your client will not have to depend on various exceptions defined in the library implementation that is being abstracted. The advantage of this helper function is somewhat preserve traceback information although it is polluted by the reraise frame. Example Code: def A(): raise Exception('Whoops') def main(): try: A() except Exception as e: exceptions.reraise(ValueError) main() Traceback (most recent call last): File "exception.py", line 53, in <module> main() File "exception.py", line 49, in main reraise(ValueError) File "exception.py", line 47, in main A() File "exception.py", line 42, in A raise Exception('Whoops') ValueError: line 49 When this code is run, the additional stack frames for calling A() and raising within A() are printed out in exception, whereas a bare exception translation would lose this information. As long as you ignore the reraise stack frame, the stack trace is okay looking. Generally this can be fixed by hacking on CPython to allow modification of traceback objects ala https://github.com/mitsuhiko/jinja2/blob/master/jinja2/debug.py, but this is fixed in Python 3 anyways and that method is the definition of hackery. Args: exc_type: (Exception) Exception class to create. message: (str) Optional message to place in exception instance. Usually not needed as the original exception probably has a message that will be printed out in the modified stacktrace. *args: Args to pass to exception constructor. **kwargs: Kwargs to pass to exception constructor.
[ "reraises", "an", "exception", "for", "exception", "translation", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/exceptions.py#L22-L74