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,700
google/openhtf
openhtf/core/measurements.py
Measurement.with_dimensions
def with_dimensions(self, *dimensions): """Declare dimensions for this Measurement, returns self for chaining.""" self.dimensions = tuple( self._maybe_make_dimension(dim) for dim in dimensions) self._cached = None return self
python
def with_dimensions(self, *dimensions): self.dimensions = tuple( self._maybe_make_dimension(dim) for dim in dimensions) self._cached = None return self
[ "def", "with_dimensions", "(", "self", ",", "*", "dimensions", ")", ":", "self", ".", "dimensions", "=", "tuple", "(", "self", ".", "_maybe_make_dimension", "(", "dim", ")", "for", "dim", "in", "dimensions", ")", "self", ".", "_cached", "=", "None", "ret...
Declare dimensions for this Measurement, returns self for chaining.
[ "Declare", "dimensions", "for", "this", "Measurement", "returns", "self", "for", "chaining", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L218-L223
240,701
google/openhtf
openhtf/core/measurements.py
Measurement.with_validator
def with_validator(self, validator): """Add a validator callback to this Measurement, chainable.""" if not callable(validator): raise ValueError('Validator must be callable', validator) self.validators.append(validator) self._cached = None return self
python
def with_validator(self, validator): if not callable(validator): raise ValueError('Validator must be callable', validator) self.validators.append(validator) self._cached = None return self
[ "def", "with_validator", "(", "self", ",", "validator", ")", ":", "if", "not", "callable", "(", "validator", ")", ":", "raise", "ValueError", "(", "'Validator must be callable'", ",", "validator", ")", "self", ".", "validators", ".", "append", "(", "validator"...
Add a validator callback to this Measurement, chainable.
[ "Add", "a", "validator", "callback", "to", "this", "Measurement", "chainable", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L225-L231
240,702
google/openhtf
openhtf/core/measurements.py
Measurement.with_args
def with_args(self, **kwargs): """String substitution for names and docstrings.""" validators = [ validator.with_args(**kwargs) if hasattr(validator, 'with_args') else validator for validator in self.validators ] return mutablerecords.CopyRecord( self, name=util.format_string(self.name, kwargs), docstring=util.format_string(self.docstring, kwargs), validators=validators, _cached=None, )
python
def with_args(self, **kwargs): validators = [ validator.with_args(**kwargs) if hasattr(validator, 'with_args') else validator for validator in self.validators ] return mutablerecords.CopyRecord( self, name=util.format_string(self.name, kwargs), docstring=util.format_string(self.docstring, kwargs), validators=validators, _cached=None, )
[ "def", "with_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "validators", "=", "[", "validator", ".", "with_args", "(", "*", "*", "kwargs", ")", "if", "hasattr", "(", "validator", ",", "'with_args'", ")", "else", "validator", "for", "validator", ...
String substitution for names and docstrings.
[ "String", "substitution", "for", "names", "and", "docstrings", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L233-L245
240,703
google/openhtf
openhtf/core/measurements.py
Measurement.validate
def validate(self): """Validate this measurement and update its 'outcome' field.""" # PASS if all our validators return True, otherwise FAIL. try: if all(v(self.measured_value.value) for v in self.validators): self.outcome = Outcome.PASS else: self.outcome = Outcome.FAIL return self except Exception as e: # pylint: disable=bare-except _LOG.error('Validation for measurement %s raised an exception %s.', self.name, e) self.outcome = Outcome.FAIL raise finally: if self._cached: self._cached['outcome'] = self.outcome.name
python
def validate(self): # PASS if all our validators return True, otherwise FAIL. try: if all(v(self.measured_value.value) for v in self.validators): self.outcome = Outcome.PASS else: self.outcome = Outcome.FAIL return self except Exception as e: # pylint: disable=bare-except _LOG.error('Validation for measurement %s raised an exception %s.', self.name, e) self.outcome = Outcome.FAIL raise finally: if self._cached: self._cached['outcome'] = self.outcome.name
[ "def", "validate", "(", "self", ")", ":", "# PASS if all our validators return True, otherwise FAIL.", "try", ":", "if", "all", "(", "v", "(", "self", ".", "measured_value", ".", "value", ")", "for", "v", "in", "self", ".", "validators", ")", ":", "self", "....
Validate this measurement and update its 'outcome' field.
[ "Validate", "this", "measurement", "and", "update", "its", "outcome", "field", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L260-L276
240,704
google/openhtf
openhtf/core/measurements.py
Measurement.as_base_types
def as_base_types(self): """Convert this measurement to a dict of basic types.""" if not self._cached: # Create the single cache file the first time this is called. self._cached = { 'name': self.name, 'outcome': self.outcome.name, } if self.validators: self._cached['validators'] = data.convert_to_base_types( tuple(str(v) for v in self.validators)) if self.dimensions: self._cached['dimensions'] = data.convert_to_base_types(self.dimensions) if self.units: self._cached['units'] = data.convert_to_base_types(self.units) if self.docstring: self._cached['docstring'] = self.docstring if self.measured_value.is_value_set: self._cached['measured_value'] = self.measured_value.basetype_value() return self._cached
python
def as_base_types(self): if not self._cached: # Create the single cache file the first time this is called. self._cached = { 'name': self.name, 'outcome': self.outcome.name, } if self.validators: self._cached['validators'] = data.convert_to_base_types( tuple(str(v) for v in self.validators)) if self.dimensions: self._cached['dimensions'] = data.convert_to_base_types(self.dimensions) if self.units: self._cached['units'] = data.convert_to_base_types(self.units) if self.docstring: self._cached['docstring'] = self.docstring if self.measured_value.is_value_set: self._cached['measured_value'] = self.measured_value.basetype_value() return self._cached
[ "def", "as_base_types", "(", "self", ")", ":", "if", "not", "self", ".", "_cached", ":", "# Create the single cache file the first time this is called.", "self", ".", "_cached", "=", "{", "'name'", ":", "self", ".", "name", ",", "'outcome'", ":", "self", ".", ...
Convert this measurement to a dict of basic types.
[ "Convert", "this", "measurement", "to", "a", "dict", "of", "basic", "types", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L278-L297
240,705
google/openhtf
openhtf/core/measurements.py
Measurement.to_dataframe
def to_dataframe(self, columns=None): """Convert a multi-dim to a pandas dataframe.""" if not isinstance(self.measured_value, DimensionedMeasuredValue): raise TypeError( 'Only a dimensioned measurement can be converted to a DataFrame') if columns is None: columns = [d.name for d in self.dimensions] columns += [self.units.name if self.units else 'value'] dataframe = self.measured_value.to_dataframe(columns) return dataframe
python
def to_dataframe(self, columns=None): if not isinstance(self.measured_value, DimensionedMeasuredValue): raise TypeError( 'Only a dimensioned measurement can be converted to a DataFrame') if columns is None: columns = [d.name for d in self.dimensions] columns += [self.units.name if self.units else 'value'] dataframe = self.measured_value.to_dataframe(columns) return dataframe
[ "def", "to_dataframe", "(", "self", ",", "columns", "=", "None", ")", ":", "if", "not", "isinstance", "(", "self", ".", "measured_value", ",", "DimensionedMeasuredValue", ")", ":", "raise", "TypeError", "(", "'Only a dimensioned measurement can be converted to a DataF...
Convert a multi-dim to a pandas dataframe.
[ "Convert", "a", "multi", "-", "dim", "to", "a", "pandas", "dataframe", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L299-L311
240,706
google/openhtf
openhtf/core/measurements.py
MeasuredValue.set
def set(self, value): """Set the value for this measurement, with some sanity checks.""" if self.is_value_set: # While we want to *allow* re-setting previously set measurements, we'd # rather promote the use of multidimensional measurements instead of # discarding data, so we make this somewhat chatty. _LOG.warning( 'Overriding previous measurement %s value of %s with %s, the old ' 'value will be lost. Use a dimensioned measurement if you need to ' 'save multiple values.', self.name, self.stored_value, value) if value is None: _LOG.warning('Measurement %s is set to None', self.name) self.stored_value = value self._cached_value = data.convert_to_base_types(value) self.is_value_set = True
python
def set(self, value): if self.is_value_set: # While we want to *allow* re-setting previously set measurements, we'd # rather promote the use of multidimensional measurements instead of # discarding data, so we make this somewhat chatty. _LOG.warning( 'Overriding previous measurement %s value of %s with %s, the old ' 'value will be lost. Use a dimensioned measurement if you need to ' 'save multiple values.', self.name, self.stored_value, value) if value is None: _LOG.warning('Measurement %s is set to None', self.name) self.stored_value = value self._cached_value = data.convert_to_base_types(value) self.is_value_set = True
[ "def", "set", "(", "self", ",", "value", ")", ":", "if", "self", ".", "is_value_set", ":", "# While we want to *allow* re-setting previously set measurements, we'd", "# rather promote the use of multidimensional measurements instead of", "# discarding data, so we make this somewhat cha...
Set the value for this measurement, with some sanity checks.
[ "Set", "the", "value", "for", "this", "measurement", "with", "some", "sanity", "checks", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L354-L368
240,707
google/openhtf
openhtf/core/measurements.py
Dimension.from_string
def from_string(cls, string): """Convert a string into a Dimension""" # Note: There is some ambiguity as to whether the string passed is intended # to become a unit looked up by name or suffix, or a Dimension descriptor. if string in units.UNITS_BY_ALL: return cls(description=string, unit=units.Unit(string)) else: return cls(description=string)
python
def from_string(cls, string): # Note: There is some ambiguity as to whether the string passed is intended # to become a unit looked up by name or suffix, or a Dimension descriptor. if string in units.UNITS_BY_ALL: return cls(description=string, unit=units.Unit(string)) else: return cls(description=string)
[ "def", "from_string", "(", "cls", ",", "string", ")", ":", "# Note: There is some ambiguity as to whether the string passed is intended", "# to become a unit looked up by name or suffix, or a Dimension descriptor.", "if", "string", "in", "units", ".", "UNITS_BY_ALL", ":", "return",...
Convert a string into a Dimension
[ "Convert", "a", "string", "into", "a", "Dimension" ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L404-L411
240,708
google/openhtf
openhtf/core/measurements.py
DimensionedMeasuredValue.value
def value(self): """The values stored in this record. Returns: A list of tuples; the last element of each tuple will be the measured value, the other elements will be the associated coordinates. The tuples are output in the order in which they were set. """ if not self.is_value_set: raise MeasurementNotSetError('Measurement not yet set', self.name) return [dimensions + (value,) for dimensions, value in six.iteritems(self.value_dict)]
python
def value(self): if not self.is_value_set: raise MeasurementNotSetError('Measurement not yet set', self.name) return [dimensions + (value,) for dimensions, value in six.iteritems(self.value_dict)]
[ "def", "value", "(", "self", ")", ":", "if", "not", "self", ".", "is_value_set", ":", "raise", "MeasurementNotSetError", "(", "'Measurement not yet set'", ",", "self", ".", "name", ")", "return", "[", "dimensions", "+", "(", "value", ",", ")", "for", "dime...
The values stored in this record. Returns: A list of tuples; the last element of each tuple will be the measured value, the other elements will be the associated coordinates. The tuples are output in the order in which they were set.
[ "The", "values", "stored", "in", "this", "record", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L505-L516
240,709
google/openhtf
openhtf/core/measurements.py
DimensionedMeasuredValue.to_dataframe
def to_dataframe(self, columns=None): """Converts to a `pandas.DataFrame`""" if not self.is_value_set: raise ValueError('Value must be set before converting to a DataFrame.') if not pandas: raise RuntimeError('Install pandas to convert to pandas.DataFrame') return pandas.DataFrame.from_records(self.value, columns=columns)
python
def to_dataframe(self, columns=None): if not self.is_value_set: raise ValueError('Value must be set before converting to a DataFrame.') if not pandas: raise RuntimeError('Install pandas to convert to pandas.DataFrame') return pandas.DataFrame.from_records(self.value, columns=columns)
[ "def", "to_dataframe", "(", "self", ",", "columns", "=", "None", ")", ":", "if", "not", "self", ".", "is_value_set", ":", "raise", "ValueError", "(", "'Value must be set before converting to a DataFrame.'", ")", "if", "not", "pandas", ":", "raise", "RuntimeError",...
Converts to a `pandas.DataFrame`
[ "Converts", "to", "a", "pandas", ".", "DataFrame" ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L525-L531
240,710
google/openhtf
openhtf/core/measurements.py
Collection._assert_valid_key
def _assert_valid_key(self, name): """Raises if name is not a valid measurement.""" if name not in self._measurements: raise NotAMeasurementError('Not a measurement', name, self._measurements)
python
def _assert_valid_key(self, name): if name not in self._measurements: raise NotAMeasurementError('Not a measurement', name, self._measurements)
[ "def", "_assert_valid_key", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_measurements", ":", "raise", "NotAMeasurementError", "(", "'Not a measurement'", ",", "name", ",", "self", ".", "_measurements", ")" ]
Raises if name is not a valid measurement.
[ "Raises", "if", "name", "is", "not", "a", "valid", "measurement", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L579-L582
240,711
google/openhtf
openhtf/plugs/usb/adb_device.py
AdbDevice.install
def install(self, apk_path, destination_dir=None, timeout_ms=None): """Install apk to device. Doesn't support verifier file, instead allows destination directory to be overridden. Arguments: apk_path: Local path to apk to install. destination_dir: Optional destination directory. Use /system/app/ for persistent applications. timeout_ms: Expected timeout for pushing and installing. Returns: The pm install output. """ if not destination_dir: destination_dir = '/data/local/tmp/' basename = os.path.basename(apk_path) destination_path = destination_dir + basename self.push(apk_path, destination_path, timeout_ms=timeout_ms) return self.Shell('pm install -r "%s"' % destination_path, timeout_ms=timeout_ms)
python
def install(self, apk_path, destination_dir=None, timeout_ms=None): if not destination_dir: destination_dir = '/data/local/tmp/' basename = os.path.basename(apk_path) destination_path = destination_dir + basename self.push(apk_path, destination_path, timeout_ms=timeout_ms) return self.Shell('pm install -r "%s"' % destination_path, timeout_ms=timeout_ms)
[ "def", "install", "(", "self", ",", "apk_path", ",", "destination_dir", "=", "None", ",", "timeout_ms", "=", "None", ")", ":", "if", "not", "destination_dir", ":", "destination_dir", "=", "'/data/local/tmp/'", "basename", "=", "os", ".", "path", ".", "basena...
Install apk to device. Doesn't support verifier file, instead allows destination directory to be overridden. Arguments: apk_path: Local path to apk to install. destination_dir: Optional destination directory. Use /system/app/ for persistent applications. timeout_ms: Expected timeout for pushing and installing. Returns: The pm install output.
[ "Install", "apk", "to", "device", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L111-L132
240,712
google/openhtf
openhtf/plugs/usb/adb_device.py
AdbDevice.push
def push(self, source_file, device_filename, timeout_ms=None): """Push source_file to file on device. Arguments: source_file: Either a filename or file-like object to push to the device. If a filename, will set the remote mtime to match the local mtime, otherwise will use the current time. device_filename: The filename on the device to write to. timeout_ms: Expected timeout for any part of the push. """ mtime = 0 if isinstance(source_file, six.string_types): mtime = os.path.getmtime(source_file) source_file = open(source_file) self.filesync_service.send( source_file, device_filename, mtime=mtime, timeout=timeouts.PolledTimeout.from_millis(timeout_ms))
python
def push(self, source_file, device_filename, timeout_ms=None): mtime = 0 if isinstance(source_file, six.string_types): mtime = os.path.getmtime(source_file) source_file = open(source_file) self.filesync_service.send( source_file, device_filename, mtime=mtime, timeout=timeouts.PolledTimeout.from_millis(timeout_ms))
[ "def", "push", "(", "self", ",", "source_file", ",", "device_filename", ",", "timeout_ms", "=", "None", ")", ":", "mtime", "=", "0", "if", "isinstance", "(", "source_file", ",", "six", ".", "string_types", ")", ":", "mtime", "=", "os", ".", "path", "."...
Push source_file to file on device. Arguments: source_file: Either a filename or file-like object to push to the device. If a filename, will set the remote mtime to match the local mtime, otherwise will use the current time. device_filename: The filename on the device to write to. timeout_ms: Expected timeout for any part of the push.
[ "Push", "source_file", "to", "file", "on", "device", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L134-L151
240,713
google/openhtf
openhtf/plugs/usb/adb_device.py
AdbDevice.pull
def pull(self, device_filename, dest_file=None, timeout_ms=None): """Pull file from device. Arguments: device_filename: The filename on the device to pull. dest_file: If set, a filename or writable file-like object. timeout_ms: Expected timeout for the pull. Returns: The file data if dest_file is not set, None otherwise. """ should_return_data = dest_file is None if isinstance(dest_file, six.string_types): dest_file = open(dest_file, 'w') elif dest_file is None: dest_file = six.StringIO() self.filesync_service.recv(device_filename, dest_file, timeouts.PolledTimeout.from_millis(timeout_ms)) if should_return_data: return dest_file.getvalue()
python
def pull(self, device_filename, dest_file=None, timeout_ms=None): should_return_data = dest_file is None if isinstance(dest_file, six.string_types): dest_file = open(dest_file, 'w') elif dest_file is None: dest_file = six.StringIO() self.filesync_service.recv(device_filename, dest_file, timeouts.PolledTimeout.from_millis(timeout_ms)) if should_return_data: return dest_file.getvalue()
[ "def", "pull", "(", "self", ",", "device_filename", ",", "dest_file", "=", "None", ",", "timeout_ms", "=", "None", ")", ":", "should_return_data", "=", "dest_file", "is", "None", "if", "isinstance", "(", "dest_file", ",", "six", ".", "string_types", ")", "...
Pull file from device. Arguments: device_filename: The filename on the device to pull. dest_file: If set, a filename or writable file-like object. timeout_ms: Expected timeout for the pull. Returns: The file data if dest_file is not set, None otherwise.
[ "Pull", "file", "from", "device", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L153-L172
240,714
google/openhtf
openhtf/plugs/usb/adb_device.py
AdbDevice.list
def list(self, device_path, timeout_ms=None): """Yield filesync_service.DeviceFileStat objects for directory contents.""" return self.filesync_service.list( device_path, timeouts.PolledTimeout.from_millis(timeout_ms))
python
def list(self, device_path, timeout_ms=None): return self.filesync_service.list( device_path, timeouts.PolledTimeout.from_millis(timeout_ms))
[ "def", "list", "(", "self", ",", "device_path", ",", "timeout_ms", "=", "None", ")", ":", "return", "self", ".", "filesync_service", ".", "list", "(", "device_path", ",", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", ")" ]
Yield filesync_service.DeviceFileStat objects for directory contents.
[ "Yield", "filesync_service", ".", "DeviceFileStat", "objects", "for", "directory", "contents", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L174-L177
240,715
google/openhtf
openhtf/plugs/usb/adb_device.py
AdbDevice._check_remote_command
def _check_remote_command(self, destination, timeout_ms, success_msgs=None): """Open a stream to destination, check for remote errors. Used for reboot, remount, and root services. If this method returns, the command was successful, otherwise an appropriate error will have been raised. Args: destination: Stream destination to open. timeout_ms: Timeout in milliseconds for the operation. success_msgs: If provided, a list of messages that, if returned from the device, indicate success, so don't treat them as errors. Raises: AdbRemoteError: If the remote command fails, will contain any message we got back from the device. AdbStreamUnavailableError: The service requested isn't supported. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) stream = self._adb_connection.open_stream(destination, timeout) if not stream: raise usb_exceptions.AdbStreamUnavailableError( 'Service %s not supported', destination) try: message = stream.read(timeout_ms=timeout) # Some commands report success messages, ignore them. if any([m in message for m in success_msgs]): return except usb_exceptions.CommonUsbError: if destination.startswith('reboot:'): # We expect this if the device is rebooting. return raise raise usb_exceptions.AdbRemoteError('Device message: %s', message)
python
def _check_remote_command(self, destination, timeout_ms, success_msgs=None): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) stream = self._adb_connection.open_stream(destination, timeout) if not stream: raise usb_exceptions.AdbStreamUnavailableError( 'Service %s not supported', destination) try: message = stream.read(timeout_ms=timeout) # Some commands report success messages, ignore them. if any([m in message for m in success_msgs]): return except usb_exceptions.CommonUsbError: if destination.startswith('reboot:'): # We expect this if the device is rebooting. return raise raise usb_exceptions.AdbRemoteError('Device message: %s', message)
[ "def", "_check_remote_command", "(", "self", ",", "destination", ",", "timeout_ms", ",", "success_msgs", "=", "None", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", "stream", "=", "self", ".", "_adb_conn...
Open a stream to destination, check for remote errors. Used for reboot, remount, and root services. If this method returns, the command was successful, otherwise an appropriate error will have been raised. Args: destination: Stream destination to open. timeout_ms: Timeout in milliseconds for the operation. success_msgs: If provided, a list of messages that, if returned from the device, indicate success, so don't treat them as errors. Raises: AdbRemoteError: If the remote command fails, will contain any message we got back from the device. AdbStreamUnavailableError: The service requested isn't supported.
[ "Open", "a", "stream", "to", "destination", "check", "for", "remote", "errors", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_device.py#L191-L224
240,716
google/openhtf
openhtf/util/multicast.py
send
def send(query, address=DEFAULT_ADDRESS, port=DEFAULT_PORT, ttl=DEFAULT_TTL, local_only=False, timeout_s=2): """Sends a query to the given multicast socket and returns responses. Args: query: The string query to send. address: Multicast IP address component of the socket to send to. port: Multicast UDP port component of the socket to send to. ttl: TTL for multicast messages. 1 to keep traffic in-network. timeout_s: Seconds to wait for responses. Returns: A set of all responses that arrived before the timeout expired. Responses are tuples of (sender_address, message). """ # Set up the socket as a UDP Multicast socket with the given timeout. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) if local_only: # Set outgoing interface to localhost to ensure no packets leave this host. sock.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_IF, struct.pack('!L', LOCALHOST_ADDRESS)) sock.settimeout(timeout_s) sock.sendto(query.encode('utf-8'), (address, port)) # Set up our thread-safe Queue for handling responses. recv_queue = queue.Queue() def _handle_responses(): while True: try: data, address = sock.recvfrom(MAX_MESSAGE_BYTES) data = data.decode('utf-8') except socket.timeout: recv_queue.put(None) break else: _LOG.debug('Multicast response to query "%s": %s:%s', query, address[0], data) recv_queue.put((address[0], str(data))) # Yield responses as they come in, giving up once timeout expires. response_thread = threading.Thread(target=_handle_responses) response_thread.start() while response_thread.is_alive(): recv_tuple = recv_queue.get() if not recv_tuple: break yield recv_tuple response_thread.join()
python
def send(query, address=DEFAULT_ADDRESS, port=DEFAULT_PORT, ttl=DEFAULT_TTL, local_only=False, timeout_s=2): # Set up the socket as a UDP Multicast socket with the given timeout. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) if local_only: # Set outgoing interface to localhost to ensure no packets leave this host. sock.setsockopt( socket.IPPROTO_IP, socket.IP_MULTICAST_IF, struct.pack('!L', LOCALHOST_ADDRESS)) sock.settimeout(timeout_s) sock.sendto(query.encode('utf-8'), (address, port)) # Set up our thread-safe Queue for handling responses. recv_queue = queue.Queue() def _handle_responses(): while True: try: data, address = sock.recvfrom(MAX_MESSAGE_BYTES) data = data.decode('utf-8') except socket.timeout: recv_queue.put(None) break else: _LOG.debug('Multicast response to query "%s": %s:%s', query, address[0], data) recv_queue.put((address[0], str(data))) # Yield responses as they come in, giving up once timeout expires. response_thread = threading.Thread(target=_handle_responses) response_thread.start() while response_thread.is_alive(): recv_tuple = recv_queue.get() if not recv_tuple: break yield recv_tuple response_thread.join()
[ "def", "send", "(", "query", ",", "address", "=", "DEFAULT_ADDRESS", ",", "port", "=", "DEFAULT_PORT", ",", "ttl", "=", "DEFAULT_TTL", ",", "local_only", "=", "False", ",", "timeout_s", "=", "2", ")", ":", "# Set up the socket as a UDP Multicast socket with the gi...
Sends a query to the given multicast socket and returns responses. Args: query: The string query to send. address: Multicast IP address component of the socket to send to. port: Multicast UDP port component of the socket to send to. ttl: TTL for multicast messages. 1 to keep traffic in-network. timeout_s: Seconds to wait for responses. Returns: A set of all responses that arrived before the timeout expired. Responses are tuples of (sender_address, message).
[ "Sends", "a", "query", "to", "the", "given", "multicast", "socket", "and", "returns", "responses", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/multicast.py#L135-L188
240,717
google/openhtf
openhtf/util/multicast.py
MulticastListener.run
def run(self): """Listen for pings until stopped.""" self._live = True self._sock.settimeout(self.LISTEN_TIMEOUT_S) # Passing in INADDR_ANY means the kernel will choose the default interface. # The localhost address is used to receive messages sent in "local_only" # mode and the default address is used to receive all other messages. for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS): self._sock.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP # assigned to the interface on which to listen. struct.pack('!4sL', socket.inet_aton(self.address), interface_ip)) if sys.platform == 'darwin': self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Allow multiple listeners to bind. else: self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow multiple listeners to bind. self._sock.bind((self.address, self.port)) while self._live: try: data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES) data = data.decode('utf-8') log_line = 'Received multicast message from %s: %s' % (address, data) response = self._callback(data) if response is not None: log_line += ', responding with %s bytes' % len(response) # Send replies out-of-band instead of with the same multicast socket # so that multiple processes on the same host can listen for # requests and reply (if they all try to use the multicast socket # to reply, they conflict and this sendto fails). response = response.encode('utf-8') socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto( response, address) _LOG.debug(log_line) except socket.timeout: pass except socket.error: _LOG.debug('Error receiving multicast message', exc_info=True)
python
def run(self): self._live = True self._sock.settimeout(self.LISTEN_TIMEOUT_S) # Passing in INADDR_ANY means the kernel will choose the default interface. # The localhost address is used to receive messages sent in "local_only" # mode and the default address is used to receive all other messages. for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS): self._sock.setsockopt( socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP # assigned to the interface on which to listen. struct.pack('!4sL', socket.inet_aton(self.address), interface_ip)) if sys.platform == 'darwin': self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Allow multiple listeners to bind. else: self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow multiple listeners to bind. self._sock.bind((self.address, self.port)) while self._live: try: data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES) data = data.decode('utf-8') log_line = 'Received multicast message from %s: %s' % (address, data) response = self._callback(data) if response is not None: log_line += ', responding with %s bytes' % len(response) # Send replies out-of-band instead of with the same multicast socket # so that multiple processes on the same host can listen for # requests and reply (if they all try to use the multicast socket # to reply, they conflict and this sendto fails). response = response.encode('utf-8') socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto( response, address) _LOG.debug(log_line) except socket.timeout: pass except socket.error: _LOG.debug('Error receiving multicast message', exc_info=True)
[ "def", "run", "(", "self", ")", ":", "self", ".", "_live", "=", "True", "self", ".", "_sock", ".", "settimeout", "(", "self", ".", "LISTEN_TIMEOUT_S", ")", "# Passing in INADDR_ANY means the kernel will choose the default interface.", "# The localhost address is used to r...
Listen for pings until stopped.
[ "Listen", "for", "pings", "until", "stopped", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/multicast.py#L87-L132
240,718
google/openhtf
openhtf/plugs/usb/fastboot_protocol.py
FastbootProtocol._handle_progress
def _handle_progress(self, total, progress_callback): # pylint: disable=no-self-use """Calls the callback with the current progress and total .""" current = 0 while True: current += yield try: progress_callback(current, total) except Exception: # pylint: disable=broad-except _LOG.exception('Progress callback raised an exception. %s', progress_callback) continue
python
def _handle_progress(self, total, progress_callback): # pylint: disable=no-self-use current = 0 while True: current += yield try: progress_callback(current, total) except Exception: # pylint: disable=broad-except _LOG.exception('Progress callback raised an exception. %s', progress_callback) continue
[ "def", "_handle_progress", "(", "self", ",", "total", ",", "progress_callback", ")", ":", "# pylint: disable=no-self-use", "current", "=", "0", "while", "True", ":", "current", "+=", "yield", "try", ":", "progress_callback", "(", "current", ",", "total", ")", ...
Calls the callback with the current progress and total .
[ "Calls", "the", "callback", "with", "the", "current", "progress", "and", "total", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_protocol.py#L162-L172
240,719
google/openhtf
openhtf/plugs/usb/fastboot_protocol.py
FastbootCommands._simple_command
def _simple_command(self, command, arg=None, **kwargs): """Send a simple command.""" self._protocol.send_command(command, arg) return self._protocol.handle_simple_responses(**kwargs)
python
def _simple_command(self, command, arg=None, **kwargs): self._protocol.send_command(command, arg) return self._protocol.handle_simple_responses(**kwargs)
[ "def", "_simple_command", "(", "self", ",", "command", ",", "arg", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_protocol", ".", "send_command", "(", "command", ",", "arg", ")", "return", "self", ".", "_protocol", ".", "handle_simple_res...
Send a simple command.
[ "Send", "a", "simple", "command", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_protocol.py#L210-L213
240,720
google/openhtf
openhtf/output/servers/dashboard_server.py
_discover
def _discover(**kwargs): """Yields info about station servers announcing themselves via multicast.""" query = station_server.MULTICAST_QUERY for host, response in multicast.send(query, **kwargs): try: result = json.loads(response) except ValueError: _LOG.warn('Received bad JSON over multicast from %s: %s', host, response) try: yield StationInfo(result['cell'], host, result['port'], result['station_id'], 'ONLINE', result.get('test_description'), result['test_name']) except KeyError: if 'last_activity_time_millis' in result: _LOG.debug('Received old station API response on multicast. Ignoring.') else: _LOG.warn('Received bad multicast response from %s: %s', host, response)
python
def _discover(**kwargs): query = station_server.MULTICAST_QUERY for host, response in multicast.send(query, **kwargs): try: result = json.loads(response) except ValueError: _LOG.warn('Received bad JSON over multicast from %s: %s', host, response) try: yield StationInfo(result['cell'], host, result['port'], result['station_id'], 'ONLINE', result.get('test_description'), result['test_name']) except KeyError: if 'last_activity_time_millis' in result: _LOG.debug('Received old station API response on multicast. Ignoring.') else: _LOG.warn('Received bad multicast response from %s: %s', host, response)
[ "def", "_discover", "(", "*", "*", "kwargs", ")", ":", "query", "=", "station_server", ".", "MULTICAST_QUERY", "for", "host", ",", "response", "in", "multicast", ".", "send", "(", "query", ",", "*", "*", "kwargs", ")", ":", "try", ":", "result", "=", ...
Yields info about station servers announcing themselves via multicast.
[ "Yields", "info", "about", "station", "servers", "announcing", "themselves", "via", "multicast", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/dashboard_server.py#L35-L52
240,721
google/openhtf
openhtf/output/servers/dashboard_server.py
DashboardPubSub.update_stations
def update_stations(cls, station_info_list): """Called by the station discovery loop to update the station map.""" with cls.station_map_lock: # By default, assume old stations are unreachable. for host_port, station_info in six.iteritems(cls.station_map): cls.station_map[host_port] = station_info._replace(status='UNREACHABLE') for station_info in station_info_list: host_port = '%s:%s' % (station_info.host, station_info.port) cls.station_map[host_port] = station_info
python
def update_stations(cls, station_info_list): with cls.station_map_lock: # By default, assume old stations are unreachable. for host_port, station_info in six.iteritems(cls.station_map): cls.station_map[host_port] = station_info._replace(status='UNREACHABLE') for station_info in station_info_list: host_port = '%s:%s' % (station_info.host, station_info.port) cls.station_map[host_port] = station_info
[ "def", "update_stations", "(", "cls", ",", "station_info_list", ")", ":", "with", "cls", ".", "station_map_lock", ":", "# By default, assume old stations are unreachable.", "for", "host_port", ",", "station_info", "in", "six", ".", "iteritems", "(", "cls", ".", "sta...
Called by the station discovery loop to update the station map.
[ "Called", "by", "the", "station", "discovery", "loop", "to", "update", "the", "station", "map", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/dashboard_server.py#L79-L89
240,722
google/openhtf
openhtf/output/servers/dashboard_server.py
DashboardPubSub.publish_if_new
def publish_if_new(cls): """If the station map has changed, publish the new information.""" message = cls.make_message() if message != cls.last_message: super(DashboardPubSub, cls).publish(message) cls.last_message = message
python
def publish_if_new(cls): message = cls.make_message() if message != cls.last_message: super(DashboardPubSub, cls).publish(message) cls.last_message = message
[ "def", "publish_if_new", "(", "cls", ")", ":", "message", "=", "cls", ".", "make_message", "(", ")", "if", "message", "!=", "cls", ".", "last_message", ":", "super", "(", "DashboardPubSub", ",", "cls", ")", ".", "publish", "(", "message", ")", "cls", "...
If the station map has changed, publish the new information.
[ "If", "the", "station", "map", "has", "changed", "publish", "the", "new", "information", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/dashboard_server.py#L92-L97
240,723
google/openhtf
examples/phase_groups.py
run_basic_group
def run_basic_group(): """Run the basic phase group example. In this example, there are no terminal phases; all phases are run. """ test = htf.Test(htf.PhaseGroup( setup=[setup_phase], main=[main_phase], teardown=[teardown_phase], )) test.execute()
python
def run_basic_group(): test = htf.Test(htf.PhaseGroup( setup=[setup_phase], main=[main_phase], teardown=[teardown_phase], )) test.execute()
[ "def", "run_basic_group", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "setup", "=", "[", "setup_phase", "]", ",", "main", "=", "[", "main_phase", "]", ",", "teardown", "=", "[", "teardown_phase", "]", ",", ")",...
Run the basic phase group example. In this example, there are no terminal phases; all phases are run.
[ "Run", "the", "basic", "phase", "group", "example", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/phase_groups.py#L54-L64
240,724
google/openhtf
examples/phase_groups.py
run_setup_error_group
def run_setup_error_group(): """Run the phase group example where an error occurs in a setup phase. The terminal setup phase shortcuts the test. The main phases are skipped. The PhaseGroup is not entered, so the teardown phases are also skipped. """ test = htf.Test(htf.PhaseGroup( setup=[error_setup_phase], main=[main_phase], teardown=[teardown_phase], )) test.execute()
python
def run_setup_error_group(): test = htf.Test(htf.PhaseGroup( setup=[error_setup_phase], main=[main_phase], teardown=[teardown_phase], )) test.execute()
[ "def", "run_setup_error_group", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "setup", "=", "[", "error_setup_phase", "]", ",", "main", "=", "[", "main_phase", "]", ",", "teardown", "=", "[", "teardown_phase", "]", ...
Run the phase group example where an error occurs in a setup phase. The terminal setup phase shortcuts the test. The main phases are skipped. The PhaseGroup is not entered, so the teardown phases are also skipped.
[ "Run", "the", "phase", "group", "example", "where", "an", "error", "occurs", "in", "a", "setup", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/phase_groups.py#L67-L79
240,725
google/openhtf
examples/phase_groups.py
run_main_error_group
def run_main_error_group(): """Run the phase group example where an error occurs in a main phase. The main phase in this example is terminal. The PhaseGroup was entered because the setup phases ran without error, so the teardown phases are run. The other main phase is skipped. """ test = htf.Test(htf.PhaseGroup( setup=[setup_phase], main=[error_main_phase, main_phase], teardown=[teardown_phase], )) test.execute()
python
def run_main_error_group(): test = htf.Test(htf.PhaseGroup( setup=[setup_phase], main=[error_main_phase, main_phase], teardown=[teardown_phase], )) test.execute()
[ "def", "run_main_error_group", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "setup", "=", "[", "setup_phase", "]", ",", "main", "=", "[", "error_main_phase", ",", "main_phase", "]", ",", "teardown", "=", "[", "tea...
Run the phase group example where an error occurs in a main phase. The main phase in this example is terminal. The PhaseGroup was entered because the setup phases ran without error, so the teardown phases are run. The other main phase is skipped.
[ "Run", "the", "phase", "group", "example", "where", "an", "error", "occurs", "in", "a", "main", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/phase_groups.py#L82-L94
240,726
google/openhtf
examples/phase_groups.py
run_nested_groups
def run_nested_groups(): """Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase """ test = htf.Test( htf.PhaseGroup( main=[ main_phase, htf.PhaseGroup.with_teardown(inner_teardown_phase)( inner_main_phase), ], teardown=[teardown_phase] ) ) test.execute()
python
def run_nested_groups(): test = htf.Test( htf.PhaseGroup( main=[ main_phase, htf.PhaseGroup.with_teardown(inner_teardown_phase)( inner_main_phase), ], teardown=[teardown_phase] ) ) test.execute()
[ "def", "run_nested_groups", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "main", "=", "[", "main_phase", ",", "htf", ".", "PhaseGroup", ".", "with_teardown", "(", "inner_teardown_phase", ")", "(", "inner_main_phase", ...
Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase
[ "Run", "the", "nested", "groups", "example", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/phase_groups.py#L97-L117
240,727
google/openhtf
examples/phase_groups.py
run_nested_error_groups
def run_nested_error_groups(): """Run nested groups example where an error occurs in nested main phase. In this example, the first main phase in the nested PhaseGroup errors out. The other inner main phase is skipped, as is the outer main phase. Both PhaseGroups were entered, so both teardown phases are run. """ test = htf.Test( htf.PhaseGroup( main=[ htf.PhaseGroup.with_teardown(inner_teardown_phase)( error_main_phase, main_phase), main_phase, ], teardown=[teardown_phase], ) ) test.execute()
python
def run_nested_error_groups(): test = htf.Test( htf.PhaseGroup( main=[ htf.PhaseGroup.with_teardown(inner_teardown_phase)( error_main_phase, main_phase), main_phase, ], teardown=[teardown_phase], ) ) test.execute()
[ "def", "run_nested_error_groups", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "main", "=", "[", "htf", ".", "PhaseGroup", ".", "with_teardown", "(", "inner_teardown_phase", ")", "(", "error_main_phase", ",", "main_phas...
Run nested groups example where an error occurs in nested main phase. In this example, the first main phase in the nested PhaseGroup errors out. The other inner main phase is skipped, as is the outer main phase. Both PhaseGroups were entered, so both teardown phases are run.
[ "Run", "nested", "groups", "example", "where", "an", "error", "occurs", "in", "nested", "main", "phase", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/phase_groups.py#L120-L137
240,728
google/openhtf
bin/units_from_xls.py
main
def main(): """Main entry point for UNECE code .xls parsing.""" parser = argparse.ArgumentParser( description='Reads in a .xls file and generates a units module for ' 'OpenHTF.', prog='python units_from_xls.py') parser.add_argument('xlsfile', type=str, help='the .xls file to parse') parser.add_argument( '--outfile', type=str, default=os.path.join(os.path.dirname(__file__), os.path.pardir, 'openhtf','util', 'units.py'), help='where to put the generated .py file.') args = parser.parse_args() if not os.path.exists(args.xlsfile): print('Unable to locate the file "%s".' % args.xlsfile) parser.print_help() sys.exit() unit_defs = unit_defs_from_sheet( xlrd.open_workbook(args.xlsfile).sheet_by_name(SHEET_NAME), COLUMN_NAMES) _, tmp_path = mkstemp() with open(tmp_path, 'w') as new_file: new_file.write(PRE) new_file.writelines( [line.encode('utf8', 'replace') for line in unit_defs]) new_file.write(POST) new_file.flush() os.remove(args.outfile) shutil.move(tmp_path, args.outfile)
python
def main(): parser = argparse.ArgumentParser( description='Reads in a .xls file and generates a units module for ' 'OpenHTF.', prog='python units_from_xls.py') parser.add_argument('xlsfile', type=str, help='the .xls file to parse') parser.add_argument( '--outfile', type=str, default=os.path.join(os.path.dirname(__file__), os.path.pardir, 'openhtf','util', 'units.py'), help='where to put the generated .py file.') args = parser.parse_args() if not os.path.exists(args.xlsfile): print('Unable to locate the file "%s".' % args.xlsfile) parser.print_help() sys.exit() unit_defs = unit_defs_from_sheet( xlrd.open_workbook(args.xlsfile).sheet_by_name(SHEET_NAME), COLUMN_NAMES) _, tmp_path = mkstemp() with open(tmp_path, 'w') as new_file: new_file.write(PRE) new_file.writelines( [line.encode('utf8', 'replace') for line in unit_defs]) new_file.write(POST) new_file.flush() os.remove(args.outfile) shutil.move(tmp_path, args.outfile)
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Reads in a .xls file and generates a units module for '", "'OpenHTF.'", ",", "prog", "=", "'python units_from_xls.py'", ")", "parser", ".", "add_argument", "(", ...
Main entry point for UNECE code .xls parsing.
[ "Main", "entry", "point", "for", "UNECE", "code", ".", "xls", "parsing", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/bin/units_from_xls.py#L169-L203
240,729
google/openhtf
bin/units_from_xls.py
unit_defs_from_sheet
def unit_defs_from_sheet(sheet, column_names): """A generator that parses a worksheet containing UNECE code definitions. Args: sheet: An xldr.sheet object representing a UNECE code worksheet. column_names: A list/tuple with the expected column names corresponding to the unit name, code and suffix in that order. Yields: Lines of Python source code that define OpenHTF Unit objects. """ seen = set() try: col_indices = {} rows = sheet.get_rows() # Find the indices for the columns we care about. for idx, cell in enumerate(six.next(rows)): if cell.value in column_names: col_indices[cell.value] = idx # loop over all remaining rows and pull out units. for row in rows: name = row[col_indices[column_names[0]]].value.replace("'", r'\'') code = row[col_indices[column_names[1]]].value suffix = row[col_indices[column_names[2]]].value.replace("'", r'\'') key = unit_key_from_name(name) if key in seen: continue seen.add(key) # Split on ' or ' to support the units like '% or pct' for suffix in suffix.split(' or '): yield "%s = UnitDescriptor('%s', '%s', '''%s''')\n" % ( key, name, code, suffix) yield "ALL_UNITS.append(%s)\n" % key except xlrd.XLRDError: sys.stdout.write('Unable to process the .xls file.')
python
def unit_defs_from_sheet(sheet, column_names): seen = set() try: col_indices = {} rows = sheet.get_rows() # Find the indices for the columns we care about. for idx, cell in enumerate(six.next(rows)): if cell.value in column_names: col_indices[cell.value] = idx # loop over all remaining rows and pull out units. for row in rows: name = row[col_indices[column_names[0]]].value.replace("'", r'\'') code = row[col_indices[column_names[1]]].value suffix = row[col_indices[column_names[2]]].value.replace("'", r'\'') key = unit_key_from_name(name) if key in seen: continue seen.add(key) # Split on ' or ' to support the units like '% or pct' for suffix in suffix.split(' or '): yield "%s = UnitDescriptor('%s', '%s', '''%s''')\n" % ( key, name, code, suffix) yield "ALL_UNITS.append(%s)\n" % key except xlrd.XLRDError: sys.stdout.write('Unable to process the .xls file.')
[ "def", "unit_defs_from_sheet", "(", "sheet", ",", "column_names", ")", ":", "seen", "=", "set", "(", ")", "try", ":", "col_indices", "=", "{", "}", "rows", "=", "sheet", ".", "get_rows", "(", ")", "# Find the indices for the columns we care about.", "for", "id...
A generator that parses a worksheet containing UNECE code definitions. Args: sheet: An xldr.sheet object representing a UNECE code worksheet. column_names: A list/tuple with the expected column names corresponding to the unit name, code and suffix in that order. Yields: Lines of Python source code that define OpenHTF Unit objects.
[ "A", "generator", "that", "parses", "a", "worksheet", "containing", "UNECE", "code", "definitions", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/bin/units_from_xls.py#L206-L242
240,730
google/openhtf
bin/units_from_xls.py
unit_key_from_name
def unit_key_from_name(name): """Return a legal python name for the given name for use as a unit key.""" result = name for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS): result = result.replace(old, new) # Collapse redundant underscores and convert to uppercase. result = re.sub(r'_+', '_', result.upper()) return result
python
def unit_key_from_name(name): result = name for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS): result = result.replace(old, new) # Collapse redundant underscores and convert to uppercase. result = re.sub(r'_+', '_', result.upper()) return result
[ "def", "unit_key_from_name", "(", "name", ")", ":", "result", "=", "name", "for", "old", ",", "new", "in", "six", ".", "iteritems", "(", "UNIT_KEY_REPLACEMENTS", ")", ":", "result", "=", "result", ".", "replace", "(", "old", ",", "new", ")", "# Collapse ...
Return a legal python name for the given name for use as a unit key.
[ "Return", "a", "legal", "python", "name", "for", "the", "given", "name", "for", "use", "as", "a", "unit", "key", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/bin/units_from_xls.py#L245-L255
240,731
google/openhtf
openhtf/plugs/usb/adb_message.py
make_wire_commands
def make_wire_commands(*ids): """Assemble the commands.""" cmd_to_wire = { cmd: sum(ord(c) << (i * 8) for i, c in enumerate(cmd)) for cmd in ids } wire_to_cmd = {wire: cmd for cmd, wire in six.iteritems(cmd_to_wire)} return cmd_to_wire, wire_to_cmd
python
def make_wire_commands(*ids): cmd_to_wire = { cmd: sum(ord(c) << (i * 8) for i, c in enumerate(cmd)) for cmd in ids } wire_to_cmd = {wire: cmd for cmd, wire in six.iteritems(cmd_to_wire)} return cmd_to_wire, wire_to_cmd
[ "def", "make_wire_commands", "(", "*", "ids", ")", ":", "cmd_to_wire", "=", "{", "cmd", ":", "sum", "(", "ord", "(", "c", ")", "<<", "(", "i", "*", "8", ")", "for", "i", ",", "c", "in", "enumerate", "(", "cmd", ")", ")", "for", "cmd", "in", "...
Assemble the commands.
[ "Assemble", "the", "commands", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_message.py#L55-L61
240,732
google/openhtf
openhtf/plugs/usb/adb_message.py
RawAdbMessage.to_adb_message
def to_adb_message(self, data): """Turn the data into an ADB message.""" message = AdbMessage(AdbMessage.WIRE_TO_CMD.get(self.cmd), self.arg0, self.arg1, data) if (len(data) != self.data_length or message.data_crc32 != self.data_checksum): raise usb_exceptions.AdbDataIntegrityError( '%s (%s) received invalid data: %s', message, self, repr(data)) return message
python
def to_adb_message(self, data): message = AdbMessage(AdbMessage.WIRE_TO_CMD.get(self.cmd), self.arg0, self.arg1, data) if (len(data) != self.data_length or message.data_crc32 != self.data_checksum): raise usb_exceptions.AdbDataIntegrityError( '%s (%s) received invalid data: %s', message, self, repr(data)) return message
[ "def", "to_adb_message", "(", "self", ",", "data", ")", ":", "message", "=", "AdbMessage", "(", "AdbMessage", ".", "WIRE_TO_CMD", ".", "get", "(", "self", ".", "cmd", ")", ",", "self", ".", "arg0", ",", "self", ".", "arg1", ",", "data", ")", "if", ...
Turn the data into an ADB message.
[ "Turn", "the", "data", "into", "an", "ADB", "message", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_message.py#L70-L78
240,733
google/openhtf
openhtf/plugs/usb/adb_message.py
AdbTransportAdapter.write_message
def write_message(self, message, timeout): """Send the given message over this transport. Args: message: The AdbMessage to send. timeout: Use this timeout for the entire write operation, it should be an instance of timeouts.PolledTimeout. """ with self._writer_lock: self._transport.write(message.header, timeout.remaining_ms) # Use any remaining time to send the data. Note that if we get this far, # we always at least try to send the data (with a minimum of 10ms timeout) # because we don't want the remote end to get out of sync because we sent # a header but no data. if timeout.has_expired(): _LOG.warning('Timed out between AdbMessage header and data, sending ' 'data anyway with 10ms timeout') timeout = timeouts.PolledTimeout.from_millis(10) self._transport.write(message.data, timeout.remaining_ms)
python
def write_message(self, message, timeout): with self._writer_lock: self._transport.write(message.header, timeout.remaining_ms) # Use any remaining time to send the data. Note that if we get this far, # we always at least try to send the data (with a minimum of 10ms timeout) # because we don't want the remote end to get out of sync because we sent # a header but no data. if timeout.has_expired(): _LOG.warning('Timed out between AdbMessage header and data, sending ' 'data anyway with 10ms timeout') timeout = timeouts.PolledTimeout.from_millis(10) self._transport.write(message.data, timeout.remaining_ms)
[ "def", "write_message", "(", "self", ",", "message", ",", "timeout", ")", ":", "with", "self", ".", "_writer_lock", ":", "self", ".", "_transport", ".", "write", "(", "message", ".", "header", ",", "timeout", ".", "remaining_ms", ")", "# Use any remaining ti...
Send the given message over this transport. Args: message: The AdbMessage to send. timeout: Use this timeout for the entire write operation, it should be an instance of timeouts.PolledTimeout.
[ "Send", "the", "given", "message", "over", "this", "transport", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_message.py#L109-L128
240,734
google/openhtf
openhtf/plugs/usb/adb_message.py
AdbTransportAdapter.read_message
def read_message(self, timeout): """Read an AdbMessage from this transport. Args: timeout: Timeout for the entire read operation, in the form of a timeouts.PolledTimeout instance. Note that for packets with a data payload, two USB reads are performed. Returns: The ADB message read from the device. Raises: UsbReadFailedError: There's an error during read, including timeout. AdbProtocolError: A message is incorrectly formatted. AdbTimeoutError: timeout is already expired, or expires before we read the entire message, specifically between reading header and data packets. """ with self._reader_lock: raw_header = self._transport.read( struct.calcsize(AdbMessage.HEADER_STRUCT_FORMAT), timeout.remaining_ms) if not raw_header: raise usb_exceptions.AdbProtocolError('Adb connection lost') try: raw_message = RawAdbMessage(*struct.unpack( AdbMessage.HEADER_STRUCT_FORMAT, raw_header)) except struct.error as exception: raise usb_exceptions.AdbProtocolError( 'Unable to unpack ADB command (%s): %s (%s)', AdbMessage.HEADER_STRUCT_FORMAT, raw_header, exception) if raw_message.data_length > 0: if timeout.has_expired(): _LOG.warning('Timed out between AdbMessage header and data, reading ' 'data anyway with 10ms timeout') timeout = timeouts.PolledTimeout.from_millis(10) data = self._transport.read(raw_message.data_length, timeout.remaining_ms) else: data = '' return raw_message.to_adb_message(data)
python
def read_message(self, timeout): with self._reader_lock: raw_header = self._transport.read( struct.calcsize(AdbMessage.HEADER_STRUCT_FORMAT), timeout.remaining_ms) if not raw_header: raise usb_exceptions.AdbProtocolError('Adb connection lost') try: raw_message = RawAdbMessage(*struct.unpack( AdbMessage.HEADER_STRUCT_FORMAT, raw_header)) except struct.error as exception: raise usb_exceptions.AdbProtocolError( 'Unable to unpack ADB command (%s): %s (%s)', AdbMessage.HEADER_STRUCT_FORMAT, raw_header, exception) if raw_message.data_length > 0: if timeout.has_expired(): _LOG.warning('Timed out between AdbMessage header and data, reading ' 'data anyway with 10ms timeout') timeout = timeouts.PolledTimeout.from_millis(10) data = self._transport.read(raw_message.data_length, timeout.remaining_ms) else: data = '' return raw_message.to_adb_message(data)
[ "def", "read_message", "(", "self", ",", "timeout", ")", ":", "with", "self", ".", "_reader_lock", ":", "raw_header", "=", "self", ".", "_transport", ".", "read", "(", "struct", ".", "calcsize", "(", "AdbMessage", ".", "HEADER_STRUCT_FORMAT", ")", ",", "ti...
Read an AdbMessage from this transport. Args: timeout: Timeout for the entire read operation, in the form of a timeouts.PolledTimeout instance. Note that for packets with a data payload, two USB reads are performed. Returns: The ADB message read from the device. Raises: UsbReadFailedError: There's an error during read, including timeout. AdbProtocolError: A message is incorrectly formatted. AdbTimeoutError: timeout is already expired, or expires before we read the entire message, specifically between reading header and data packets.
[ "Read", "an", "AdbMessage", "from", "this", "transport", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_message.py#L130-L172
240,735
google/openhtf
openhtf/plugs/usb/adb_message.py
AdbTransportAdapter.read_until
def read_until(self, expected_commands, timeout): """Read AdbMessages from this transport until we get an expected command. The ADB protocol specifies that before a successful CNXN handshake, any other packets must be ignored, so this method provides the ability to ignore unwanted commands. It's primarily used during the initial connection to the device. See Read() for more details, including more exceptions that may be raised. Args: expected_commands: Iterable of expected command responses, like ('CNXN', 'AUTH'). timeout: timeouts.PolledTimeout object to use for timeout. Returns: The ADB message received that matched one of expected_commands. Raises: AdbProtocolError: If timeout expires between reads, this can happen if we are getting spammed with unexpected commands. """ msg = timeouts.loop_until_timeout_or_valid( timeout, lambda: self.read_message(timeout), lambda m: m.command in expected_commands, 0) if msg.command not in expected_commands: raise usb_exceptions.AdbTimeoutError( 'Timed out establishing connection, waiting for: %s', expected_commands) return msg
python
def read_until(self, expected_commands, timeout): msg = timeouts.loop_until_timeout_or_valid( timeout, lambda: self.read_message(timeout), lambda m: m.command in expected_commands, 0) if msg.command not in expected_commands: raise usb_exceptions.AdbTimeoutError( 'Timed out establishing connection, waiting for: %s', expected_commands) return msg
[ "def", "read_until", "(", "self", ",", "expected_commands", ",", "timeout", ")", ":", "msg", "=", "timeouts", ".", "loop_until_timeout_or_valid", "(", "timeout", ",", "lambda", ":", "self", ".", "read_message", "(", "timeout", ")", ",", "lambda", "m", ":", ...
Read AdbMessages from this transport until we get an expected command. The ADB protocol specifies that before a successful CNXN handshake, any other packets must be ignored, so this method provides the ability to ignore unwanted commands. It's primarily used during the initial connection to the device. See Read() for more details, including more exceptions that may be raised. Args: expected_commands: Iterable of expected command responses, like ('CNXN', 'AUTH'). timeout: timeouts.PolledTimeout object to use for timeout. Returns: The ADB message received that matched one of expected_commands. Raises: AdbProtocolError: If timeout expires between reads, this can happen if we are getting spammed with unexpected commands.
[ "Read", "AdbMessages", "from", "this", "transport", "until", "we", "get", "an", "expected", "command", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_message.py#L174-L202
240,736
google/openhtf
openhtf/plugs/usb/adb_message.py
AdbMessage.header
def header(self): """The message header.""" return struct.pack( self.HEADER_STRUCT_FORMAT, self._command, self.arg0, self.arg1, len(self.data), self.data_crc32, self.magic)
python
def header(self): return struct.pack( self.HEADER_STRUCT_FORMAT, self._command, self.arg0, self.arg1, len(self.data), self.data_crc32, self.magic)
[ "def", "header", "(", "self", ")", ":", "return", "struct", ".", "pack", "(", "self", ".", "HEADER_STRUCT_FORMAT", ",", "self", ".", "_command", ",", "self", ".", "arg0", ",", "self", ".", "arg1", ",", "len", "(", "self", ".", "data", ")", ",", "se...
The message header.
[ "The", "message", "header", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_message.py#L276-L280
240,737
google/openhtf
openhtf/plugs/usb/filesync_service.py
_make_message_type
def _make_message_type(name, attributes, has_data=True): """Make a message type for the AdbTransport subclasses.""" def assert_command_is(self, command): # pylint: disable=invalid-name """Assert that a message's command matches the given command.""" if self.command != command: raise usb_exceptions.AdbProtocolError( 'Expected %s command, received %s', command, self) return type(name, (collections.namedtuple(name, attributes),), { 'assert_command_is': assert_command_is, 'has_data': has_data, # Struct format on the wire has an unsigned int for each attr. 'struct_format': '<%sI' % len(attributes.split()), })
python
def _make_message_type(name, attributes, has_data=True): def assert_command_is(self, command): # pylint: disable=invalid-name """Assert that a message's command matches the given command.""" if self.command != command: raise usb_exceptions.AdbProtocolError( 'Expected %s command, received %s', command, self) return type(name, (collections.namedtuple(name, attributes),), { 'assert_command_is': assert_command_is, 'has_data': has_data, # Struct format on the wire has an unsigned int for each attr. 'struct_format': '<%sI' % len(attributes.split()), })
[ "def", "_make_message_type", "(", "name", ",", "attributes", ",", "has_data", "=", "True", ")", ":", "def", "assert_command_is", "(", "self", ",", "command", ")", ":", "# pylint: disable=invalid-name", "\"\"\"Assert that a message's command matches the given command.\"\"\""...
Make a message type for the AdbTransport subclasses.
[ "Make", "a", "message", "type", "for", "the", "AdbTransport", "subclasses", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L130-L145
240,738
google/openhtf
openhtf/plugs/usb/filesync_service.py
FilesyncService.stat
def stat(self, filename, timeout=None): """Return device file stat.""" transport = StatFilesyncTransport(self.stream) transport.write_data('STAT', filename, timeout) stat_msg = transport.read_message(timeout) stat_msg.assert_command_is('STAT') return DeviceFileStat(filename, stat_msg.mode, stat_msg.size, stat_msg.time)
python
def stat(self, filename, timeout=None): transport = StatFilesyncTransport(self.stream) transport.write_data('STAT', filename, timeout) stat_msg = transport.read_message(timeout) stat_msg.assert_command_is('STAT') return DeviceFileStat(filename, stat_msg.mode, stat_msg.size, stat_msg.time)
[ "def", "stat", "(", "self", ",", "filename", ",", "timeout", "=", "None", ")", ":", "transport", "=", "StatFilesyncTransport", "(", "self", ".", "stream", ")", "transport", ".", "write_data", "(", "'STAT'", ",", "filename", ",", "timeout", ")", "stat_msg",...
Return device file stat.
[ "Return", "device", "file", "stat", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L173-L179
240,739
google/openhtf
openhtf/plugs/usb/filesync_service.py
FilesyncService.list
def list(self, path, timeout=None): """List directory contents on the device. Args: path: List the contents of this directory. timeout: Timeout to use for this operation. Returns: Generator yielding DeviceFileStat tuples representing the contents of the requested path. """ transport = DentFilesyncTransport(self.stream) transport.write_data('LIST', path, timeout) return (DeviceFileStat(dent_msg.name, dent_msg.mode, dent_msg.size, dent_msg.time) for dent_msg in transport.read_until_done('DENT', timeout))
python
def list(self, path, timeout=None): transport = DentFilesyncTransport(self.stream) transport.write_data('LIST', path, timeout) return (DeviceFileStat(dent_msg.name, dent_msg.mode, dent_msg.size, dent_msg.time) for dent_msg in transport.read_until_done('DENT', timeout))
[ "def", "list", "(", "self", ",", "path", ",", "timeout", "=", "None", ")", ":", "transport", "=", "DentFilesyncTransport", "(", "self", ".", "stream", ")", "transport", ".", "write_data", "(", "'LIST'", ",", "path", ",", "timeout", ")", "return", "(", ...
List directory contents on the device. Args: path: List the contents of this directory. timeout: Timeout to use for this operation. Returns: Generator yielding DeviceFileStat tuples representing the contents of the requested path.
[ "List", "directory", "contents", "on", "the", "device", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L181-L196
240,740
google/openhtf
openhtf/plugs/usb/filesync_service.py
FilesyncService.recv
def recv(self, filename, dest_file, timeout=None): """Retrieve a file from the device into the file-like dest_file.""" transport = DataFilesyncTransport(self.stream) transport.write_data('RECV', filename, timeout) for data_msg in transport.read_until_done('DATA', timeout): dest_file.write(data_msg.data)
python
def recv(self, filename, dest_file, timeout=None): transport = DataFilesyncTransport(self.stream) transport.write_data('RECV', filename, timeout) for data_msg in transport.read_until_done('DATA', timeout): dest_file.write(data_msg.data)
[ "def", "recv", "(", "self", ",", "filename", ",", "dest_file", ",", "timeout", "=", "None", ")", ":", "transport", "=", "DataFilesyncTransport", "(", "self", ".", "stream", ")", "transport", ".", "write_data", "(", "'RECV'", ",", "filename", ",", "timeout"...
Retrieve a file from the device into the file-like dest_file.
[ "Retrieve", "a", "file", "from", "the", "device", "into", "the", "file", "-", "like", "dest_file", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L198-L203
240,741
google/openhtf
openhtf/plugs/usb/filesync_service.py
FilesyncService._check_for_fail_message
def _check_for_fail_message(self, transport, exc_info, timeout): # pylint: disable=no-self-use """Check for a 'FAIL' message from transport. This method always raises, if 'FAIL' was read, it will raise an AdbRemoteError with the message, otherwise it will raise based on exc_info, which should be a tuple as per sys.exc_info(). Args: transport: Transport from which to read for a 'FAIL' message. exc_info: Exception info to raise if no 'FAIL' is read. timeout: Timeout to use for the read operation. Raises: AdbRemoteError: If a 'FAIL' is read, otherwise raises exc_info. """ try: transport.read_message(timeout) except usb_exceptions.CommonUsbError: # If we got a remote error, raise that exception. if sys.exc_info()[0] is usb_exceptions.AdbRemoteError: raise # Otherwise reraise the original exception. raise_with_traceback(exc_info[0](exc_info[1]), traceback=exc_info[2])
python
def _check_for_fail_message(self, transport, exc_info, timeout): # pylint: disable=no-self-use try: transport.read_message(timeout) except usb_exceptions.CommonUsbError: # If we got a remote error, raise that exception. if sys.exc_info()[0] is usb_exceptions.AdbRemoteError: raise # Otherwise reraise the original exception. raise_with_traceback(exc_info[0](exc_info[1]), traceback=exc_info[2])
[ "def", "_check_for_fail_message", "(", "self", ",", "transport", ",", "exc_info", ",", "timeout", ")", ":", "# pylint: disable=no-self-use", "try", ":", "transport", ".", "read_message", "(", "timeout", ")", "except", "usb_exceptions", ".", "CommonUsbError", ":", ...
Check for a 'FAIL' message from transport. This method always raises, if 'FAIL' was read, it will raise an AdbRemoteError with the message, otherwise it will raise based on exc_info, which should be a tuple as per sys.exc_info(). Args: transport: Transport from which to read for a 'FAIL' message. exc_info: Exception info to raise if no 'FAIL' is read. timeout: Timeout to use for the read operation. Raises: AdbRemoteError: If a 'FAIL' is read, otherwise raises exc_info.
[ "Check", "for", "a", "FAIL", "message", "from", "transport", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L205-L227
240,742
google/openhtf
openhtf/plugs/usb/filesync_service.py
AbstractFilesyncTransport.write_data
def write_data(self, command, data, timeout=None): """Shortcut for writing specifically a DataMessage.""" self.write_message(FilesyncMessageTypes.DataMessage(command, data), timeout)
python
def write_data(self, command, data, timeout=None): self.write_message(FilesyncMessageTypes.DataMessage(command, data), timeout)
[ "def", "write_data", "(", "self", ",", "command", ",", "data", ",", "timeout", "=", "None", ")", ":", "self", ".", "write_message", "(", "FilesyncMessageTypes", ".", "DataMessage", "(", "command", ",", "data", ")", ",", "timeout", ")" ]
Shortcut for writing specifically a DataMessage.
[ "Shortcut", "for", "writing", "specifically", "a", "DataMessage", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L362-L364
240,743
google/openhtf
openhtf/plugs/usb/filesync_service.py
AbstractFilesyncTransport.read_until_done
def read_until_done(self, command, timeout=None): """Yield messages read until we receive a 'DONE' command. Read messages of the given command until we receive a 'DONE' command. If a command different than the requested one is received, an AdbProtocolError is raised. Args: command: The command to expect, like 'DENT' or 'DATA'. timeout: The timeouts.PolledTimeout to use for this operation. Yields: Messages read, of type self.RECV_MSG_TYPE, see read_message(). Raises: AdbProtocolError: If an unexpected command is read. AdbRemoteError: If a 'FAIL' message is read. """ message = self.read_message(timeout) while message.command != 'DONE': message.assert_command_is(command) yield message message = self.read_message(timeout)
python
def read_until_done(self, command, timeout=None): message = self.read_message(timeout) while message.command != 'DONE': message.assert_command_is(command) yield message message = self.read_message(timeout)
[ "def", "read_until_done", "(", "self", ",", "command", ",", "timeout", "=", "None", ")", ":", "message", "=", "self", ".", "read_message", "(", "timeout", ")", "while", "message", ".", "command", "!=", "'DONE'", ":", "message", ".", "assert_command_is", "(...
Yield messages read until we receive a 'DONE' command. Read messages of the given command until we receive a 'DONE' command. If a command different than the requested one is received, an AdbProtocolError is raised. Args: command: The command to expect, like 'DENT' or 'DATA'. timeout: The timeouts.PolledTimeout to use for this operation. Yields: Messages read, of type self.RECV_MSG_TYPE, see read_message(). Raises: AdbProtocolError: If an unexpected command is read. AdbRemoteError: If a 'FAIL' message is read.
[ "Yield", "messages", "read", "until", "we", "receive", "a", "DONE", "command", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L391-L413
240,744
google/openhtf
openhtf/plugs/usb/filesync_service.py
AbstractFilesyncTransport.read_message
def read_message(self, timeout=None): """Read a message from this transport and return it. Reads a message of RECV_MSG_TYPE and returns it. Note that this method abstracts the data length and data read so that the caller simply gets the data along with the header in the returned message. Args: timeout: timeouts.PolledTimeout to use for the operation. Returns: An instance of self.RECV_MSG_TYPE that was read from self.stream. Raises: AdbProtocolError: If an invalid response is received. AdbRemoteError: If a FAIL response is received. """ raw_data = self.stream.read( struct.calcsize(self.RECV_MSG_TYPE.struct_format), timeout) try: raw_message = struct.unpack(self.RECV_MSG_TYPE.struct_format, raw_data) except struct.error: raise usb_exceptions.AdbProtocolError( '%s expected format "%s", got data %s', self, self.RECV_MSG_TYPE.struct_format, raw_data) if raw_message[0] not in self.WIRE_TO_CMD: raise usb_exceptions.AdbProtocolError( 'Unrecognized command id: %s', raw_message) # Swap out the wire command with the string equivalent. raw_message = (self.WIRE_TO_CMD[raw_message[0]],) + raw_message[1:] if self.RECV_MSG_TYPE.has_data and raw_message[-1]: # For messages that have data, the length of the data is the last field # in the struct. We do another read and swap out that length for the # actual data read before we create the namedtuple to return. data_len = raw_message[-1] raw_message = raw_message[:-1] + (self.stream.read(data_len, timeout),) if raw_message[0] not in self.VALID_RESPONSES: raise usb_exceptions.AdbProtocolError( '%s not a valid response for %s', raw_message[0], self) if raw_message[0] == 'FAIL': raise usb_exceptions.AdbRemoteError( 'Remote ADB failure: %s', raw_message) return self.RECV_MSG_TYPE(*raw_message)
python
def read_message(self, timeout=None): raw_data = self.stream.read( struct.calcsize(self.RECV_MSG_TYPE.struct_format), timeout) try: raw_message = struct.unpack(self.RECV_MSG_TYPE.struct_format, raw_data) except struct.error: raise usb_exceptions.AdbProtocolError( '%s expected format "%s", got data %s', self, self.RECV_MSG_TYPE.struct_format, raw_data) if raw_message[0] not in self.WIRE_TO_CMD: raise usb_exceptions.AdbProtocolError( 'Unrecognized command id: %s', raw_message) # Swap out the wire command with the string equivalent. raw_message = (self.WIRE_TO_CMD[raw_message[0]],) + raw_message[1:] if self.RECV_MSG_TYPE.has_data and raw_message[-1]: # For messages that have data, the length of the data is the last field # in the struct. We do another read and swap out that length for the # actual data read before we create the namedtuple to return. data_len = raw_message[-1] raw_message = raw_message[:-1] + (self.stream.read(data_len, timeout),) if raw_message[0] not in self.VALID_RESPONSES: raise usb_exceptions.AdbProtocolError( '%s not a valid response for %s', raw_message[0], self) if raw_message[0] == 'FAIL': raise usb_exceptions.AdbRemoteError( 'Remote ADB failure: %s', raw_message) return self.RECV_MSG_TYPE(*raw_message)
[ "def", "read_message", "(", "self", ",", "timeout", "=", "None", ")", ":", "raw_data", "=", "self", ".", "stream", ".", "read", "(", "struct", ".", "calcsize", "(", "self", ".", "RECV_MSG_TYPE", ".", "struct_format", ")", ",", "timeout", ")", "try", ":...
Read a message from this transport and return it. Reads a message of RECV_MSG_TYPE and returns it. Note that this method abstracts the data length and data read so that the caller simply gets the data along with the header in the returned message. Args: timeout: timeouts.PolledTimeout to use for the operation. Returns: An instance of self.RECV_MSG_TYPE that was read from self.stream. Raises: AdbProtocolError: If an invalid response is received. AdbRemoteError: If a FAIL response is received.
[ "Read", "a", "message", "from", "this", "transport", "and", "return", "it", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/filesync_service.py#L415-L461
240,745
google/openhtf
openhtf/output/proto/mfg_event_converter.py
_lazy_load_units_by_code
def _lazy_load_units_by_code(): """Populate dict of units by code iff UNITS_BY_CODE is empty.""" if UNITS_BY_CODE: # already populated return for unit in units.UNITS_BY_NAME.values(): UNITS_BY_CODE[unit.code] = unit
python
def _lazy_load_units_by_code(): if UNITS_BY_CODE: # already populated return for unit in units.UNITS_BY_NAME.values(): UNITS_BY_CODE[unit.code] = unit
[ "def", "_lazy_load_units_by_code", "(", ")", ":", "if", "UNITS_BY_CODE", ":", "# already populated", "return", "for", "unit", "in", "units", ".", "UNITS_BY_NAME", ".", "values", "(", ")", ":", "UNITS_BY_CODE", "[", "unit", ".", "code", "]", "=", "unit" ]
Populate dict of units by code iff UNITS_BY_CODE is empty.
[ "Populate", "dict", "of", "units", "by", "code", "iff", "UNITS_BY_CODE", "is", "empty", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L52-L59
240,746
google/openhtf
openhtf/output/proto/mfg_event_converter.py
_populate_basic_data
def _populate_basic_data(mfg_event, record): """Copies data from the OpenHTF TestRecord to the MfgEvent proto.""" # TODO: # * Missing in proto: set run name from metadata. # * `part_tags` field on proto is unused # * `timings` field on proto is unused. # * Handle arbitrary units as uom_code/uom_suffix. # Populate non-repeated fields. mfg_event.dut_serial = record.dut_id mfg_event.start_time_ms = record.start_time_millis mfg_event.end_time_ms = record.end_time_millis mfg_event.tester_name = record.station_id mfg_event.test_name = record.metadata.get('test_name') or record.station_id mfg_event.test_status = test_runs_converter.OUTCOME_MAP[record.outcome] mfg_event.operator_name = record.metadata.get('operator_name', '') mfg_event.test_version = str(record.metadata.get('test_version', '')) mfg_event.test_description = record.metadata.get('test_description', '') # Populate part_tags. mfg_event.part_tags.extend(record.metadata.get('part_tags', [])) # Populate phases. for phase in record.phases: mfg_phase = mfg_event.phases.add() mfg_phase.name = phase.name mfg_phase.description = phase.codeinfo.sourcecode mfg_phase.timing.start_time_millis = phase.start_time_millis mfg_phase.timing.end_time_millis = phase.end_time_millis # Populate failure codes. for details in record.outcome_details: failure_code = mfg_event.failure_codes.add() failure_code.code = details.code failure_code.details = details.description # Populate test logs. for log_record in record.log_records: test_log = mfg_event.test_logs.add() test_log.timestamp_millis = log_record.timestamp_millis test_log.log_message = log_record.message test_log.logger_name = log_record.logger_name test_log.levelno = log_record.level if log_record.level <= logging.DEBUG: test_log.level = test_runs_pb2.TestRunLogMessage.DEBUG elif log_record.level <= logging.INFO: test_log.level = test_runs_pb2.TestRunLogMessage.INFO elif log_record.level <= logging.WARNING: test_log.level = test_runs_pb2.TestRunLogMessage.WARNING elif log_record.level <= logging.ERROR: test_log.level = test_runs_pb2.TestRunLogMessage.ERROR elif log_record.level <= logging.CRITICAL: test_log.level = test_runs_pb2.TestRunLogMessage.CRITICAL test_log.log_source = log_record.source test_log.lineno = log_record.lineno
python
def _populate_basic_data(mfg_event, record): # TODO: # * Missing in proto: set run name from metadata. # * `part_tags` field on proto is unused # * `timings` field on proto is unused. # * Handle arbitrary units as uom_code/uom_suffix. # Populate non-repeated fields. mfg_event.dut_serial = record.dut_id mfg_event.start_time_ms = record.start_time_millis mfg_event.end_time_ms = record.end_time_millis mfg_event.tester_name = record.station_id mfg_event.test_name = record.metadata.get('test_name') or record.station_id mfg_event.test_status = test_runs_converter.OUTCOME_MAP[record.outcome] mfg_event.operator_name = record.metadata.get('operator_name', '') mfg_event.test_version = str(record.metadata.get('test_version', '')) mfg_event.test_description = record.metadata.get('test_description', '') # Populate part_tags. mfg_event.part_tags.extend(record.metadata.get('part_tags', [])) # Populate phases. for phase in record.phases: mfg_phase = mfg_event.phases.add() mfg_phase.name = phase.name mfg_phase.description = phase.codeinfo.sourcecode mfg_phase.timing.start_time_millis = phase.start_time_millis mfg_phase.timing.end_time_millis = phase.end_time_millis # Populate failure codes. for details in record.outcome_details: failure_code = mfg_event.failure_codes.add() failure_code.code = details.code failure_code.details = details.description # Populate test logs. for log_record in record.log_records: test_log = mfg_event.test_logs.add() test_log.timestamp_millis = log_record.timestamp_millis test_log.log_message = log_record.message test_log.logger_name = log_record.logger_name test_log.levelno = log_record.level if log_record.level <= logging.DEBUG: test_log.level = test_runs_pb2.TestRunLogMessage.DEBUG elif log_record.level <= logging.INFO: test_log.level = test_runs_pb2.TestRunLogMessage.INFO elif log_record.level <= logging.WARNING: test_log.level = test_runs_pb2.TestRunLogMessage.WARNING elif log_record.level <= logging.ERROR: test_log.level = test_runs_pb2.TestRunLogMessage.ERROR elif log_record.level <= logging.CRITICAL: test_log.level = test_runs_pb2.TestRunLogMessage.CRITICAL test_log.log_source = log_record.source test_log.lineno = log_record.lineno
[ "def", "_populate_basic_data", "(", "mfg_event", ",", "record", ")", ":", "# TODO:", "# * Missing in proto: set run name from metadata.", "# * `part_tags` field on proto is unused", "# * `timings` field on proto is unused.", "# * Handle arbitrary units as uom_code/uom_suffix.", "# ...
Copies data from the OpenHTF TestRecord to the MfgEvent proto.
[ "Copies", "data", "from", "the", "OpenHTF", "TestRecord", "to", "the", "MfgEvent", "proto", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L105-L159
240,747
google/openhtf
openhtf/output/proto/mfg_event_converter.py
_attach_record_as_json
def _attach_record_as_json(mfg_event, record): """Attach a copy of the record as JSON so we have an un-mangled copy.""" attachment = mfg_event.attachment.add() attachment.name = TEST_RECORD_ATTACHMENT_NAME test_record_dict = htf_data.convert_to_base_types(record) attachment.value_binary = _convert_object_to_json(test_record_dict) attachment.type = test_runs_pb2.TEXT_UTF8
python
def _attach_record_as_json(mfg_event, record): attachment = mfg_event.attachment.add() attachment.name = TEST_RECORD_ATTACHMENT_NAME test_record_dict = htf_data.convert_to_base_types(record) attachment.value_binary = _convert_object_to_json(test_record_dict) attachment.type = test_runs_pb2.TEXT_UTF8
[ "def", "_attach_record_as_json", "(", "mfg_event", ",", "record", ")", ":", "attachment", "=", "mfg_event", ".", "attachment", ".", "add", "(", ")", "attachment", ".", "name", "=", "TEST_RECORD_ATTACHMENT_NAME", "test_record_dict", "=", "htf_data", ".", "convert_t...
Attach a copy of the record as JSON so we have an un-mangled copy.
[ "Attach", "a", "copy", "of", "the", "record", "as", "JSON", "so", "we", "have", "an", "un", "-", "mangled", "copy", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L162-L168
240,748
google/openhtf
openhtf/output/proto/mfg_event_converter.py
_attach_config
def _attach_config(mfg_event, record): """Attaches the OpenHTF config file as JSON.""" if 'config' not in record.metadata: return attachment = mfg_event.attachment.add() attachment.name = 'config' attachment.value_binary = _convert_object_to_json(record.metadata['config']) attachment.type = test_runs_pb2.TEXT_UTF8
python
def _attach_config(mfg_event, record): if 'config' not in record.metadata: return attachment = mfg_event.attachment.add() attachment.name = 'config' attachment.value_binary = _convert_object_to_json(record.metadata['config']) attachment.type = test_runs_pb2.TEXT_UTF8
[ "def", "_attach_config", "(", "mfg_event", ",", "record", ")", ":", "if", "'config'", "not", "in", "record", ".", "metadata", ":", "return", "attachment", "=", "mfg_event", ".", "attachment", ".", "add", "(", ")", "attachment", ".", "name", "=", "'config'"...
Attaches the OpenHTF config file as JSON.
[ "Attaches", "the", "OpenHTF", "config", "file", "as", "JSON", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L186-L193
240,749
google/openhtf
openhtf/output/proto/mfg_event_converter.py
phase_uniquizer
def phase_uniquizer(all_phases): """Makes the names of phase measurement and attachments unique. This function will make the names of measurements and attachments unique. It modifies the input all_phases. Args: all_phases: the phases to make unique Returns: the phases now modified. """ measurement_name_maker = UniqueNameMaker( itertools.chain.from_iterable( phase.measurements.keys() for phase in all_phases if phase.measurements)) attachment_names = list(itertools.chain.from_iterable( phase.attachments.keys() for phase in all_phases)) attachment_names.extend(itertools.chain.from_iterable([ 'multidim_' + name for name, meas in phase.measurements.items() if meas.dimensions is not None ] for phase in all_phases if phase.measurements)) attachment_name_maker = UniqueNameMaker(attachment_names) for phase in all_phases: # Make measurements unique. for name, _ in sorted(phase.measurements.items()): old_name = name name = measurement_name_maker.make_unique(name) phase.measurements[old_name].name = name phase.measurements[name] = phase.measurements.pop(old_name) # Make attachments unique. for name, _ in sorted(phase.attachments.items()): old_name = name name = attachment_name_maker.make_unique(name) phase.attachments[old_name].name = name phase.attachments[name] = phase.attachments.pop(old_name) return all_phases
python
def phase_uniquizer(all_phases): measurement_name_maker = UniqueNameMaker( itertools.chain.from_iterable( phase.measurements.keys() for phase in all_phases if phase.measurements)) attachment_names = list(itertools.chain.from_iterable( phase.attachments.keys() for phase in all_phases)) attachment_names.extend(itertools.chain.from_iterable([ 'multidim_' + name for name, meas in phase.measurements.items() if meas.dimensions is not None ] for phase in all_phases if phase.measurements)) attachment_name_maker = UniqueNameMaker(attachment_names) for phase in all_phases: # Make measurements unique. for name, _ in sorted(phase.measurements.items()): old_name = name name = measurement_name_maker.make_unique(name) phase.measurements[old_name].name = name phase.measurements[name] = phase.measurements.pop(old_name) # Make attachments unique. for name, _ in sorted(phase.attachments.items()): old_name = name name = attachment_name_maker.make_unique(name) phase.attachments[old_name].name = name phase.attachments[name] = phase.attachments.pop(old_name) return all_phases
[ "def", "phase_uniquizer", "(", "all_phases", ")", ":", "measurement_name_maker", "=", "UniqueNameMaker", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "phase", ".", "measurements", ".", "keys", "(", ")", "for", "phase", "in", "all_phases", "if", "...
Makes the names of phase measurement and attachments unique. This function will make the names of measurements and attachments unique. It modifies the input all_phases. Args: all_phases: the phases to make unique Returns: the phases now modified.
[ "Makes", "the", "names", "of", "phase", "measurement", "and", "attachments", "unique", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L224-L261
240,750
google/openhtf
openhtf/output/proto/mfg_event_converter.py
multidim_measurement_to_attachment
def multidim_measurement_to_attachment(name, measurement): """Convert a multi-dim measurement to an `openhtf.test_record.Attachment`.""" dimensions = list(measurement.dimensions) if measurement.units: dimensions.append( measurements.Dimension.from_unit_descriptor(measurement.units)) dims = [] for d in dimensions: if d.suffix is None: suffix = u'' # Ensure that the suffix is unicode. It's typically str/bytes because # units.py looks them up against str/bytes. elif isinstance(d.suffix, unicode): suffix = d.suffix else: suffix = d.suffix.decode('utf8') dims.append({ 'uom_suffix': suffix, 'uom_code': d.code, 'name': d.name, }) # Refer to the module docstring for the expected schema. dimensioned_measured_value = measurement.measured_value value = (sorted(dimensioned_measured_value.value, key=lambda x: x[0]) if dimensioned_measured_value.is_value_set else None) outcome_str = MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[measurement.outcome] data = _convert_object_to_json({ 'outcome': outcome_str, 'name': name, 'dimensions': dims, 'value': value, }) attachment = htf_test_record.Attachment(data, test_runs_pb2.MULTIDIM_JSON) return attachment
python
def multidim_measurement_to_attachment(name, measurement): dimensions = list(measurement.dimensions) if measurement.units: dimensions.append( measurements.Dimension.from_unit_descriptor(measurement.units)) dims = [] for d in dimensions: if d.suffix is None: suffix = u'' # Ensure that the suffix is unicode. It's typically str/bytes because # units.py looks them up against str/bytes. elif isinstance(d.suffix, unicode): suffix = d.suffix else: suffix = d.suffix.decode('utf8') dims.append({ 'uom_suffix': suffix, 'uom_code': d.code, 'name': d.name, }) # Refer to the module docstring for the expected schema. dimensioned_measured_value = measurement.measured_value value = (sorted(dimensioned_measured_value.value, key=lambda x: x[0]) if dimensioned_measured_value.is_value_set else None) outcome_str = MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[measurement.outcome] data = _convert_object_to_json({ 'outcome': outcome_str, 'name': name, 'dimensions': dims, 'value': value, }) attachment = htf_test_record.Attachment(data, test_runs_pb2.MULTIDIM_JSON) return attachment
[ "def", "multidim_measurement_to_attachment", "(", "name", ",", "measurement", ")", ":", "dimensions", "=", "list", "(", "measurement", ".", "dimensions", ")", "if", "measurement", ".", "units", ":", "dimensions", ".", "append", "(", "measurements", ".", "Dimensi...
Convert a multi-dim measurement to an `openhtf.test_record.Attachment`.
[ "Convert", "a", "multi", "-", "dim", "measurement", "to", "an", "openhtf", ".", "test_record", ".", "Attachment", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L264-L300
240,751
google/openhtf
openhtf/output/proto/mfg_event_converter.py
convert_multidim_measurements
def convert_multidim_measurements(all_phases): """Converts each multidim measurements into attachments for all phases..""" # Combine actual attachments with attachments we make from multi-dim # measurements. attachment_names = list(itertools.chain.from_iterable( phase.attachments.keys() for phase in all_phases)) attachment_names.extend(itertools.chain.from_iterable([ 'multidim_' + name for name, meas in phase.measurements.items() if meas.dimensions is not None ] for phase in all_phases if phase.measurements)) attachment_name_maker = UniqueNameMaker(attachment_names) for phase in all_phases: # Process multi-dim measurements into unique attachments. for name, measurement in sorted(phase.measurements.items()): if measurement.dimensions: old_name = name name = attachment_name_maker.make_unique('multidim_%s' % name) attachment = multidim_measurement_to_attachment(name, measurement) phase.attachments[name] = attachment phase.measurements.pop(old_name) return all_phases
python
def convert_multidim_measurements(all_phases): # Combine actual attachments with attachments we make from multi-dim # measurements. attachment_names = list(itertools.chain.from_iterable( phase.attachments.keys() for phase in all_phases)) attachment_names.extend(itertools.chain.from_iterable([ 'multidim_' + name for name, meas in phase.measurements.items() if meas.dimensions is not None ] for phase in all_phases if phase.measurements)) attachment_name_maker = UniqueNameMaker(attachment_names) for phase in all_phases: # Process multi-dim measurements into unique attachments. for name, measurement in sorted(phase.measurements.items()): if measurement.dimensions: old_name = name name = attachment_name_maker.make_unique('multidim_%s' % name) attachment = multidim_measurement_to_attachment(name, measurement) phase.attachments[name] = attachment phase.measurements.pop(old_name) return all_phases
[ "def", "convert_multidim_measurements", "(", "all_phases", ")", ":", "# Combine actual attachments with attachments we make from multi-dim", "# measurements.", "attachment_names", "=", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "phase", ".", "attachmen...
Converts each multidim measurements into attachments for all phases..
[ "Converts", "each", "multidim", "measurements", "into", "attachments", "for", "all", "phases", ".." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L303-L324
240,752
google/openhtf
openhtf/output/proto/mfg_event_converter.py
attachment_to_multidim_measurement
def attachment_to_multidim_measurement(attachment, name=None): """Convert an OpenHTF test record attachment to a multi-dim measurement. This is a best effort attempt to reverse, as some data is lost in converting from a multidim to an attachment. Args: attachment: an `openhtf.test_record.Attachment` from a multi-dim. name: an optional name for the measurement. If not provided will use the name included in the attachment. Returns: An multi-dim `openhtf.Measurement`. """ data = json.loads(attachment.data) name = name or data.get('name') # attachment_dimn are a list of dicts with keys 'uom_suffix' and 'uom_code' attachment_dims = data.get('dimensions', []) # attachment_value is a list of lists [[t1, x1, y1, f1], [t2, x2, y2, f2]] attachment_values = data.get('value') attachment_outcome_str = data.get('outcome') if attachment_outcome_str not in TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME: # Fpr backward compatibility with saved data we'll convert integers to str try: attachment_outcome_str = test_runs_pb2.Status.Name( int(attachment_outcome_str)) except ValueError: attachment_outcome_str = None # Convert test status outcome str to measurement outcome outcome = TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME.get( attachment_outcome_str) # convert dimensions into htf.Dimensions _lazy_load_units_by_code() dims = [] for d in attachment_dims: # Try to convert into htf.Dimension including backwards compatibility. unit = UNITS_BY_CODE.get(d.get('uom_code'), units.NONE) description = d.get('name', '') dims.append(measurements.Dimension(description=description, unit=unit)) # Attempt to determine if units are included. if attachment_values and len(dims) == len(attachment_values[0]): # units provided units_ = dims[-1].unit dimensions = dims[:-1] else: units_ = None dimensions = dims # created dimensioned_measured_value and populate with values. measured_value = measurements.DimensionedMeasuredValue( name=name, num_dimensions=len(dimensions) ) for row in attachment_values: coordinates = tuple(row[:-1]) val = row[-1] measured_value[coordinates] = val measurement = measurements.Measurement( name=name, units=units_, dimensions=tuple(dimensions), measured_value=measured_value, outcome=outcome ) return measurement
python
def attachment_to_multidim_measurement(attachment, name=None): data = json.loads(attachment.data) name = name or data.get('name') # attachment_dimn are a list of dicts with keys 'uom_suffix' and 'uom_code' attachment_dims = data.get('dimensions', []) # attachment_value is a list of lists [[t1, x1, y1, f1], [t2, x2, y2, f2]] attachment_values = data.get('value') attachment_outcome_str = data.get('outcome') if attachment_outcome_str not in TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME: # Fpr backward compatibility with saved data we'll convert integers to str try: attachment_outcome_str = test_runs_pb2.Status.Name( int(attachment_outcome_str)) except ValueError: attachment_outcome_str = None # Convert test status outcome str to measurement outcome outcome = TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME.get( attachment_outcome_str) # convert dimensions into htf.Dimensions _lazy_load_units_by_code() dims = [] for d in attachment_dims: # Try to convert into htf.Dimension including backwards compatibility. unit = UNITS_BY_CODE.get(d.get('uom_code'), units.NONE) description = d.get('name', '') dims.append(measurements.Dimension(description=description, unit=unit)) # Attempt to determine if units are included. if attachment_values and len(dims) == len(attachment_values[0]): # units provided units_ = dims[-1].unit dimensions = dims[:-1] else: units_ = None dimensions = dims # created dimensioned_measured_value and populate with values. measured_value = measurements.DimensionedMeasuredValue( name=name, num_dimensions=len(dimensions) ) for row in attachment_values: coordinates = tuple(row[:-1]) val = row[-1] measured_value[coordinates] = val measurement = measurements.Measurement( name=name, units=units_, dimensions=tuple(dimensions), measured_value=measured_value, outcome=outcome ) return measurement
[ "def", "attachment_to_multidim_measurement", "(", "attachment", ",", "name", "=", "None", ")", ":", "data", "=", "json", ".", "loads", "(", "attachment", ".", "data", ")", "name", "=", "name", "or", "data", ".", "get", "(", "'name'", ")", "# attachment_dim...
Convert an OpenHTF test record attachment to a multi-dim measurement. This is a best effort attempt to reverse, as some data is lost in converting from a multidim to an attachment. Args: attachment: an `openhtf.test_record.Attachment` from a multi-dim. name: an optional name for the measurement. If not provided will use the name included in the attachment. Returns: An multi-dim `openhtf.Measurement`.
[ "Convert", "an", "OpenHTF", "test", "record", "attachment", "to", "a", "multi", "-", "dim", "measurement", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L427-L497
240,753
google/openhtf
openhtf/output/proto/mfg_event_converter.py
PhaseCopier._copy_unidimensional_measurement
def _copy_unidimensional_measurement( self, phase, name, measurement, mfg_event): """Copy uni-dimensional measurements to the MfgEvent.""" mfg_measurement = mfg_event.measurement.add() # Copy basic measurement fields. mfg_measurement.name = name if measurement.docstring: mfg_measurement.description = measurement.docstring mfg_measurement.parameter_tag.append(phase.name) if (measurement.units and measurement.units.code in test_runs_converter.UOM_CODE_MAP): mfg_measurement.unit_code = ( test_runs_converter.UOM_CODE_MAP[measurement.units.code]) # Copy failed measurements as failure_codes. This happens early to include # unset measurements. if (measurement.outcome != measurements.Outcome.PASS and phase.outcome != htf_test_record.PhaseOutcome.SKIP): failure_code = mfg_event.failure_codes.add() failure_code.code = name failure_code.details = '\n'.join(str(v) for v in measurement.validators) # Copy measurement value. measured_value = measurement.measured_value status_str = MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[ measurement.outcome] mfg_measurement.status = test_runs_pb2.Status.Value(status_str) if not measured_value.is_value_set: return value = measured_value.value if isinstance(value, numbers.Number): mfg_measurement.numeric_value = float(value) elif isinstance(value, bytes): # text_value expects unicode or ascii-compatible strings, so we must # 'decode' it, even if it's actually just garbage bytestring data. mfg_measurement.text_value = unicode(value, errors='replace') elif isinstance(value, unicode): # Don't waste time and potential errors decoding unicode. mfg_measurement.text_value = value else: # Coercing to string. mfg_measurement.text_value = str(value) # Copy measurement validators. for validator in measurement.validators: if isinstance(validator, validators.RangeValidatorBase): if validator.minimum is not None: mfg_measurement.numeric_minimum = float(validator.minimum) if validator.maximum is not None: mfg_measurement.numeric_maximum = float(validator.maximum) elif isinstance(validator, validators.RegexMatcher): mfg_measurement.expected_text = validator.regex else: mfg_measurement.description += '\nValidator: ' + str(validator)
python
def _copy_unidimensional_measurement( self, phase, name, measurement, mfg_event): mfg_measurement = mfg_event.measurement.add() # Copy basic measurement fields. mfg_measurement.name = name if measurement.docstring: mfg_measurement.description = measurement.docstring mfg_measurement.parameter_tag.append(phase.name) if (measurement.units and measurement.units.code in test_runs_converter.UOM_CODE_MAP): mfg_measurement.unit_code = ( test_runs_converter.UOM_CODE_MAP[measurement.units.code]) # Copy failed measurements as failure_codes. This happens early to include # unset measurements. if (measurement.outcome != measurements.Outcome.PASS and phase.outcome != htf_test_record.PhaseOutcome.SKIP): failure_code = mfg_event.failure_codes.add() failure_code.code = name failure_code.details = '\n'.join(str(v) for v in measurement.validators) # Copy measurement value. measured_value = measurement.measured_value status_str = MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[ measurement.outcome] mfg_measurement.status = test_runs_pb2.Status.Value(status_str) if not measured_value.is_value_set: return value = measured_value.value if isinstance(value, numbers.Number): mfg_measurement.numeric_value = float(value) elif isinstance(value, bytes): # text_value expects unicode or ascii-compatible strings, so we must # 'decode' it, even if it's actually just garbage bytestring data. mfg_measurement.text_value = unicode(value, errors='replace') elif isinstance(value, unicode): # Don't waste time and potential errors decoding unicode. mfg_measurement.text_value = value else: # Coercing to string. mfg_measurement.text_value = str(value) # Copy measurement validators. for validator in measurement.validators: if isinstance(validator, validators.RangeValidatorBase): if validator.minimum is not None: mfg_measurement.numeric_minimum = float(validator.minimum) if validator.maximum is not None: mfg_measurement.numeric_maximum = float(validator.maximum) elif isinstance(validator, validators.RegexMatcher): mfg_measurement.expected_text = validator.regex else: mfg_measurement.description += '\nValidator: ' + str(validator)
[ "def", "_copy_unidimensional_measurement", "(", "self", ",", "phase", ",", "name", ",", "measurement", ",", "mfg_event", ")", ":", "mfg_measurement", "=", "mfg_event", ".", "measurement", ".", "add", "(", ")", "# Copy basic measurement fields.", "mfg_measurement", "...
Copy uni-dimensional measurements to the MfgEvent.
[ "Copy", "uni", "-", "dimensional", "measurements", "to", "the", "MfgEvent", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L341-L396
240,754
google/openhtf
openhtf/output/proto/mfg_event_converter.py
PhaseCopier._copy_attachment
def _copy_attachment(self, name, data, mimetype, mfg_event): """Copies an attachment to mfg_event.""" attachment = mfg_event.attachment.add() attachment.name = name if isinstance(data, unicode): data = data.encode('utf8') attachment.value_binary = data if mimetype in test_runs_converter.MIMETYPE_MAP: attachment.type = test_runs_converter.MIMETYPE_MAP[mimetype] elif mimetype == test_runs_pb2.MULTIDIM_JSON: attachment.type = mimetype else: attachment.type = test_runs_pb2.BINARY
python
def _copy_attachment(self, name, data, mimetype, mfg_event): attachment = mfg_event.attachment.add() attachment.name = name if isinstance(data, unicode): data = data.encode('utf8') attachment.value_binary = data if mimetype in test_runs_converter.MIMETYPE_MAP: attachment.type = test_runs_converter.MIMETYPE_MAP[mimetype] elif mimetype == test_runs_pb2.MULTIDIM_JSON: attachment.type = mimetype else: attachment.type = test_runs_pb2.BINARY
[ "def", "_copy_attachment", "(", "self", ",", "name", ",", "data", ",", "mimetype", ",", "mfg_event", ")", ":", "attachment", "=", "mfg_event", ".", "attachment", ".", "add", "(", ")", "attachment", ".", "name", "=", "name", "if", "isinstance", "(", "data...
Copies an attachment to mfg_event.
[ "Copies", "an", "attachment", "to", "mfg_event", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/proto/mfg_event_converter.py#L403-L415
240,755
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStream.write
def write(self, data, timeout_ms=None): """Write data to this stream. Args: data: Data to write. timeout_ms: Timeout to use for the write/Ack transaction, in milliseconds (or as a PolledTimeout object). Raises: AdbProtocolError: If an ACK is not received. AdbStreamClosedError: If the stream is already closed, or gets closed before the write completes. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) # Break the data up into our transport's maxdata sized WRTE messages. while data: self._transport.write( data[:self._transport.adb_connection.maxdata], timeout) data = data[self._transport.adb_connection.maxdata:]
python
def write(self, data, timeout_ms=None): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) # Break the data up into our transport's maxdata sized WRTE messages. while data: self._transport.write( data[:self._transport.adb_connection.maxdata], timeout) data = data[self._transport.adb_connection.maxdata:]
[ "def", "write", "(", "self", ",", "data", ",", "timeout_ms", "=", "None", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", "# Break the data up into our transport's maxdata sized WRTE messages.", "while", "data", ...
Write data to this stream. Args: data: Data to write. timeout_ms: Timeout to use for the write/Ack transaction, in milliseconds (or as a PolledTimeout object). Raises: AdbProtocolError: If an ACK is not received. AdbStreamClosedError: If the stream is already closed, or gets closed before the write completes.
[ "Write", "data", "to", "this", "stream", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L167-L185
240,756
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStream.read
def read(self, length=0, timeout_ms=None): """Reads data from the remote end of this stream. Internally, this data will have been contained in AdbMessages, but users of streams shouldn't need to care about the transport mechanism. Args: length: If provided, the number of bytes to read, otherwise all available data will be returned (at least one byte). timeout_ms: Time to wait for a message to come in for this stream, in milliseconds (or as a PolledTimeout object). Returns: Data that was read, or None if the end of the stream was reached. Raises: AdbProtocolError: Received an unexpected wonky non-stream packet (like a CNXN ADB message). AdbStreamClosedError: The stream is already closed. AdbTimeoutError: Timed out waiting for a message. """ return self._transport.read( length, timeouts.PolledTimeout.from_millis(timeout_ms))
python
def read(self, length=0, timeout_ms=None): return self._transport.read( length, timeouts.PolledTimeout.from_millis(timeout_ms))
[ "def", "read", "(", "self", ",", "length", "=", "0", ",", "timeout_ms", "=", "None", ")", ":", "return", "self", ".", "_transport", ".", "read", "(", "length", ",", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", ")" ]
Reads data from the remote end of this stream. Internally, this data will have been contained in AdbMessages, but users of streams shouldn't need to care about the transport mechanism. Args: length: If provided, the number of bytes to read, otherwise all available data will be returned (at least one byte). timeout_ms: Time to wait for a message to come in for this stream, in milliseconds (or as a PolledTimeout object). Returns: Data that was read, or None if the end of the stream was reached. Raises: AdbProtocolError: Received an unexpected wonky non-stream packet (like a CNXN ADB message). AdbStreamClosedError: The stream is already closed. AdbTimeoutError: Timed out waiting for a message.
[ "Reads", "data", "from", "the", "remote", "end", "of", "this", "stream", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L187-L209
240,757
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStream.read_until_close
def read_until_close(self, timeout_ms=None): """Yield data until this stream is closed. Args: timeout_ms: Timeout in milliseconds to keep reading (or a PolledTimeout object). Yields: Data read from a single call to self.read(), until the stream is closed or timeout is reached. Raises: AdbTimeoutError: On timeout. """ while True: try: yield self.read(timeout_ms=timeout_ms) except usb_exceptions.AdbStreamClosedError: break
python
def read_until_close(self, timeout_ms=None): while True: try: yield self.read(timeout_ms=timeout_ms) except usb_exceptions.AdbStreamClosedError: break
[ "def", "read_until_close", "(", "self", ",", "timeout_ms", "=", "None", ")", ":", "while", "True", ":", "try", ":", "yield", "self", ".", "read", "(", "timeout_ms", "=", "timeout_ms", ")", "except", "usb_exceptions", ".", "AdbStreamClosedError", ":", "break"...
Yield data until this stream is closed. Args: timeout_ms: Timeout in milliseconds to keep reading (or a PolledTimeout object). Yields: Data read from a single call to self.read(), until the stream is closed or timeout is reached. Raises: AdbTimeoutError: On timeout.
[ "Yield", "data", "until", "this", "stream", "is", "closed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L211-L229
240,758
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport._set_or_check_remote_id
def _set_or_check_remote_id(self, remote_id): """Set or check the remote id.""" if not self.remote_id: assert self.closed_state == self.ClosedState.PENDING, 'Bad ClosedState!' self.remote_id = remote_id self.closed_state = self.ClosedState.OPEN elif self.remote_id != remote_id: raise usb_exceptions.AdbProtocolError( '%s remote-id change to %s', self, remote_id)
python
def _set_or_check_remote_id(self, remote_id): if not self.remote_id: assert self.closed_state == self.ClosedState.PENDING, 'Bad ClosedState!' self.remote_id = remote_id self.closed_state = self.ClosedState.OPEN elif self.remote_id != remote_id: raise usb_exceptions.AdbProtocolError( '%s remote-id change to %s', self, remote_id)
[ "def", "_set_or_check_remote_id", "(", "self", ",", "remote_id", ")", ":", "if", "not", "self", ".", "remote_id", ":", "assert", "self", ".", "closed_state", "==", "self", ".", "ClosedState", ".", "PENDING", ",", "'Bad ClosedState!'", "self", ".", "remote_id",...
Set or check the remote id.
[ "Set", "or", "check", "the", "remote", "id", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L277-L285
240,759
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport._handle_message
def _handle_message(self, message, handle_wrte=True): """Handle a message that was read for this stream. For each message type, this means: OKAY: Check id's and make sure we are expecting an OKAY. Clear the self._expecting_okay flag so any pending write()'s know. CLSE: Set our internal state to closed. WRTE: Add the data read to our internal read buffer. Note we don't return the actual data because it may not be this thread that needs it. Args: message: Message that was read. handle_wrte: If True, we can handle WRTE messages, otherwise raise. Raises: AdbProtocolError: If we get a WRTE message but handle_wrte is False. """ if message.command == 'OKAY': self._set_or_check_remote_id(message.arg0) if not self._expecting_okay: raise usb_exceptions.AdbProtocolError( '%s received unexpected OKAY: %s', self, message) self._expecting_okay = False elif message.command == 'CLSE': self.closed_state = self.ClosedState.CLOSED elif not handle_wrte: raise usb_exceptions.AdbProtocolError( '%s received WRTE before OKAY/CLSE: %s', self, message) else: with self._read_buffer_lock: self._read_buffer.append(message.data) self._buffer_size += len(message.data)
python
def _handle_message(self, message, handle_wrte=True): if message.command == 'OKAY': self._set_or_check_remote_id(message.arg0) if not self._expecting_okay: raise usb_exceptions.AdbProtocolError( '%s received unexpected OKAY: %s', self, message) self._expecting_okay = False elif message.command == 'CLSE': self.closed_state = self.ClosedState.CLOSED elif not handle_wrte: raise usb_exceptions.AdbProtocolError( '%s received WRTE before OKAY/CLSE: %s', self, message) else: with self._read_buffer_lock: self._read_buffer.append(message.data) self._buffer_size += len(message.data)
[ "def", "_handle_message", "(", "self", ",", "message", ",", "handle_wrte", "=", "True", ")", ":", "if", "message", ".", "command", "==", "'OKAY'", ":", "self", ".", "_set_or_check_remote_id", "(", "message", ".", "arg0", ")", "if", "not", "self", ".", "_...
Handle a message that was read for this stream. For each message type, this means: OKAY: Check id's and make sure we are expecting an OKAY. Clear the self._expecting_okay flag so any pending write()'s know. CLSE: Set our internal state to closed. WRTE: Add the data read to our internal read buffer. Note we don't return the actual data because it may not be this thread that needs it. Args: message: Message that was read. handle_wrte: If True, we can handle WRTE messages, otherwise raise. Raises: AdbProtocolError: If we get a WRTE message but handle_wrte is False.
[ "Handle", "a", "message", "that", "was", "read", "for", "this", "stream", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L314-L345
240,760
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport._read_messages_until_true
def _read_messages_until_true(self, predicate, timeout): """Read a message from this stream and handle it. This method tries to read a message from this stream, blocking until a message is read. Once read, it will handle it accordingly by calling self._handle_message(). This is repeated as long as predicate() returns False. There is some locking used internally here so that we don't end up with multiple threads blocked on a call to read_for_stream when another thread has read the message that caused predicate() to become True. Args: predicate: Callable, keep reading messages until it returns true. Note that predicate() should not block, as doing so may cause this method to hang beyond its timeout. timeout: Timeout to use for this call. Raises: AdbStreamClosedError: If this stream is already closed. """ while not predicate(): # Hold the message_received Lock while we try to acquire the reader_lock # and waiting on the message_received condition, to prevent another reader # thread from notifying the condition between us failing to acquire the # reader_lock and waiting on the condition. self._message_received.acquire() if self._reader_lock.acquire(False): try: # Release the message_received Lock while we do the read so other # threads can wait() on the condition without having to block on # acquiring the message_received Lock (we may have a longer timeout # than them, so that would be bad). self._message_received.release() # We are now the thread responsible for reading a message. Check # predicate() to make sure nobody else read a message between our last # check and acquiring the reader Lock. if predicate(): return # Read and handle a message, using our timeout. self._handle_message( self.adb_connection.read_for_stream(self, timeout)) # Notify anyone interested that we handled a message, causing them to # check their predicate again. with self._message_received: self._message_received.notify_all() finally: self._reader_lock.release() else: # There is some other thread reading a message. Since we are already # holding the message_received Lock, we can immediately do the wait. try: self._message_received.wait(timeout.remaining) if timeout.has_expired(): raise usb_exceptions.AdbTimeoutError( '%s timed out reading messages.', self) finally: # Make sure we release this even if an exception occurred. self._message_received.release()
python
def _read_messages_until_true(self, predicate, timeout): while not predicate(): # Hold the message_received Lock while we try to acquire the reader_lock # and waiting on the message_received condition, to prevent another reader # thread from notifying the condition between us failing to acquire the # reader_lock and waiting on the condition. self._message_received.acquire() if self._reader_lock.acquire(False): try: # Release the message_received Lock while we do the read so other # threads can wait() on the condition without having to block on # acquiring the message_received Lock (we may have a longer timeout # than them, so that would be bad). self._message_received.release() # We are now the thread responsible for reading a message. Check # predicate() to make sure nobody else read a message between our last # check and acquiring the reader Lock. if predicate(): return # Read and handle a message, using our timeout. self._handle_message( self.adb_connection.read_for_stream(self, timeout)) # Notify anyone interested that we handled a message, causing them to # check their predicate again. with self._message_received: self._message_received.notify_all() finally: self._reader_lock.release() else: # There is some other thread reading a message. Since we are already # holding the message_received Lock, we can immediately do the wait. try: self._message_received.wait(timeout.remaining) if timeout.has_expired(): raise usb_exceptions.AdbTimeoutError( '%s timed out reading messages.', self) finally: # Make sure we release this even if an exception occurred. self._message_received.release()
[ "def", "_read_messages_until_true", "(", "self", ",", "predicate", ",", "timeout", ")", ":", "while", "not", "predicate", "(", ")", ":", "# Hold the message_received Lock while we try to acquire the reader_lock", "# and waiting on the message_received condition, to prevent another ...
Read a message from this stream and handle it. This method tries to read a message from this stream, blocking until a message is read. Once read, it will handle it accordingly by calling self._handle_message(). This is repeated as long as predicate() returns False. There is some locking used internally here so that we don't end up with multiple threads blocked on a call to read_for_stream when another thread has read the message that caused predicate() to become True. Args: predicate: Callable, keep reading messages until it returns true. Note that predicate() should not block, as doing so may cause this method to hang beyond its timeout. timeout: Timeout to use for this call. Raises: AdbStreamClosedError: If this stream is already closed.
[ "Read", "a", "message", "from", "this", "stream", "and", "handle", "it", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L347-L408
240,761
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport.ensure_opened
def ensure_opened(self, timeout): """Ensure this stream transport was successfully opened. Checks to make sure we receive our initial OKAY message. This must be called after creating this AdbStreamTransport and before calling read() or write(). Args: timeout: timeouts.PolledTimeout to use for this operation. Returns: True if this stream was successfully opened, False if the service was not recognized by the remote endpoint. If False is returned, then this AdbStreamTransport will be already closed. Raises: AdbProtocolError: If we receive a WRTE message instead of OKAY/CLSE. """ self._handle_message(self.adb_connection.read_for_stream(self, timeout), handle_wrte=False) return self.is_open()
python
def ensure_opened(self, timeout): self._handle_message(self.adb_connection.read_for_stream(self, timeout), handle_wrte=False) return self.is_open()
[ "def", "ensure_opened", "(", "self", ",", "timeout", ")", ":", "self", ".", "_handle_message", "(", "self", ".", "adb_connection", ".", "read_for_stream", "(", "self", ",", "timeout", ")", ",", "handle_wrte", "=", "False", ")", "return", "self", ".", "is_o...
Ensure this stream transport was successfully opened. Checks to make sure we receive our initial OKAY message. This must be called after creating this AdbStreamTransport and before calling read() or write(). Args: timeout: timeouts.PolledTimeout to use for this operation. Returns: True if this stream was successfully opened, False if the service was not recognized by the remote endpoint. If False is returned, then this AdbStreamTransport will be already closed. Raises: AdbProtocolError: If we receive a WRTE message instead of OKAY/CLSE.
[ "Ensure", "this", "stream", "transport", "was", "successfully", "opened", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L410-L430
240,762
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport.enqueue_message
def enqueue_message(self, message, timeout): """Add the given message to this transport's queue. This method also handles ACKing any WRTE messages. Args: message: The AdbMessage to enqueue. timeout: The timeout to use for the operation. Specifically, WRTE messages cause an OKAY to be sent; timeout is used for that send. """ # Ack WRTE messages immediately, handle our OPEN ack if it gets enqueued. if message.command == 'WRTE': self._send_command('OKAY', timeout=timeout) elif message.command == 'OKAY': self._set_or_check_remote_id(message.arg0) self.message_queue.put(message)
python
def enqueue_message(self, message, timeout): # Ack WRTE messages immediately, handle our OPEN ack if it gets enqueued. if message.command == 'WRTE': self._send_command('OKAY', timeout=timeout) elif message.command == 'OKAY': self._set_or_check_remote_id(message.arg0) self.message_queue.put(message)
[ "def", "enqueue_message", "(", "self", ",", "message", ",", "timeout", ")", ":", "# Ack WRTE messages immediately, handle our OPEN ack if it gets enqueued.", "if", "message", ".", "command", "==", "'WRTE'", ":", "self", ".", "_send_command", "(", "'OKAY'", ",", "timeo...
Add the given message to this transport's queue. This method also handles ACKing any WRTE messages. Args: message: The AdbMessage to enqueue. timeout: The timeout to use for the operation. Specifically, WRTE messages cause an OKAY to be sent; timeout is used for that send.
[ "Add", "the", "given", "message", "to", "this", "transport", "s", "queue", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L440-L455
240,763
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport.write
def write(self, data, timeout): """Write data to this stream, using the given timeouts.PolledTimeout.""" if not self.remote_id: raise usb_exceptions.AdbStreamClosedError( 'Cannot write() to half-opened %s', self) if self.closed_state != self.ClosedState.OPEN: raise usb_exceptions.AdbStreamClosedError( 'Cannot write() to closed %s', self) elif self._expecting_okay: raise usb_exceptions.AdbProtocolError( 'Previous WRTE failed, %s in unknown state', self) # Make sure we only have one WRTE in flight at a time, because ADB doesn't # identify which WRTE it is ACK'ing when it sends the OKAY message back. with self._write_lock: self._expecting_okay = True self._send_command('WRTE', timeout, data) self._read_messages_until_true(lambda: not self._expecting_okay, timeout)
python
def write(self, data, timeout): if not self.remote_id: raise usb_exceptions.AdbStreamClosedError( 'Cannot write() to half-opened %s', self) if self.closed_state != self.ClosedState.OPEN: raise usb_exceptions.AdbStreamClosedError( 'Cannot write() to closed %s', self) elif self._expecting_okay: raise usb_exceptions.AdbProtocolError( 'Previous WRTE failed, %s in unknown state', self) # Make sure we only have one WRTE in flight at a time, because ADB doesn't # identify which WRTE it is ACK'ing when it sends the OKAY message back. with self._write_lock: self._expecting_okay = True self._send_command('WRTE', timeout, data) self._read_messages_until_true(lambda: not self._expecting_okay, timeout)
[ "def", "write", "(", "self", ",", "data", ",", "timeout", ")", ":", "if", "not", "self", ".", "remote_id", ":", "raise", "usb_exceptions", ".", "AdbStreamClosedError", "(", "'Cannot write() to half-opened %s'", ",", "self", ")", "if", "self", ".", "closed_stat...
Write data to this stream, using the given timeouts.PolledTimeout.
[ "Write", "data", "to", "this", "stream", "using", "the", "given", "timeouts", ".", "PolledTimeout", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L457-L474
240,764
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbStreamTransport.read
def read(self, length, timeout): """Read 'length' bytes from this stream transport. Args: length: If not 0, read this many bytes from the stream, otherwise read all available data (at least one byte). timeout: timeouts.PolledTimeout to use for this read operation. Returns: The bytes read from this stream. """ self._read_messages_until_true( lambda: self._buffer_size and self._buffer_size >= length, timeout) with self._read_buffer_lock: data, push_back = ''.join(self._read_buffer), '' if length: data, push_back = data[:length], data[length:] self._read_buffer.clear() self._buffer_size = len(push_back) if push_back: self._read_buffer.appendleft(push_back) return data
python
def read(self, length, timeout): self._read_messages_until_true( lambda: self._buffer_size and self._buffer_size >= length, timeout) with self._read_buffer_lock: data, push_back = ''.join(self._read_buffer), '' if length: data, push_back = data[:length], data[length:] self._read_buffer.clear() self._buffer_size = len(push_back) if push_back: self._read_buffer.appendleft(push_back) return data
[ "def", "read", "(", "self", ",", "length", ",", "timeout", ")", ":", "self", ".", "_read_messages_until_true", "(", "lambda", ":", "self", ".", "_buffer_size", "and", "self", ".", "_buffer_size", ">=", "length", ",", "timeout", ")", "with", "self", ".", ...
Read 'length' bytes from this stream transport. Args: length: If not 0, read this many bytes from the stream, otherwise read all available data (at least one byte). timeout: timeouts.PolledTimeout to use for this read operation. Returns: The bytes read from this stream.
[ "Read", "length", "bytes", "from", "this", "stream", "transport", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L476-L498
240,765
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection._make_stream_transport
def _make_stream_transport(self): """Create an AdbStreamTransport with a newly allocated local_id.""" msg_queue = queue.Queue() with self._stream_transport_map_lock: # Start one past the last id we used, and grab the first available one. # This mimics the ADB behavior of 'increment an unsigned and let it # overflow', but with a check to ensure we don't reuse an id in use, # even though that's unlikely with 2^32 - 1 of them available. We try # at most 64 id's, if we've wrapped around and there isn't one available # in the first 64, there's a problem, better to fail fast than hang for # a potentially very long time (STREAM_ID_LIMIT can be very large). self._last_id_used = (self._last_id_used % STREAM_ID_LIMIT) + 1 for local_id in itertools.islice( itertools.chain( range(self._last_id_used, STREAM_ID_LIMIT), range(1, self._last_id_used)), 64): if local_id not in list(self._stream_transport_map.keys()): self._last_id_used = local_id break else: raise usb_exceptions.AdbStreamUnavailableError('Ran out of local ids!') # Ignore this warning - the for loop will always have at least one # iteration, so local_id will always be set. # pylint: disable=undefined-loop-variable stream_transport = AdbStreamTransport(self, local_id, msg_queue) self._stream_transport_map[local_id] = stream_transport return stream_transport
python
def _make_stream_transport(self): msg_queue = queue.Queue() with self._stream_transport_map_lock: # Start one past the last id we used, and grab the first available one. # This mimics the ADB behavior of 'increment an unsigned and let it # overflow', but with a check to ensure we don't reuse an id in use, # even though that's unlikely with 2^32 - 1 of them available. We try # at most 64 id's, if we've wrapped around and there isn't one available # in the first 64, there's a problem, better to fail fast than hang for # a potentially very long time (STREAM_ID_LIMIT can be very large). self._last_id_used = (self._last_id_used % STREAM_ID_LIMIT) + 1 for local_id in itertools.islice( itertools.chain( range(self._last_id_used, STREAM_ID_LIMIT), range(1, self._last_id_used)), 64): if local_id not in list(self._stream_transport_map.keys()): self._last_id_used = local_id break else: raise usb_exceptions.AdbStreamUnavailableError('Ran out of local ids!') # Ignore this warning - the for loop will always have at least one # iteration, so local_id will always be set. # pylint: disable=undefined-loop-variable stream_transport = AdbStreamTransport(self, local_id, msg_queue) self._stream_transport_map[local_id] = stream_transport return stream_transport
[ "def", "_make_stream_transport", "(", "self", ")", ":", "msg_queue", "=", "queue", ".", "Queue", "(", ")", "with", "self", ".", "_stream_transport_map_lock", ":", "# Start one past the last id we used, and grab the first available one.", "# This mimics the ADB behavior of 'incr...
Create an AdbStreamTransport with a newly allocated local_id.
[ "Create", "an", "AdbStreamTransport", "with", "a", "newly", "allocated", "local_id", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L568-L594
240,766
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection._handle_message_for_stream
def _handle_message_for_stream(self, stream_transport, message, timeout): """Handle an incoming message, check if it's for the given stream. If the message is not for the stream, then add it to the appropriate message queue. Args: stream_transport: AdbStreamTransport currently waiting on a message. message: Message to check and handle. timeout: Timeout to use for the operation, should be an instance of timeouts.PolledTimeout. Returns: The message read if it was for this stream, None otherwise. Raises: AdbProtocolError: If we receive an unexpected message type. """ if message.command not in ('OKAY', 'CLSE', 'WRTE'): raise usb_exceptions.AdbProtocolError( '%s received unexpected message: %s', self, message) if message.arg1 == stream_transport.local_id: # Ack writes immediately. if message.command == 'WRTE': # Make sure we don't get a WRTE before an OKAY/CLSE message. if not stream_transport.remote_id: raise usb_exceptions.AdbProtocolError( '%s received WRTE before OKAY/CLSE: %s', stream_transport, message) self.transport.write_message(adb_message.AdbMessage( 'OKAY', stream_transport.local_id, stream_transport.remote_id), timeout) elif message.command == 'CLSE': self.close_stream_transport(stream_transport, timeout) return message else: # Message was not for this stream, add it to the right stream's queue. with self._stream_transport_map_lock: dest_transport = self._stream_transport_map.get(message.arg1) if dest_transport: if message.command == 'CLSE': self.close_stream_transport(dest_transport, timeout) dest_transport.enqueue_message(message, timeout) else: _LOG.warning('Received message for unknown local-id: %s', message)
python
def _handle_message_for_stream(self, stream_transport, message, timeout): if message.command not in ('OKAY', 'CLSE', 'WRTE'): raise usb_exceptions.AdbProtocolError( '%s received unexpected message: %s', self, message) if message.arg1 == stream_transport.local_id: # Ack writes immediately. if message.command == 'WRTE': # Make sure we don't get a WRTE before an OKAY/CLSE message. if not stream_transport.remote_id: raise usb_exceptions.AdbProtocolError( '%s received WRTE before OKAY/CLSE: %s', stream_transport, message) self.transport.write_message(adb_message.AdbMessage( 'OKAY', stream_transport.local_id, stream_transport.remote_id), timeout) elif message.command == 'CLSE': self.close_stream_transport(stream_transport, timeout) return message else: # Message was not for this stream, add it to the right stream's queue. with self._stream_transport_map_lock: dest_transport = self._stream_transport_map.get(message.arg1) if dest_transport: if message.command == 'CLSE': self.close_stream_transport(dest_transport, timeout) dest_transport.enqueue_message(message, timeout) else: _LOG.warning('Received message for unknown local-id: %s', message)
[ "def", "_handle_message_for_stream", "(", "self", ",", "stream_transport", ",", "message", ",", "timeout", ")", ":", "if", "message", ".", "command", "not", "in", "(", "'OKAY'", ",", "'CLSE'", ",", "'WRTE'", ")", ":", "raise", "usb_exceptions", ".", "AdbProt...
Handle an incoming message, check if it's for the given stream. If the message is not for the stream, then add it to the appropriate message queue. Args: stream_transport: AdbStreamTransport currently waiting on a message. message: Message to check and handle. timeout: Timeout to use for the operation, should be an instance of timeouts.PolledTimeout. Returns: The message read if it was for this stream, None otherwise. Raises: AdbProtocolError: If we receive an unexpected message type.
[ "Handle", "an", "incoming", "message", "check", "if", "it", "s", "for", "the", "given", "stream", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L596-L642
240,767
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection.open_stream
def open_stream(self, destination, timeout_ms=None): """Opens a new stream to a destination service on the device. Not the same as the posix 'open' or any other Open methods, this corresponds to the OPEN message described in the ADB protocol documentation mentioned above. It creates a stream (uniquely identified by remote/local ids) that connects to a particular service endpoint. Args: destination: The service:command string, see ADB documentation. timeout_ms: Timeout in milliseconds for the Open to succeed (or as a PolledTimeout object). Raises: AdbProtocolError: Wrong local_id sent to us, or we didn't get a ready response. Returns: An AdbStream object that can be used to read/write data to the specified service endpoint, or None if the requested service couldn't be opened. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) stream_transport = self._make_stream_transport() self.transport.write_message( adb_message.AdbMessage( command='OPEN', arg0=stream_transport.local_id, arg1=0, data=destination + '\0'), timeout) if not stream_transport.ensure_opened(timeout): return None return AdbStream(destination, stream_transport)
python
def open_stream(self, destination, timeout_ms=None): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) stream_transport = self._make_stream_transport() self.transport.write_message( adb_message.AdbMessage( command='OPEN', arg0=stream_transport.local_id, arg1=0, data=destination + '\0'), timeout) if not stream_transport.ensure_opened(timeout): return None return AdbStream(destination, stream_transport)
[ "def", "open_stream", "(", "self", ",", "destination", ",", "timeout_ms", "=", "None", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", "stream_transport", "=", "self", ".", "_make_stream_transport", "(", ...
Opens a new stream to a destination service on the device. Not the same as the posix 'open' or any other Open methods, this corresponds to the OPEN message described in the ADB protocol documentation mentioned above. It creates a stream (uniquely identified by remote/local ids) that connects to a particular service endpoint. Args: destination: The service:command string, see ADB documentation. timeout_ms: Timeout in milliseconds for the Open to succeed (or as a PolledTimeout object). Raises: AdbProtocolError: Wrong local_id sent to us, or we didn't get a ready response. Returns: An AdbStream object that can be used to read/write data to the specified service endpoint, or None if the requested service couldn't be opened.
[ "Opens", "a", "new", "stream", "to", "a", "destination", "service", "on", "the", "device", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L648-L680
240,768
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection.close_stream_transport
def close_stream_transport(self, stream_transport, timeout): """Remove the given stream transport's id from our map of id's. If the stream id is actually removed, we send a CLSE message to let the remote end know (this happens when we are ack'ing a CLSE message we received). The ADB protocol doesn't say this is a requirement, but ADB does it, so we do too. Args: stream_transport: The stream transport to close. timeout: Timeout on the operation. Returns: True if the id was removed and message sent, False if it was already missing from the stream map (already closed). """ with self._stream_transport_map_lock: if stream_transport.local_id in self._stream_transport_map: del self._stream_transport_map[stream_transport.local_id] # If we never got a remote_id, there's no CLSE message to send. if stream_transport.remote_id: self.transport.write_message(adb_message.AdbMessage( 'CLSE', stream_transport.local_id, stream_transport.remote_id), timeout) return True return False
python
def close_stream_transport(self, stream_transport, timeout): with self._stream_transport_map_lock: if stream_transport.local_id in self._stream_transport_map: del self._stream_transport_map[stream_transport.local_id] # If we never got a remote_id, there's no CLSE message to send. if stream_transport.remote_id: self.transport.write_message(adb_message.AdbMessage( 'CLSE', stream_transport.local_id, stream_transport.remote_id), timeout) return True return False
[ "def", "close_stream_transport", "(", "self", ",", "stream_transport", ",", "timeout", ")", ":", "with", "self", ".", "_stream_transport_map_lock", ":", "if", "stream_transport", ".", "local_id", "in", "self", ".", "_stream_transport_map", ":", "del", "self", ".",...
Remove the given stream transport's id from our map of id's. If the stream id is actually removed, we send a CLSE message to let the remote end know (this happens when we are ack'ing a CLSE message we received). The ADB protocol doesn't say this is a requirement, but ADB does it, so we do too. Args: stream_transport: The stream transport to close. timeout: Timeout on the operation. Returns: True if the id was removed and message sent, False if it was already missing from the stream map (already closed).
[ "Remove", "the", "given", "stream", "transport", "s", "id", "from", "our", "map", "of", "id", "s", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L682-L707
240,769
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection.streaming_command
def streaming_command(self, service, command='', timeout_ms=None): """One complete set of packets for a single command. Helper function to call open_stream and yield the output. Sends service:command in a new connection, reading the data for the response. All the data is held in memory, large responses will be slow and can fill up memory. Args: service: The service on the device to talk to. command: The command to send to the service. timeout_ms: Timeout for the entire command, in milliseconds (or as a PolledTimeout object). Yields: The data contained in the responses from the service. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) stream = self.open_stream('%s:%s' % (service, command), timeout) if not stream: raise usb_exceptions.AdbStreamUnavailableError( '%s does not support service: %s', self, service) for data in stream.read_until_close(timeout): yield data
python
def streaming_command(self, service, command='', timeout_ms=None): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) stream = self.open_stream('%s:%s' % (service, command), timeout) if not stream: raise usb_exceptions.AdbStreamUnavailableError( '%s does not support service: %s', self, service) for data in stream.read_until_close(timeout): yield data
[ "def", "streaming_command", "(", "self", ",", "service", ",", "command", "=", "''", ",", "timeout_ms", "=", "None", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", "stream", "=", "self", ".", "open_st...
One complete set of packets for a single command. Helper function to call open_stream and yield the output. Sends service:command in a new connection, reading the data for the response. All the data is held in memory, large responses will be slow and can fill up memory. Args: service: The service on the device to talk to. command: The command to send to the service. timeout_ms: Timeout for the entire command, in milliseconds (or as a PolledTimeout object). Yields: The data contained in the responses from the service.
[ "One", "complete", "set", "of", "packets", "for", "a", "single", "command", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L709-L732
240,770
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection.read_for_stream
def read_for_stream(self, stream_transport, timeout_ms=None): """Attempt to read a packet for the given stream transport. Will read packets from self.transport until one intended for the given AdbStream is found. If another thread is already reading packets, this will block until that thread reads a packet for this stream, or timeout expires. Note that this method always returns None, but if a packet was read for the given stream, it will have been added to that stream's message queue. This is somewhat tricky to do - first we check if there's a message already in our queue. If not, then we try to use our AdbConnection to read a message for this stream. If some other thread is already doing reads, then read_for_stream() will sit in a tight loop, with a short delay, checking our message queue for a message from the other thread. Note that we must pass the queue in from the AdbStream, rather than looking it up in the AdbConnection's map, because the AdbConnection may have removed the queue from its map (while it still had messages in it). The AdbStream itself maintains a reference to the queue to avoid dropping those messages. The AdbMessage read is guaranteed to be one of 'OKAY', 'WRTE', or 'CLSE'. If it was a WRTE message, then it will have been automatically ACK'd with an OKAY message, if it was a CLSE message it will have been ACK'd with a corresponding CLSE message, and this AdbStream will be marked as closed. Args: stream_transport: The AdbStreamTransport for the stream that is reading an AdbMessage from this AdbConnection. timeout_ms: If provided, timeout, in milliseconds, to use. Note this timeout applies to this entire call, not for each individual Read, since there may be multiple reads if messages for other streams are read. This argument may be a timeouts.PolledTimeout. Returns: AdbMessage that was read, guaranteed to be one of 'OKAY', 'CLSE', or 'WRTE' command. Raises: AdbTimeoutError: If we don't get a packet for this stream before timeout expires. AdbStreamClosedError: If the given stream has been closed. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) # Bail when the timeout expires, or when we no longer have the given stream # in our map (it may have been closed, we don't want to leave a thread # hanging in this loop when that happens). while (not timeout.has_expired() and stream_transport.local_id in self._stream_transport_map): try: # Block for up to 10ms to rate-limit how fast we spin. return stream_transport.message_queue.get(True, .01) except queue.Empty: pass # If someone else has the Lock, just keep checking our queue. if not self._reader_lock.acquire(False): continue try: # Now that we've acquired the Lock, we have to check the queue again, # just in case someone had the Lock but hadn't yet added our message # to the queue when we checked the first time. Now that we have the # Lock ourselves, we're sure there are no potentially in-flight reads. try: return stream_transport.message_queue.get_nowait() except queue.Empty: pass while not timeout.has_expired(): msg = self._handle_message_for_stream( stream_transport, self.transport.read_message(timeout), timeout) if msg: return msg finally: self._reader_lock.release() if timeout.has_expired(): raise usb_exceptions.AdbTimeoutError( 'Read timed out for %s', stream_transport) # The stream is no longer in the map, so it's closed, but check for any # queued messages. try: return stream_transport.message_queue.get_nowait() except queue.Empty: raise usb_exceptions.AdbStreamClosedError( 'Attempt to read from closed or unknown %s', stream_transport)
python
def read_for_stream(self, stream_transport, timeout_ms=None): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) # Bail when the timeout expires, or when we no longer have the given stream # in our map (it may have been closed, we don't want to leave a thread # hanging in this loop when that happens). while (not timeout.has_expired() and stream_transport.local_id in self._stream_transport_map): try: # Block for up to 10ms to rate-limit how fast we spin. return stream_transport.message_queue.get(True, .01) except queue.Empty: pass # If someone else has the Lock, just keep checking our queue. if not self._reader_lock.acquire(False): continue try: # Now that we've acquired the Lock, we have to check the queue again, # just in case someone had the Lock but hadn't yet added our message # to the queue when we checked the first time. Now that we have the # Lock ourselves, we're sure there are no potentially in-flight reads. try: return stream_transport.message_queue.get_nowait() except queue.Empty: pass while not timeout.has_expired(): msg = self._handle_message_for_stream( stream_transport, self.transport.read_message(timeout), timeout) if msg: return msg finally: self._reader_lock.release() if timeout.has_expired(): raise usb_exceptions.AdbTimeoutError( 'Read timed out for %s', stream_transport) # The stream is no longer in the map, so it's closed, but check for any # queued messages. try: return stream_transport.message_queue.get_nowait() except queue.Empty: raise usb_exceptions.AdbStreamClosedError( 'Attempt to read from closed or unknown %s', stream_transport)
[ "def", "read_for_stream", "(", "self", ",", "stream_transport", ",", "timeout_ms", "=", "None", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", "# Bail when the timeout expires, or when we no longer have the given st...
Attempt to read a packet for the given stream transport. Will read packets from self.transport until one intended for the given AdbStream is found. If another thread is already reading packets, this will block until that thread reads a packet for this stream, or timeout expires. Note that this method always returns None, but if a packet was read for the given stream, it will have been added to that stream's message queue. This is somewhat tricky to do - first we check if there's a message already in our queue. If not, then we try to use our AdbConnection to read a message for this stream. If some other thread is already doing reads, then read_for_stream() will sit in a tight loop, with a short delay, checking our message queue for a message from the other thread. Note that we must pass the queue in from the AdbStream, rather than looking it up in the AdbConnection's map, because the AdbConnection may have removed the queue from its map (while it still had messages in it). The AdbStream itself maintains a reference to the queue to avoid dropping those messages. The AdbMessage read is guaranteed to be one of 'OKAY', 'WRTE', or 'CLSE'. If it was a WRTE message, then it will have been automatically ACK'd with an OKAY message, if it was a CLSE message it will have been ACK'd with a corresponding CLSE message, and this AdbStream will be marked as closed. Args: stream_transport: The AdbStreamTransport for the stream that is reading an AdbMessage from this AdbConnection. timeout_ms: If provided, timeout, in milliseconds, to use. Note this timeout applies to this entire call, not for each individual Read, since there may be multiple reads if messages for other streams are read. This argument may be a timeouts.PolledTimeout. Returns: AdbMessage that was read, guaranteed to be one of 'OKAY', 'CLSE', or 'WRTE' command. Raises: AdbTimeoutError: If we don't get a packet for this stream before timeout expires. AdbStreamClosedError: If the given stream has been closed.
[ "Attempt", "to", "read", "a", "packet", "for", "the", "given", "stream", "transport", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L734-L823
240,771
google/openhtf
openhtf/plugs/usb/adb_protocol.py
AdbConnection.connect
def connect(cls, transport, rsa_keys=None, timeout_ms=1000, auth_timeout_ms=100): """Establish a new connection to a device, connected via transport. Args: transport: A transport to use for reads/writes from/to the device, usually an instance of UsbHandle, but really it can be anything with read() and write() methods. rsa_keys: List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the sign method, or we will send the result of get_public_key from the first one if the device doesn't accept any of them. timeout_ms: Timeout to wait for the device to respond to our CNXN request. Actual timeout may take longer if the transport object passed has a longer default timeout than timeout_ms, or if auth_timeout_ms is longer than timeout_ms and public key auth is used. This argument may be a PolledTimeout object. auth_timeout_ms: Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it's low by default. This argument may be a PolledTimeout object. Returns: An instance of AdbConnection that is connected to the device. Raises: usb_exceptions.DeviceAuthError: When the device expects authentication, but we weren't given any valid keys. usb_exceptions.AdbProtocolError: When the device does authentication in an unexpected way, or fails to respond appropriately to our CNXN request. """ timeout = timeouts.PolledTimeout.from_millis(timeout_ms) if ADB_MESSAGE_LOG: adb_transport = adb_message.DebugAdbTransportAdapter(transport) else: adb_transport = adb_message.AdbTransportAdapter(transport) adb_transport.write_message( adb_message.AdbMessage( command='CNXN', arg0=ADB_VERSION, arg1=MAX_ADB_DATA, data='host::%s\0' % ADB_BANNER), timeout) msg = adb_transport.read_until(('AUTH', 'CNXN'), timeout) if msg.command == 'CNXN': return cls(adb_transport, msg.arg1, msg.data) # We got an AUTH response, so we have to try to authenticate. if not rsa_keys: raise usb_exceptions.DeviceAuthError( 'Device authentication required, no keys available.') # Loop through our keys, signing the last 'banner' or token. for rsa_key in rsa_keys: if msg.arg0 != cls.AUTH_TOKEN: raise usb_exceptions.AdbProtocolError('Bad AUTH response: %s', msg) signed_token = rsa_key.sign(msg.data) adb_transport.write_message( adb_message.AdbMessage( command='AUTH', arg0=cls.AUTH_SIGNATURE, arg1=0, data=signed_token), timeout) msg = adb_transport.read_until(('AUTH', 'CNXN'), timeout) if msg.command == 'CNXN': return cls(adb_transport, msg.arg1, msg.data) # None of the keys worked, so send a public key. adb_transport.write_message( adb_message.AdbMessage( command='AUTH', arg0=cls.AUTH_RSAPUBLICKEY, arg1=0, data=rsa_keys[0].get_public_key() + '\0'), timeout) try: msg = adb_transport.read_until( ('CNXN',), timeouts.PolledTimeout.from_millis(auth_timeout_ms)) except usb_exceptions.UsbReadFailedError as exception: if exception.is_timeout(): exceptions.reraise(usb_exceptions.DeviceAuthError, 'Accept auth key on device, then retry.') raise # The read didn't time-out, so we got a CNXN response. return cls(adb_transport, msg.arg1, msg.data)
python
def connect(cls, transport, rsa_keys=None, timeout_ms=1000, auth_timeout_ms=100): timeout = timeouts.PolledTimeout.from_millis(timeout_ms) if ADB_MESSAGE_LOG: adb_transport = adb_message.DebugAdbTransportAdapter(transport) else: adb_transport = adb_message.AdbTransportAdapter(transport) adb_transport.write_message( adb_message.AdbMessage( command='CNXN', arg0=ADB_VERSION, arg1=MAX_ADB_DATA, data='host::%s\0' % ADB_BANNER), timeout) msg = adb_transport.read_until(('AUTH', 'CNXN'), timeout) if msg.command == 'CNXN': return cls(adb_transport, msg.arg1, msg.data) # We got an AUTH response, so we have to try to authenticate. if not rsa_keys: raise usb_exceptions.DeviceAuthError( 'Device authentication required, no keys available.') # Loop through our keys, signing the last 'banner' or token. for rsa_key in rsa_keys: if msg.arg0 != cls.AUTH_TOKEN: raise usb_exceptions.AdbProtocolError('Bad AUTH response: %s', msg) signed_token = rsa_key.sign(msg.data) adb_transport.write_message( adb_message.AdbMessage( command='AUTH', arg0=cls.AUTH_SIGNATURE, arg1=0, data=signed_token), timeout) msg = adb_transport.read_until(('AUTH', 'CNXN'), timeout) if msg.command == 'CNXN': return cls(adb_transport, msg.arg1, msg.data) # None of the keys worked, so send a public key. adb_transport.write_message( adb_message.AdbMessage( command='AUTH', arg0=cls.AUTH_RSAPUBLICKEY, arg1=0, data=rsa_keys[0].get_public_key() + '\0'), timeout) try: msg = adb_transport.read_until( ('CNXN',), timeouts.PolledTimeout.from_millis(auth_timeout_ms)) except usb_exceptions.UsbReadFailedError as exception: if exception.is_timeout(): exceptions.reraise(usb_exceptions.DeviceAuthError, 'Accept auth key on device, then retry.') raise # The read didn't time-out, so we got a CNXN response. return cls(adb_transport, msg.arg1, msg.data)
[ "def", "connect", "(", "cls", ",", "transport", ",", "rsa_keys", "=", "None", ",", "timeout_ms", "=", "1000", ",", "auth_timeout_ms", "=", "100", ")", ":", "timeout", "=", "timeouts", ".", "PolledTimeout", ".", "from_millis", "(", "timeout_ms", ")", "if", ...
Establish a new connection to a device, connected via transport. Args: transport: A transport to use for reads/writes from/to the device, usually an instance of UsbHandle, but really it can be anything with read() and write() methods. rsa_keys: List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the sign method, or we will send the result of get_public_key from the first one if the device doesn't accept any of them. timeout_ms: Timeout to wait for the device to respond to our CNXN request. Actual timeout may take longer if the transport object passed has a longer default timeout than timeout_ms, or if auth_timeout_ms is longer than timeout_ms and public key auth is used. This argument may be a PolledTimeout object. auth_timeout_ms: Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it's low by default. This argument may be a PolledTimeout object. Returns: An instance of AdbConnection that is connected to the device. Raises: usb_exceptions.DeviceAuthError: When the device expects authentication, but we weren't given any valid keys. usb_exceptions.AdbProtocolError: When the device does authentication in an unexpected way, or fails to respond appropriately to our CNXN request.
[ "Establish", "a", "new", "connection", "to", "a", "device", "connected", "via", "transport", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/adb_protocol.py#L826-L912
240,772
google/openhtf
examples/example_plugs.py
ExamplePlug.increment
def increment(self): """Increment our value, return the previous value.""" self.value += self.increment_size return self.value - self.increment_size
python
def increment(self): self.value += self.increment_size return self.value - self.increment_size
[ "def", "increment", "(", "self", ")", ":", "self", ".", "value", "+=", "self", ".", "increment_size", "return", "self", ".", "value", "-", "self", ".", "increment_size" ]
Increment our value, return the previous value.
[ "Increment", "our", "value", "return", "the", "previous", "value", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/example_plugs.py#L76-L79
240,773
google/openhtf
openhtf/plugs/__init__.py
plug
def plug(update_kwargs=True, **plugs_map): """Creates a decorator that passes in plugs when invoked. This function returns a decorator for a function that will replace positional arguments to that function with the plugs specified. See the module docstring for details and examples. Note this decorator does not work with class or bound methods, but does work with @staticmethod. Args: update_kwargs: If true, makes the decorated phase take this plug as a kwarg. **plugs_map: Dict mapping name to Plug type. Returns: A PhaseDescriptor that will pass plug instances in as kwargs when invoked. Raises: InvalidPlugError: If a type is provided that is not a subclass of BasePlug. """ for a_plug in plugs_map.values(): if not (isinstance(a_plug, PlugPlaceholder) or issubclass(a_plug, BasePlug)): raise InvalidPlugError( 'Plug %s is not a subclass of plugs.BasePlug nor a placeholder ' 'for one' % a_plug) def result(func): """Wrap the given function and return the wrapper. Args: func: The function to wrap. Returns: A PhaseDescriptor that, when called will invoke the wrapped function, passing plugs as keyword args. Raises: DuplicatePlugError: If a plug name is declared twice for the same function. """ phase = openhtf.core.phase_descriptor.PhaseDescriptor.wrap_or_copy(func) duplicates = (frozenset(p.name for p in phase.plugs) & frozenset(plugs_map)) if duplicates: raise DuplicatePlugError( 'Plugs %s required multiple times on phase %s' % (duplicates, func)) phase.plugs.extend([ PhasePlug(name, a_plug, update_kwargs=update_kwargs) for name, a_plug in six.iteritems(plugs_map)]) return phase return result
python
def plug(update_kwargs=True, **plugs_map): for a_plug in plugs_map.values(): if not (isinstance(a_plug, PlugPlaceholder) or issubclass(a_plug, BasePlug)): raise InvalidPlugError( 'Plug %s is not a subclass of plugs.BasePlug nor a placeholder ' 'for one' % a_plug) def result(func): """Wrap the given function and return the wrapper. Args: func: The function to wrap. Returns: A PhaseDescriptor that, when called will invoke the wrapped function, passing plugs as keyword args. Raises: DuplicatePlugError: If a plug name is declared twice for the same function. """ phase = openhtf.core.phase_descriptor.PhaseDescriptor.wrap_or_copy(func) duplicates = (frozenset(p.name for p in phase.plugs) & frozenset(plugs_map)) if duplicates: raise DuplicatePlugError( 'Plugs %s required multiple times on phase %s' % (duplicates, func)) phase.plugs.extend([ PhasePlug(name, a_plug, update_kwargs=update_kwargs) for name, a_plug in six.iteritems(plugs_map)]) return phase return result
[ "def", "plug", "(", "update_kwargs", "=", "True", ",", "*", "*", "plugs_map", ")", ":", "for", "a_plug", "in", "plugs_map", ".", "values", "(", ")", ":", "if", "not", "(", "isinstance", "(", "a_plug", ",", "PlugPlaceholder", ")", "or", "issubclass", "(...
Creates a decorator that passes in plugs when invoked. This function returns a decorator for a function that will replace positional arguments to that function with the plugs specified. See the module docstring for details and examples. Note this decorator does not work with class or bound methods, but does work with @staticmethod. Args: update_kwargs: If true, makes the decorated phase take this plug as a kwarg. **plugs_map: Dict mapping name to Plug type. Returns: A PhaseDescriptor that will pass plug instances in as kwargs when invoked. Raises: InvalidPlugError: If a type is provided that is not a subclass of BasePlug.
[ "Creates", "a", "decorator", "that", "passes", "in", "plugs", "when", "invoked", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L217-L269
240,774
google/openhtf
openhtf/plugs/__init__.py
BasePlug.uses_base_tear_down
def uses_base_tear_down(cls): """Checks whether the tearDown method is the BasePlug implementation.""" this_tear_down = getattr(cls, 'tearDown') base_tear_down = getattr(BasePlug, 'tearDown') return this_tear_down.__code__ is base_tear_down.__code__
python
def uses_base_tear_down(cls): this_tear_down = getattr(cls, 'tearDown') base_tear_down = getattr(BasePlug, 'tearDown') return this_tear_down.__code__ is base_tear_down.__code__
[ "def", "uses_base_tear_down", "(", "cls", ")", ":", "this_tear_down", "=", "getattr", "(", "cls", ",", "'tearDown'", ")", "base_tear_down", "=", "getattr", "(", "BasePlug", ",", "'tearDown'", ")", "return", "this_tear_down", ".", "__code__", "is", "base_tear_dow...
Checks whether the tearDown method is the BasePlug implementation.
[ "Checks", "whether", "the", "tearDown", "method", "is", "the", "BasePlug", "implementation", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L196-L200
240,775
google/openhtf
openhtf/plugs/__init__.py
PlugManager.get_plug_mro
def get_plug_mro(self, plug_type): """Returns a list of names identifying the plug classes in the plug's MRO. For example: ['openhtf.plugs.user_input.UserInput'] Or: ['openhtf.plugs.user_input.UserInput', 'my_module.advanced_user_input.AdvancedUserInput'] """ ignored_classes = (BasePlug, FrontendAwareBasePlug) return [ self.get_plug_name(base_class) for base_class in plug_type.mro() if (issubclass(base_class, BasePlug) and base_class not in ignored_classes) ]
python
def get_plug_mro(self, plug_type): ignored_classes = (BasePlug, FrontendAwareBasePlug) return [ self.get_plug_name(base_class) for base_class in plug_type.mro() if (issubclass(base_class, BasePlug) and base_class not in ignored_classes) ]
[ "def", "get_plug_mro", "(", "self", ",", "plug_type", ")", ":", "ignored_classes", "=", "(", "BasePlug", ",", "FrontendAwareBasePlug", ")", "return", "[", "self", ".", "get_plug_name", "(", "base_class", ")", "for", "base_class", "in", "plug_type", ".", "mro",...
Returns a list of names identifying the plug classes in the plug's MRO. For example: ['openhtf.plugs.user_input.UserInput'] Or: ['openhtf.plugs.user_input.UserInput', 'my_module.advanced_user_input.AdvancedUserInput']
[ "Returns", "a", "list", "of", "names", "identifying", "the", "plug", "classes", "in", "the", "plug", "s", "MRO", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L338-L352
240,776
google/openhtf
openhtf/plugs/__init__.py
PlugManager.initialize_plugs
def initialize_plugs(self, plug_types=None): """Instantiate required plugs. Instantiates plug types and saves the instances in self._plugs_by_type for use in provide_plugs(). Args: plug_types: Plug types may be specified here rather than passed into the constructor (this is used primarily for unit testing phases). """ types = plug_types if plug_types is not None else self._plug_types for plug_type in types: # Create a logger for this plug. All plug loggers go under the 'plug' # sub-logger in the logger hierarchy. plug_logger = self.logger.getChild(plug_type.__name__) if plug_type in self._plugs_by_type: continue try: if not issubclass(plug_type, BasePlug): raise InvalidPlugError( 'Plug type "%s" is not an instance of BasePlug' % plug_type) if plug_type.logger != _LOG: # They put a logger attribute on the class itself, overriding ours. raise InvalidPlugError( 'Do not override "logger" in your plugs.', plug_type) # Override the logger so that __init__'s logging goes into the record. plug_type.logger = plug_logger try: plug_instance = plug_type() finally: # Now set it back since we'll give the instance a logger in a moment. plug_type.logger = _LOG # Set the logger attribute directly (rather than in BasePlug) so we # don't depend on subclasses' implementation of __init__ to have it # set. if plug_instance.logger != _LOG: raise InvalidPlugError( 'Do not set "self.logger" in __init__ in your plugs', plug_type) else: # Now the instance has its own copy of the test logger. plug_instance.logger = plug_logger except Exception: # pylint: disable=broad-except plug_logger.exception('Exception instantiating plug type %s', plug_type) self.tear_down_plugs() raise self.update_plug(plug_type, plug_instance)
python
def initialize_plugs(self, plug_types=None): types = plug_types if plug_types is not None else self._plug_types for plug_type in types: # Create a logger for this plug. All plug loggers go under the 'plug' # sub-logger in the logger hierarchy. plug_logger = self.logger.getChild(plug_type.__name__) if plug_type in self._plugs_by_type: continue try: if not issubclass(plug_type, BasePlug): raise InvalidPlugError( 'Plug type "%s" is not an instance of BasePlug' % plug_type) if plug_type.logger != _LOG: # They put a logger attribute on the class itself, overriding ours. raise InvalidPlugError( 'Do not override "logger" in your plugs.', plug_type) # Override the logger so that __init__'s logging goes into the record. plug_type.logger = plug_logger try: plug_instance = plug_type() finally: # Now set it back since we'll give the instance a logger in a moment. plug_type.logger = _LOG # Set the logger attribute directly (rather than in BasePlug) so we # don't depend on subclasses' implementation of __init__ to have it # set. if plug_instance.logger != _LOG: raise InvalidPlugError( 'Do not set "self.logger" in __init__ in your plugs', plug_type) else: # Now the instance has its own copy of the test logger. plug_instance.logger = plug_logger except Exception: # pylint: disable=broad-except plug_logger.exception('Exception instantiating plug type %s', plug_type) self.tear_down_plugs() raise self.update_plug(plug_type, plug_instance)
[ "def", "initialize_plugs", "(", "self", ",", "plug_types", "=", "None", ")", ":", "types", "=", "plug_types", "if", "plug_types", "is", "not", "None", "else", "self", ".", "_plug_types", "for", "plug_type", "in", "types", ":", "# Create a logger for this plug. A...
Instantiate required plugs. Instantiates plug types and saves the instances in self._plugs_by_type for use in provide_plugs(). Args: plug_types: Plug types may be specified here rather than passed into the constructor (this is used primarily for unit testing phases).
[ "Instantiate", "required", "plugs", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L362-L409
240,777
google/openhtf
openhtf/plugs/__init__.py
PlugManager.update_plug
def update_plug(self, plug_type, plug_value): """Update internal data stores with the given plug value for plug type. Safely tears down the old instance if one was already created, but that's generally not the case outside unittests. Also, we explicitly pass the plug_type rather than detecting it from plug_value to allow unittests to override plugs with Mock instances. Note this should only be used inside unittests, as this mechanism is not compatible with RemotePlug support. """ self._plug_types.add(plug_type) if plug_type in self._plugs_by_type: self._plugs_by_type[plug_type].tearDown() plug_name = self.get_plug_name(plug_type) self._plugs_by_type[plug_type] = plug_value self._plugs_by_name[plug_name] = plug_value self._plug_descriptors[plug_name] = self._make_plug_descriptor(plug_type)
python
def update_plug(self, plug_type, plug_value): self._plug_types.add(plug_type) if plug_type in self._plugs_by_type: self._plugs_by_type[plug_type].tearDown() plug_name = self.get_plug_name(plug_type) self._plugs_by_type[plug_type] = plug_value self._plugs_by_name[plug_name] = plug_value self._plug_descriptors[plug_name] = self._make_plug_descriptor(plug_type)
[ "def", "update_plug", "(", "self", ",", "plug_type", ",", "plug_value", ")", ":", "self", ".", "_plug_types", ".", "add", "(", "plug_type", ")", "if", "plug_type", "in", "self", ".", "_plugs_by_type", ":", "self", ".", "_plugs_by_type", "[", "plug_type", "...
Update internal data stores with the given plug value for plug type. Safely tears down the old instance if one was already created, but that's generally not the case outside unittests. Also, we explicitly pass the plug_type rather than detecting it from plug_value to allow unittests to override plugs with Mock instances. Note this should only be used inside unittests, as this mechanism is not compatible with RemotePlug support.
[ "Update", "internal", "data", "stores", "with", "the", "given", "plug", "value", "for", "plug", "type", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L425-L442
240,778
google/openhtf
openhtf/plugs/__init__.py
PlugManager.wait_for_plug_update
def wait_for_plug_update(self, plug_name, remote_state, timeout_s): """Wait for a change in the state of a frontend-aware plug. Args: plug_name: Plug name, e.g. 'openhtf.plugs.user_input.UserInput'. remote_state: The last observed state. timeout_s: Number of seconds to wait for an update. Returns: An updated state, or None if the timeout runs out. Raises: InvalidPlugError: The plug can't be waited on either because it's not in use or it's not a frontend-aware plug. """ plug = self._plugs_by_name.get(plug_name) if plug is None: raise InvalidPlugError('Cannot wait on unknown plug "%s".' % plug_name) if not isinstance(plug, FrontendAwareBasePlug): raise InvalidPlugError('Cannot wait on a plug %s that is not an subclass ' 'of FrontendAwareBasePlug.' % plug_name) state, update_event = plug.asdict_with_event() if state != remote_state: return state if update_event.wait(timeout_s): return plug._asdict()
python
def wait_for_plug_update(self, plug_name, remote_state, timeout_s): plug = self._plugs_by_name.get(plug_name) if plug is None: raise InvalidPlugError('Cannot wait on unknown plug "%s".' % plug_name) if not isinstance(plug, FrontendAwareBasePlug): raise InvalidPlugError('Cannot wait on a plug %s that is not an subclass ' 'of FrontendAwareBasePlug.' % plug_name) state, update_event = plug.asdict_with_event() if state != remote_state: return state if update_event.wait(timeout_s): return plug._asdict()
[ "def", "wait_for_plug_update", "(", "self", ",", "plug_name", ",", "remote_state", ",", "timeout_s", ")", ":", "plug", "=", "self", ".", "_plugs_by_name", ".", "get", "(", "plug_name", ")", "if", "plug", "is", "None", ":", "raise", "InvalidPlugError", "(", ...
Wait for a change in the state of a frontend-aware plug. Args: plug_name: Plug name, e.g. 'openhtf.plugs.user_input.UserInput'. remote_state: The last observed state. timeout_s: Number of seconds to wait for an update. Returns: An updated state, or None if the timeout runs out. Raises: InvalidPlugError: The plug can't be waited on either because it's not in use or it's not a frontend-aware plug.
[ "Wait", "for", "a", "change", "in", "the", "state", "of", "a", "frontend", "-", "aware", "plug", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L477-L506
240,779
google/openhtf
openhtf/plugs/__init__.py
PlugManager.get_frontend_aware_plug_names
def get_frontend_aware_plug_names(self): """Returns the names of frontend-aware plugs.""" return [name for name, plug in six.iteritems(self._plugs_by_name) if isinstance(plug, FrontendAwareBasePlug)]
python
def get_frontend_aware_plug_names(self): return [name for name, plug in six.iteritems(self._plugs_by_name) if isinstance(plug, FrontendAwareBasePlug)]
[ "def", "get_frontend_aware_plug_names", "(", "self", ")", ":", "return", "[", "name", "for", "name", ",", "plug", "in", "six", ".", "iteritems", "(", "self", ".", "_plugs_by_name", ")", "if", "isinstance", "(", "plug", ",", "FrontendAwareBasePlug", ")", "]" ...
Returns the names of frontend-aware plugs.
[ "Returns", "the", "names", "of", "frontend", "-", "aware", "plugs", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/__init__.py#L508-L511
240,780
google/openhtf
openhtf/output/servers/station_server.py
_wait_for_any_event
def _wait_for_any_event(events, timeout_s): """Wait for any in a list of threading.Event's to be set. Args: events: List of threading.Event's. timeout_s: Max duration in seconds to wait before returning. Returns: True if at least one event was set before the timeout expired, else False. """ def any_event_set(): return any(event.is_set() for event in events) result = timeouts.loop_until_timeout_or_true( timeout_s, any_event_set, sleep_s=_WAIT_FOR_ANY_EVENT_POLL_S) return result or any_event_set()
python
def _wait_for_any_event(events, timeout_s): def any_event_set(): return any(event.is_set() for event in events) result = timeouts.loop_until_timeout_or_true( timeout_s, any_event_set, sleep_s=_WAIT_FOR_ANY_EVENT_POLL_S) return result or any_event_set()
[ "def", "_wait_for_any_event", "(", "events", ",", "timeout_s", ")", ":", "def", "any_event_set", "(", ")", ":", "return", "any", "(", "event", ".", "is_set", "(", ")", "for", "event", "in", "events", ")", "result", "=", "timeouts", ".", "loop_until_timeout...
Wait for any in a list of threading.Event's to be set. Args: events: List of threading.Event's. timeout_s: Max duration in seconds to wait before returning. Returns: True if at least one event was set before the timeout expired, else False.
[ "Wait", "for", "any", "in", "a", "list", "of", "threading", ".", "Event", "s", "to", "be", "set", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/station_server.py#L119-L135
240,781
google/openhtf
openhtf/output/servers/station_server.py
StationWatcher._poll_for_update
def _poll_for_update(self): """Call the callback with the current test state, then wait for a change.""" test, test_state = _get_executing_test() if test is None: time.sleep(_WAIT_FOR_EXECUTING_TEST_POLL_S) return state_dict, event = self._to_dict_with_event(test_state) self._update_callback(state_dict) plug_manager = test_state.plug_manager plug_events = [ plug_manager.get_plug_by_class_path(plug_name).asdict_with_event()[1] for plug_name in plug_manager.get_frontend_aware_plug_names() ] events = [event] + plug_events # Wait for the test state or a plug state to change, or for the previously # executing test to finish. while not _wait_for_any_event(events, _CHECK_FOR_FINISHED_TEST_POLL_S): new_test, _ = _get_executing_test() if test != new_test: break
python
def _poll_for_update(self): test, test_state = _get_executing_test() if test is None: time.sleep(_WAIT_FOR_EXECUTING_TEST_POLL_S) return state_dict, event = self._to_dict_with_event(test_state) self._update_callback(state_dict) plug_manager = test_state.plug_manager plug_events = [ plug_manager.get_plug_by_class_path(plug_name).asdict_with_event()[1] for plug_name in plug_manager.get_frontend_aware_plug_names() ] events = [event] + plug_events # Wait for the test state or a plug state to change, or for the previously # executing test to finish. while not _wait_for_any_event(events, _CHECK_FOR_FINISHED_TEST_POLL_S): new_test, _ = _get_executing_test() if test != new_test: break
[ "def", "_poll_for_update", "(", "self", ")", ":", "test", ",", "test_state", "=", "_get_executing_test", "(", ")", "if", "test", "is", "None", ":", "time", ".", "sleep", "(", "_WAIT_FOR_EXECUTING_TEST_POLL_S", ")", "return", "state_dict", ",", "event", "=", ...
Call the callback with the current test state, then wait for a change.
[ "Call", "the", "callback", "with", "the", "current", "test", "state", "then", "wait", "for", "a", "change", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/station_server.py#L176-L199
240,782
google/openhtf
openhtf/output/servers/station_server.py
StationWatcher._to_dict_with_event
def _to_dict_with_event(cls, test_state): """Process a test state into the format we want to send to the frontend.""" original_dict, event = test_state.asdict_with_event() # This line may produce a 'dictionary changed size during iteration' error. test_state_dict = data.convert_to_base_types(original_dict) test_state_dict['execution_uid'] = test_state.execution_uid return test_state_dict, event
python
def _to_dict_with_event(cls, test_state): original_dict, event = test_state.asdict_with_event() # This line may produce a 'dictionary changed size during iteration' error. test_state_dict = data.convert_to_base_types(original_dict) test_state_dict['execution_uid'] = test_state.execution_uid return test_state_dict, event
[ "def", "_to_dict_with_event", "(", "cls", ",", "test_state", ")", ":", "original_dict", ",", "event", "=", "test_state", ".", "asdict_with_event", "(", ")", "# This line may produce a 'dictionary changed size during iteration' error.", "test_state_dict", "=", "data", ".", ...
Process a test state into the format we want to send to the frontend.
[ "Process", "a", "test", "state", "into", "the", "format", "we", "want", "to", "send", "to", "the", "frontend", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/servers/station_server.py#L202-L210
240,783
google/openhtf
openhtf/util/threads.py
_safe_lock_release_py2
def _safe_lock_release_py2(rlock): """Ensure that a threading.RLock is fully released for Python 2. The RLock release code is: https://github.com/python/cpython/blob/2.7/Lib/threading.py#L187 The RLock object's release method does not release all of its state if an exception is raised in the middle of its operation. There are three pieces of internal state that must be cleaned up: - owning thread ident, an integer. - entry count, an integer that counts how many times the current owner has locked the RLock. - internal lock, a threading.Lock instance that handles blocking. Args: rlock: threading.RLock, lock to fully release. Yields: None. """ assert isinstance(rlock, threading._RLock) ident = _thread.get_ident() expected_count = 0 if rlock._RLock__owner == ident: expected_count = rlock._RLock__count try: yield except ThreadTerminationError: # Check if the current thread still owns the lock by checking if we can # acquire the underlying lock. if rlock._RLock__block.acquire(0): # Lock is clean, so unlock and we are done. rlock._RLock__block.release() elif rlock._RLock__owner == ident and expected_count > 0: # The lock is still held up the stack, so make sure the count is accurate. if rlock._RLock__count != expected_count: rlock._RLock__count = expected_count elif rlock._RLock__owner == ident or rlock._RLock__owner is None: # The internal lock is still acquired, but either this thread or no thread # owns it, which means it needs to be hard reset. rlock._RLock__owner = None rlock._RLock__count = 0 rlock._RLock__block.release() raise
python
def _safe_lock_release_py2(rlock): assert isinstance(rlock, threading._RLock) ident = _thread.get_ident() expected_count = 0 if rlock._RLock__owner == ident: expected_count = rlock._RLock__count try: yield except ThreadTerminationError: # Check if the current thread still owns the lock by checking if we can # acquire the underlying lock. if rlock._RLock__block.acquire(0): # Lock is clean, so unlock and we are done. rlock._RLock__block.release() elif rlock._RLock__owner == ident and expected_count > 0: # The lock is still held up the stack, so make sure the count is accurate. if rlock._RLock__count != expected_count: rlock._RLock__count = expected_count elif rlock._RLock__owner == ident or rlock._RLock__owner is None: # The internal lock is still acquired, but either this thread or no thread # owns it, which means it needs to be hard reset. rlock._RLock__owner = None rlock._RLock__count = 0 rlock._RLock__block.release() raise
[ "def", "_safe_lock_release_py2", "(", "rlock", ")", ":", "assert", "isinstance", "(", "rlock", ",", "threading", ".", "_RLock", ")", "ident", "=", "_thread", ".", "get_ident", "(", ")", "expected_count", "=", "0", "if", "rlock", ".", "_RLock__owner", "==", ...
Ensure that a threading.RLock is fully released for Python 2. The RLock release code is: https://github.com/python/cpython/blob/2.7/Lib/threading.py#L187 The RLock object's release method does not release all of its state if an exception is raised in the middle of its operation. There are three pieces of internal state that must be cleaned up: - owning thread ident, an integer. - entry count, an integer that counts how many times the current owner has locked the RLock. - internal lock, a threading.Lock instance that handles blocking. Args: rlock: threading.RLock, lock to fully release. Yields: None.
[ "Ensure", "that", "a", "threading", ".", "RLock", "is", "fully", "released", "for", "Python", "2", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L54-L97
240,784
google/openhtf
openhtf/util/threads.py
loop
def loop(_=None, force=False): # pylint: disable=invalid-name """Causes a function to loop indefinitely.""" if not force: raise AttributeError( 'threads.loop() is DEPRECATED. If you really like this and want to ' 'keep it, file an issue at https://github.com/google/openhtf/issues ' 'and use it as @loop(force=True) for now.') def real_loop(fn): @functools.wraps(fn) def _proc(*args, **kwargs): """Wrapper to return.""" while True: fn(*args, **kwargs) _proc.once = fn # way for tests to invoke the function once # you may need to pass in "self" since this may be unbound. return _proc return real_loop
python
def loop(_=None, force=False): # pylint: disable=invalid-name if not force: raise AttributeError( 'threads.loop() is DEPRECATED. If you really like this and want to ' 'keep it, file an issue at https://github.com/google/openhtf/issues ' 'and use it as @loop(force=True) for now.') def real_loop(fn): @functools.wraps(fn) def _proc(*args, **kwargs): """Wrapper to return.""" while True: fn(*args, **kwargs) _proc.once = fn # way for tests to invoke the function once # you may need to pass in "self" since this may be unbound. return _proc return real_loop
[ "def", "loop", "(", "_", "=", "None", ",", "force", "=", "False", ")", ":", "# pylint: disable=invalid-name", "if", "not", "force", ":", "raise", "AttributeError", "(", "'threads.loop() is DEPRECATED. If you really like this and want to '", "'keep it, file an issue at http...
Causes a function to loop indefinitely.
[ "Causes", "a", "function", "to", "loop", "indefinitely", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L101-L118
240,785
google/openhtf
openhtf/util/threads.py
synchronized
def synchronized(func): # pylint: disable=invalid-name """Hold self._lock while executing func.""" @functools.wraps(func) def synchronized_method(self, *args, **kwargs): """Wrapper to return.""" if not hasattr(self, '_lock'): if func.__name__ in type(self).__dict__: hint = '' else: hint = (' Might be missing call to super in %s.__init__?' % type(self).__name__) raise RuntimeError('Can\'t synchronize method `%s` of %s without ' 'attribute `_lock`.%s' % (func.__name__, type(self).__name__, hint)) with self._lock: # pylint: disable=protected-access return func(self, *args, **kwargs) return synchronized_method
python
def synchronized(func): # pylint: disable=invalid-name @functools.wraps(func) def synchronized_method(self, *args, **kwargs): """Wrapper to return.""" if not hasattr(self, '_lock'): if func.__name__ in type(self).__dict__: hint = '' else: hint = (' Might be missing call to super in %s.__init__?' % type(self).__name__) raise RuntimeError('Can\'t synchronize method `%s` of %s without ' 'attribute `_lock`.%s' % (func.__name__, type(self).__name__, hint)) with self._lock: # pylint: disable=protected-access return func(self, *args, **kwargs) return synchronized_method
[ "def", "synchronized", "(", "func", ")", ":", "# pylint: disable=invalid-name", "@", "functools", ".", "wraps", "(", "func", ")", "def", "synchronized_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapper to return.\"\"\"", ...
Hold self._lock while executing func.
[ "Hold", "self", ".", "_lock", "while", "executing", "func", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L241-L257
240,786
google/openhtf
openhtf/util/threads.py
KillableThread.kill
def kill(self): """Terminates the current thread by raising an error.""" self._killed.set() if not self.is_alive(): logging.debug('Cannot kill thread that is no longer running.') return if not self._is_thread_proc_running(): logging.debug("Thread's _thread_proc function is no longer running, " 'will not kill; letting thread exit gracefully.') return self.async_raise(ThreadTerminationError)
python
def kill(self): self._killed.set() if not self.is_alive(): logging.debug('Cannot kill thread that is no longer running.') return if not self._is_thread_proc_running(): logging.debug("Thread's _thread_proc function is no longer running, " 'will not kill; letting thread exit gracefully.') return self.async_raise(ThreadTerminationError)
[ "def", "kill", "(", "self", ")", ":", "self", ".", "_killed", ".", "set", "(", ")", "if", "not", "self", ".", "is_alive", "(", ")", ":", "logging", ".", "debug", "(", "'Cannot kill thread that is no longer running.'", ")", "return", "if", "not", "self", ...
Terminates the current thread by raising an error.
[ "Terminates", "the", "current", "thread", "by", "raising", "an", "error", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L193-L203
240,787
google/openhtf
openhtf/util/threads.py
KillableThread.async_raise
def async_raise(self, exc_type): """Raise the exception.""" # Should only be called on a started thread, so raise otherwise. assert self.ident is not None, 'Only started threads have thread identifier' # If the thread has died we don't want to raise an exception so log. if not self.is_alive(): _LOG.debug('Not raising %s because thread %s (%s) is not alive', exc_type, self.name, self.ident) return result = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(self.ident), ctypes.py_object(exc_type)) if result == 0 and self.is_alive(): # Don't raise an exception an error unnecessarily if the thread is dead. raise ValueError('Thread ID was invalid.', self.ident) elif result > 1: # Something bad happened, call with a NULL exception to undo. ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, None) raise RuntimeError('Error: PyThreadState_SetAsyncExc %s %s (%s) %s' % ( exc_type, self.name, self.ident, result))
python
def async_raise(self, exc_type): # Should only be called on a started thread, so raise otherwise. assert self.ident is not None, 'Only started threads have thread identifier' # If the thread has died we don't want to raise an exception so log. if not self.is_alive(): _LOG.debug('Not raising %s because thread %s (%s) is not alive', exc_type, self.name, self.ident) return result = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(self.ident), ctypes.py_object(exc_type)) if result == 0 and self.is_alive(): # Don't raise an exception an error unnecessarily if the thread is dead. raise ValueError('Thread ID was invalid.', self.ident) elif result > 1: # Something bad happened, call with a NULL exception to undo. ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, None) raise RuntimeError('Error: PyThreadState_SetAsyncExc %s %s (%s) %s' % ( exc_type, self.name, self.ident, result))
[ "def", "async_raise", "(", "self", ",", "exc_type", ")", ":", "# Should only be called on a started thread, so raise otherwise.", "assert", "self", ".", "ident", "is", "not", "None", ",", "'Only started threads have thread identifier'", "# If the thread has died we don't want to ...
Raise the exception.
[ "Raise", "the", "exception", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/threads.py#L205-L225
240,788
google/openhtf
openhtf/util/logs.py
get_record_logger_for
def get_record_logger_for(test_uid): """Return the child logger associated with the specified test UID.""" htf_logger = logging.getLogger(RECORD_LOGGER_PREFIX) record_logger = HtfTestLogger('.'.join(((RECORD_LOGGER_PREFIX, test_uid)))) record_logger.parent = htf_logger return record_logger
python
def get_record_logger_for(test_uid): htf_logger = logging.getLogger(RECORD_LOGGER_PREFIX) record_logger = HtfTestLogger('.'.join(((RECORD_LOGGER_PREFIX, test_uid)))) record_logger.parent = htf_logger return record_logger
[ "def", "get_record_logger_for", "(", "test_uid", ")", ":", "htf_logger", "=", "logging", ".", "getLogger", "(", "RECORD_LOGGER_PREFIX", ")", "record_logger", "=", "HtfTestLogger", "(", "'.'", ".", "join", "(", "(", "(", "RECORD_LOGGER_PREFIX", ",", "test_uid", "...
Return the child logger associated with the specified test UID.
[ "Return", "the", "child", "logger", "associated", "with", "the", "specified", "test", "UID", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L161-L166
240,789
google/openhtf
openhtf/util/logs.py
initialize_record_handler
def initialize_record_handler(test_uid, test_record, notify_update): """Initialize the record handler for a test. For each running test, we attach a record handler to the top-level OpenHTF logger. The handler will append OpenHTF logs to the test record, while filtering out logs that are specific to any other test run. """ htf_logger = logging.getLogger(LOGGER_PREFIX) htf_logger.addHandler(RecordHandler(test_uid, test_record, notify_update))
python
def initialize_record_handler(test_uid, test_record, notify_update): htf_logger = logging.getLogger(LOGGER_PREFIX) htf_logger.addHandler(RecordHandler(test_uid, test_record, notify_update))
[ "def", "initialize_record_handler", "(", "test_uid", ",", "test_record", ",", "notify_update", ")", ":", "htf_logger", "=", "logging", ".", "getLogger", "(", "LOGGER_PREFIX", ")", "htf_logger", ".", "addHandler", "(", "RecordHandler", "(", "test_uid", ",", "test_r...
Initialize the record handler for a test. For each running test, we attach a record handler to the top-level OpenHTF logger. The handler will append OpenHTF logs to the test record, while filtering out logs that are specific to any other test run.
[ "Initialize", "the", "record", "handler", "for", "a", "test", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L169-L177
240,790
google/openhtf
openhtf/util/logs.py
log_once
def log_once(log_func, msg, *args, **kwargs): """"Logs a message only once.""" if msg not in _LOG_ONCE_SEEN: log_func(msg, *args, **kwargs) # Key on the message, ignoring args. This should fit most use cases. _LOG_ONCE_SEEN.add(msg)
python
def log_once(log_func, msg, *args, **kwargs): "if msg not in _LOG_ONCE_SEEN: log_func(msg, *args, **kwargs) # Key on the message, ignoring args. This should fit most use cases. _LOG_ONCE_SEEN.add(msg)
[ "def", "log_once", "(", "log_func", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "msg", "not", "in", "_LOG_ONCE_SEEN", ":", "log_func", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Key on the message, ignorin...
Logs a message only once.
[ "Logs", "a", "message", "only", "once", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L188-L193
240,791
google/openhtf
openhtf/util/logs.py
configure_logging
def configure_logging(): """One-time initialization of loggers. See module docstring for more info.""" # Define the top-level logger. htf_logger = logging.getLogger(LOGGER_PREFIX) htf_logger.propagate = False htf_logger.setLevel(logging.DEBUG) # By default, don't print any logs to the CLI. if CLI_LOGGING_VERBOSITY == 0: htf_logger.addHandler(logging.NullHandler()) return if CLI_LOGGING_VERBOSITY == 1: logging_level = logging.INFO else: logging_level = logging.DEBUG # Configure a handler to print to the CLI. cli_handler = KillableThreadSafeStreamHandler(stream=sys.stdout) cli_handler.setFormatter(CliFormatter()) cli_handler.setLevel(logging_level) cli_handler.addFilter(MAC_FILTER) htf_logger.addHandler(cli_handler) # Suppress CLI logging if the --quiet flag is used, or while CLI_QUIET is set # in the console_output module. cli_handler.addFilter(console_output.CliQuietFilter())
python
def configure_logging(): # Define the top-level logger. htf_logger = logging.getLogger(LOGGER_PREFIX) htf_logger.propagate = False htf_logger.setLevel(logging.DEBUG) # By default, don't print any logs to the CLI. if CLI_LOGGING_VERBOSITY == 0: htf_logger.addHandler(logging.NullHandler()) return if CLI_LOGGING_VERBOSITY == 1: logging_level = logging.INFO else: logging_level = logging.DEBUG # Configure a handler to print to the CLI. cli_handler = KillableThreadSafeStreamHandler(stream=sys.stdout) cli_handler.setFormatter(CliFormatter()) cli_handler.setLevel(logging_level) cli_handler.addFilter(MAC_FILTER) htf_logger.addHandler(cli_handler) # Suppress CLI logging if the --quiet flag is used, or while CLI_QUIET is set # in the console_output module. cli_handler.addFilter(console_output.CliQuietFilter())
[ "def", "configure_logging", "(", ")", ":", "# Define the top-level logger.", "htf_logger", "=", "logging", ".", "getLogger", "(", "LOGGER_PREFIX", ")", "htf_logger", ".", "propagate", "=", "False", "htf_logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", ...
One-time initialization of loggers. See module docstring for more info.
[ "One", "-", "time", "initialization", "of", "loggers", ".", "See", "module", "docstring", "for", "more", "info", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L319-L346
240,792
google/openhtf
openhtf/util/logs.py
RecordHandler.emit
def emit(self, record): """Save a logging.LogRecord to our test record. Logs carry useful metadata such as the logger name and level information. We capture this in a structured format in the test record to enable filtering by client applications. Args: record: A logging.LogRecord to record. """ try: message = self.format(record) log_record = LogRecord( record.levelno, record.name, os.path.basename(record.pathname), record.lineno, int(record.created * 1000), message, ) self._test_record.add_log_record(log_record) self._notify_update() except Exception: # pylint: disable=broad-except self.handleError(record)
python
def emit(self, record): try: message = self.format(record) log_record = LogRecord( record.levelno, record.name, os.path.basename(record.pathname), record.lineno, int(record.created * 1000), message, ) self._test_record.add_log_record(log_record) self._notify_update() except Exception: # pylint: disable=broad-except self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "message", "=", "self", ".", "format", "(", "record", ")", "log_record", "=", "LogRecord", "(", "record", ".", "levelno", ",", "record", ".", "name", ",", "os", ".", "path", ".", "bas...
Save a logging.LogRecord to our test record. Logs carry useful metadata such as the logger name and level information. We capture this in a structured format in the test record to enable filtering by client applications. Args: record: A logging.LogRecord to record.
[ "Save", "a", "logging", ".", "LogRecord", "to", "our", "test", "record", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L269-L288
240,793
google/openhtf
openhtf/util/logs.py
CliFormatter.format
def format(self, record): """Format the record as tersely as possible but preserve info.""" super(CliFormatter, self).format(record) localized_time = datetime.datetime.fromtimestamp(record.created) terse_time = localized_time.strftime(u'%H:%M:%S') terse_level = record.levelname[0] terse_name = record.name.split('.')[-1] match = RECORD_LOGGER_RE.match(record.name) if match: # Figure out which OpenHTF subsystem the record came from. subsys_match = SUBSYSTEM_LOGGER_RE.match(record.name) if subsys_match: terse_name = '<{subsys}: {id}>'.format( subsys=subsys_match.group('subsys'), id=subsys_match.group('id')) else: # Fall back to using the last five characters of the test UUID. terse_name = '<test %s>' % match.group('test_uid')[-5:] return '{lvl} {time} {logger} - {msg}'.format(lvl=terse_level, time=terse_time, logger=terse_name, msg=record.message)
python
def format(self, record): super(CliFormatter, self).format(record) localized_time = datetime.datetime.fromtimestamp(record.created) terse_time = localized_time.strftime(u'%H:%M:%S') terse_level = record.levelname[0] terse_name = record.name.split('.')[-1] match = RECORD_LOGGER_RE.match(record.name) if match: # Figure out which OpenHTF subsystem the record came from. subsys_match = SUBSYSTEM_LOGGER_RE.match(record.name) if subsys_match: terse_name = '<{subsys}: {id}>'.format( subsys=subsys_match.group('subsys'), id=subsys_match.group('id')) else: # Fall back to using the last five characters of the test UUID. terse_name = '<test %s>' % match.group('test_uid')[-5:] return '{lvl} {time} {logger} - {msg}'.format(lvl=terse_level, time=terse_time, logger=terse_name, msg=record.message)
[ "def", "format", "(", "self", ",", "record", ")", ":", "super", "(", "CliFormatter", ",", "self", ")", ".", "format", "(", "record", ")", "localized_time", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "record", ".", "created", ")", "terse...
Format the record as tersely as possible but preserve info.
[ "Format", "the", "record", "as", "tersely", "as", "possible", "but", "preserve", "info", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/logs.py#L294-L315
240,794
google/openhtf
openhtf/output/callbacks/mfg_inspector.py
_send_mfg_inspector_request
def _send_mfg_inspector_request(envelope_data, credentials, destination_url): """Send upload http request. Intended to be run in retry loop.""" logging.info('Uploading result...') http = httplib2.Http() if credentials.access_token_expired: credentials.refresh(http) credentials.authorize(http) resp, content = http.request(destination_url, 'POST', envelope_data) try: result = json.loads(content) except Exception: logging.debug('Upload failed with response %s: %s', resp, content) raise UploadFailedError(resp, content) if resp.status != 200: logging.debug('Upload failed: %s', result) raise UploadFailedError(result['error'], result) return result
python
def _send_mfg_inspector_request(envelope_data, credentials, destination_url): logging.info('Uploading result...') http = httplib2.Http() if credentials.access_token_expired: credentials.refresh(http) credentials.authorize(http) resp, content = http.request(destination_url, 'POST', envelope_data) try: result = json.loads(content) except Exception: logging.debug('Upload failed with response %s: %s', resp, content) raise UploadFailedError(resp, content) if resp.status != 200: logging.debug('Upload failed: %s', result) raise UploadFailedError(result['error'], result) return result
[ "def", "_send_mfg_inspector_request", "(", "envelope_data", ",", "credentials", ",", "destination_url", ")", ":", "logging", ".", "info", "(", "'Uploading result...'", ")", "http", "=", "httplib2", ".", "Http", "(", ")", "if", "credentials", ".", "access_token_exp...
Send upload http request. Intended to be run in retry loop.
[ "Send", "upload", "http", "request", ".", "Intended", "to", "be", "run", "in", "retry", "loop", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L27-L48
240,795
google/openhtf
openhtf/output/callbacks/mfg_inspector.py
send_mfg_inspector_data
def send_mfg_inspector_data(inspector_proto, credentials, destination_url): """Upload MfgEvent to steam_engine.""" envelope = guzzle_pb2.TestRunEnvelope() envelope.payload = zlib.compress(inspector_proto.SerializeToString()) envelope.payload_type = guzzle_pb2.COMPRESSED_MFG_EVENT envelope_data = envelope.SerializeToString() for _ in xrange(5): try: result = _send_mfg_inspector_request( envelope_data, credentials, destination_url) return result except UploadFailedError: time.sleep(1) logging.critical( 'Could not upload to mfg-inspector after 5 attempts. Giving up.') return {}
python
def send_mfg_inspector_data(inspector_proto, credentials, destination_url): envelope = guzzle_pb2.TestRunEnvelope() envelope.payload = zlib.compress(inspector_proto.SerializeToString()) envelope.payload_type = guzzle_pb2.COMPRESSED_MFG_EVENT envelope_data = envelope.SerializeToString() for _ in xrange(5): try: result = _send_mfg_inspector_request( envelope_data, credentials, destination_url) return result except UploadFailedError: time.sleep(1) logging.critical( 'Could not upload to mfg-inspector after 5 attempts. Giving up.') return {}
[ "def", "send_mfg_inspector_data", "(", "inspector_proto", ",", "credentials", ",", "destination_url", ")", ":", "envelope", "=", "guzzle_pb2", ".", "TestRunEnvelope", "(", ")", "envelope", ".", "payload", "=", "zlib", ".", "compress", "(", "inspector_proto", ".", ...
Upload MfgEvent to steam_engine.
[ "Upload", "MfgEvent", "to", "steam_engine", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L51-L69
240,796
google/openhtf
openhtf/output/callbacks/mfg_inspector.py
MfgInspector._convert
def _convert(self, test_record_obj): """Convert and cache a test record to a mfg-inspector proto.""" if self._cached_proto is None: self._cached_proto = self._converter(test_record_obj) return self._cached_proto
python
def _convert(self, test_record_obj): if self._cached_proto is None: self._cached_proto = self._converter(test_record_obj) return self._cached_proto
[ "def", "_convert", "(", "self", ",", "test_record_obj", ")", ":", "if", "self", ".", "_cached_proto", "is", "None", ":", "self", ".", "_cached_proto", "=", "self", ".", "_converter", "(", "test_record_obj", ")", "return", "self", ".", "_cached_proto" ]
Convert and cache a test record to a mfg-inspector proto.
[ "Convert", "and", "cache", "a", "test", "record", "to", "a", "mfg", "-", "inspector", "proto", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L174-L180
240,797
google/openhtf
openhtf/output/callbacks/mfg_inspector.py
MfgInspector.save_to_disk
def save_to_disk(self, filename_pattern=None): """Returns a callback to convert test record to proto and save to disk.""" if not self._converter: raise RuntimeError( 'Must set _converter on subclass or via set_converter before calling ' 'save_to_disk.') pattern = filename_pattern or self._default_filename_pattern if not pattern: raise RuntimeError( 'Must specify provide a filename_pattern or set a ' '_default_filename_pattern on subclass.') def save_to_disk_callback(test_record_obj): proto = self._convert(test_record_obj) output_to_file = callbacks.OutputToFile(pattern) with output_to_file.open_output_file(test_record_obj) as outfile: outfile.write(proto.SerializeToString()) return save_to_disk_callback
python
def save_to_disk(self, filename_pattern=None): if not self._converter: raise RuntimeError( 'Must set _converter on subclass or via set_converter before calling ' 'save_to_disk.') pattern = filename_pattern or self._default_filename_pattern if not pattern: raise RuntimeError( 'Must specify provide a filename_pattern or set a ' '_default_filename_pattern on subclass.') def save_to_disk_callback(test_record_obj): proto = self._convert(test_record_obj) output_to_file = callbacks.OutputToFile(pattern) with output_to_file.open_output_file(test_record_obj) as outfile: outfile.write(proto.SerializeToString()) return save_to_disk_callback
[ "def", "save_to_disk", "(", "self", ",", "filename_pattern", "=", "None", ")", ":", "if", "not", "self", ".", "_converter", ":", "raise", "RuntimeError", "(", "'Must set _converter on subclass or via set_converter before calling '", "'save_to_disk.'", ")", "pattern", "=...
Returns a callback to convert test record to proto and save to disk.
[ "Returns", "a", "callback", "to", "convert", "test", "record", "to", "proto", "and", "save", "to", "disk", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L182-L202
240,798
google/openhtf
openhtf/output/callbacks/mfg_inspector.py
MfgInspector.upload
def upload(self): """Returns a callback to convert a test record to a proto and upload.""" if not self._converter: raise RuntimeError( 'Must set _converter on subclass or via set_converter before calling ' 'upload.') if not self.credentials: raise RuntimeError('Must provide credentials to use upload callback.') def upload_callback(test_record_obj): proto = self._convert(test_record_obj) self.upload_result = send_mfg_inspector_data( proto, self.credentials, self.destination_url) return upload_callback
python
def upload(self): if not self._converter: raise RuntimeError( 'Must set _converter on subclass or via set_converter before calling ' 'upload.') if not self.credentials: raise RuntimeError('Must provide credentials to use upload callback.') def upload_callback(test_record_obj): proto = self._convert(test_record_obj) self.upload_result = send_mfg_inspector_data( proto, self.credentials, self.destination_url) return upload_callback
[ "def", "upload", "(", "self", ")", ":", "if", "not", "self", ".", "_converter", ":", "raise", "RuntimeError", "(", "'Must set _converter on subclass or via set_converter before calling '", "'upload.'", ")", "if", "not", "self", ".", "credentials", ":", "raise", "Run...
Returns a callback to convert a test record to a proto and upload.
[ "Returns", "a", "callback", "to", "convert", "a", "test", "record", "to", "a", "proto", "and", "upload", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/output/callbacks/mfg_inspector.py#L204-L219
240,799
google/openhtf
openhtf/plugs/usb/shell_service.py
AsyncCommandHandle._writer_thread_proc
def _writer_thread_proc(self, is_raw): """Write as long as the stream is not closed.""" # If we're not in raw mode, do line-buffered reads to play nicer with # potential interactive uses, max of MAX_ADB_DATA, since anything we write # to the stream will get packetized to that size anyway. # # Loop until our stream gets closed, which will cause one of these # operations to raise. Since we're in a separate thread, it'll just get # ignored, which is what we want. reader = self.stdin.read if is_raw else self.stdin.readline while not self.stream.is_closed(): self.stream.write(reader(adb_protocol.MAX_ADB_DATA))
python
def _writer_thread_proc(self, is_raw): # If we're not in raw mode, do line-buffered reads to play nicer with # potential interactive uses, max of MAX_ADB_DATA, since anything we write # to the stream will get packetized to that size anyway. # # Loop until our stream gets closed, which will cause one of these # operations to raise. Since we're in a separate thread, it'll just get # ignored, which is what we want. reader = self.stdin.read if is_raw else self.stdin.readline while not self.stream.is_closed(): self.stream.write(reader(adb_protocol.MAX_ADB_DATA))
[ "def", "_writer_thread_proc", "(", "self", ",", "is_raw", ")", ":", "# If we're not in raw mode, do line-buffered reads to play nicer with", "# potential interactive uses, max of MAX_ADB_DATA, since anything we write", "# to the stream will get packetized to that size anyway.", "#", "# Loop ...
Write as long as the stream is not closed.
[ "Write", "as", "long", "as", "the", "stream", "is", "not", "closed", "." ]
655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/shell_service.py#L132-L143