code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
try:
response = self._client.readline()
self.log.debug('Snippet received: %s', response)
return response
except socket.error as e:
raise Error(
self._ad,
'Encountered socket error reading RPC response "%s"' % e) | def _client_receive(self) | Receives the server's response of an Rpc message.
Returns:
Raw byte string of the response.
Raises:
Error: a socket error occurred during the read. | 7.975823 | 6.708767 | 1.188866 |
if not uid:
uid = self.uid
self._client_send(json.dumps({'cmd': command, 'uid': uid}))
return self._client_receive() | def _cmd(self, command, uid=None) | Send a command to the server.
Args:
command: str, The name of the command to execute.
uid: int, the uid of the session to send the command to.
Returns:
The line that was written back. | 3.739518 | 4.489551 | 0.832938 |
with self._lock:
apiid = next(self._counter)
data = {'id': apiid, 'method': method, 'params': args}
request = json.dumps(data)
self._client_send(request)
response = self._client_receive()
if not response:
raise ProtocolErro... | def _rpc(self, method, *args) | Sends an rpc to the app.
Args:
method: str, The name of the method to execute.
args: any, The args of the method.
Returns:
The result of the rpc.
Raises:
ProtocolError: Something went wrong with the protocol.
ApiError: The rpc went t... | 2.915837 | 2.922246 | 0.997807 |
version_codename = self._ad.adb.getprop('ro.build.version.codename')
sdk_version = int(self._ad.adb.getprop('ro.build.version.sdk'))
# we check version_codename in addition to sdk_version because P builds
# in development report sdk_version 27, but still enforce the blacklist.
... | def disable_hidden_api_blacklist(self) | If necessary and possible, disables hidden api blacklist. | 6.758545 | 6.316612 | 1.069964 |
self._ad.load_snippet(name='snippet', package=self._package)
console_env['snippet'] = self._ad.snippet
console_env['s'] = self._ad.snippet | def _start_services(self, console_env) | Overrides superclass. | 9.237067 | 8.153357 | 1.132916 |
if not self._has_data or 'sum' not in self.result['end']:
return None
bps = self.result['end']['sum']['bits_per_second']
return bps / 8 / 1024 / 1024 | def avg_rate(self) | Average receiving rate in MB/s over the entire run.
If the result is not from a success run, this property is None. | 5.390593 | 4.054221 | 1.329625 |
if not self._has_data or 'sum_received' not in self.result['end']:
return None
bps = self.result['end']['sum_received']['bits_per_second']
return bps / 8 / 1024 / 1024 | def avg_receive_rate(self) | Average receiving rate in MB/s over the entire run. This data may
not exist if iperf was interrupted.
If the result is not from a success run, this property is None. | 4.855193 | 3.836144 | 1.265644 |
if not self._has_data or 'sum_sent' not in self.result['end']:
return None
bps = self.result['end']['sum_sent']['bits_per_second']
return bps / 8 / 1024 / 1024 | def avg_send_rate(self) | Average sending rate in MB/s over the entire run. This data may
not exist if iperf was interrupted.
If the result is not from a success run, this property is None. | 4.967772 | 3.85492 | 1.288684 |
if self.started:
return
utils.create_dir(self.log_path)
if tag:
tag = tag + ','
out_file_name = "IPerfServer,{},{}{}.log".format(
self.port, tag, len(self.log_files))
full_out_path = os.path.join(self.log_path, out_file_name)
c... | def start(self, extra_args="", tag="") | Starts iperf server on specified port.
Args:
extra_args: A string representing extra arguments to start iperf
server with.
tag: Appended to log file name to identify logs from different
iperf runs. | 3.541956 | 3.304133 | 1.071977 |
final_configs = {}
if self._base_configs:
final_configs.update(self._base_configs)
if override_configs:
final_configs.update(override_configs)
if sniffer.Sniffer.CONFIG_KEY_CHANNEL in final_configs:
try:
subprocess.check_call(... | def _pre_capture_config(self, override_configs=None) | Utility function which configures the wireless interface per the
specified configurations. Operation is performed before every capture
start using baseline configurations (specified when sniffer initialized)
and override configurations specified here. | 3.180811 | 2.724904 | 1.167311 |
self._process = None
shutil.move(self._temp_capture_file_path, self._capture_file_path) | def _post_process(self) | Utility function which is executed after a capture is done. It
moves the capture file to the requested location. | 8.387543 | 4.568197 | 1.836073 |
if self._process is not None:
raise sniffer.InvalidOperationError(
"Trying to start a sniff while another is still running!")
capture_dir = os.path.join(self._logger.log_path,
"Sniffer-{}".format(self._interface))
os.mak... | def start_capture(self, override_configs=None,
additional_args=None, duration=None,
packet_count=None) | See base class documentation | 3.988077 | 3.988052 | 1.000006 |
if self._process is None:
raise sniffer.InvalidOperationError(
"Trying to stop a non-started process")
utils.stop_standing_subprocess(self._process, kill_signal=signal.SIGINT)
self._post_process() | def stop_capture(self) | See base class documentation | 9.448262 | 8.366454 | 1.129303 |
if self._process is None:
raise sniffer.InvalidOperationError(
"Trying to wait on a non-started process")
try:
utils.wait_for_standing_subprocess(self._process, timeout)
self._post_process()
except subprocess.TimeoutE... | def wait_for_capture(self, timeout=None) | See base class documentation | 6.387601 | 5.850891 | 1.091731 |
out = AdbProxy().forward('--list')
clean_lines = str(out, 'utf-8').strip().split('\n')
used_ports = []
for line in clean_lines:
tokens = line.split(' tcp:')
if len(tokens) != 3:
continue
used_ports.append(int(tokens[1]))
return used_ports | def list_occupied_adb_ports() | Lists all the host ports occupied by adb forward.
This is useful because adb will silently override the binding if an attempt
to bind to a port already used by adb was made, instead of throwing binding
error. So one should always check what ports adb is using before trying to
bind to a port with adb.
... | 3.835047 | 4.195797 | 0.914021 |
if timeout and timeout <= 0:
raise ValueError('Timeout is not a positive value: %s' % timeout)
try:
(ret, out, err) = utils.run_command(
args, shell=shell, timeout=timeout)
except psutil.TimeoutExpired:
raise AdbTimeoutError(
... | def _exec_cmd(self, args, shell, timeout, stderr) | Executes adb commands.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See subprocess.Popen() docs.
ti... | 2.746182 | 2.640002 | 1.04022 |
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
bufsize=1)
out = '[elided, processed via handler]'
try:
# Even if the process dies, stdout.readline still works
... | def _execute_and_process_stdout(self, args, shell, handler) | Executes adb commands and processes the stdout with a handler.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See... | 4.138667 | 4.065717 | 1.017943 |
args = args or ''
name = raw_name.replace('_', '-')
if shell:
args = utils.cli_cmd_to_string(args)
# Add quotes around "adb" in case the ADB path contains spaces. This
# is pretty common on Windows (e.g. Program Files).
if self.serial:
... | def _construct_adb_cmd(self, raw_name, args, shell) | Constructs an adb command with arguments for a subprocess call.
Args:
raw_name: string, the raw unsanitized name of the adb command to
format.
args: string or list of strings, arguments to the adb command.
See subprocess.Proc() documentation.
... | 2.529246 | 2.650087 | 0.954401 |
return self.shell(
['getprop', prop_name],
timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip() | def getprop(self, prop_name) | Get a property of the device.
This is a convenience wrapper for "adb shell getprop xxx".
Args:
prop_name: A string that is the name of the property to get.
Returns:
A string that is the value of the property, or None if the property
doesn't exist. | 6.547002 | 6.004227 | 1.090399 |
try:
output = self.shell(['command', '-v',
command]).decode('utf-8').strip()
return command in output
except AdbError:
# If the command doesn't exist, then 'command -v' can return
# an exit code > 1.
re... | def has_shell_command(self, command) | Checks to see if a given check command exists on the device.
Args:
command: A string that is the name of the command to check.
Returns:
A boolean that is True if the command exists and False otherwise. | 5.884919 | 6.791989 | 0.86645 |
if runner is None:
runner = DEFAULT_INSTRUMENTATION_RUNNER
if options is None:
options = {}
options_list = []
for option_key, option_value in options.items():
options_list.append('-e %s %s' % (option_key, option_value))
options_string... | def instrument(self, package, options=None, runner=None, handler=None) | Runs an instrumentation command on the device.
This is a convenience wrapper to avoid parameter formatting.
Example:
.. code-block:: python
device.instrument(
'com.my.package.test',
options = {
'class': 'com.my.package.test.Test... | 3.374677 | 3.178037 | 1.061875 |
my_msg = None
try:
_pyunit_proxy.assertEqual(first, second)
except AssertionError as e:
my_msg = str(e)
if msg:
my_msg = "%s %s" % (my_msg, msg)
# This raise statement is outside of the above except statement to prevent
# Python3's exception message from hav... | def assert_equal(first, second, msg=None, extras=None) | Assert the equality of objects, otherwise fail the test.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.
second: The second object to compare.
msg: A string that adds additional info abo... | 5.60096 | 6.393339 | 0.876062 |
context = _AssertRaisesContext(expected_exception, extras=extras)
return context | def assert_raises(expected_exception, extras=None, *args, **kwargs) | Assert that an exception is raised when a function is called.
If no exception is raised, test fail. If an exception is raised but not
of the expected type, the exception is let through.
This should only be used as a context manager:
with assert_raises(Exception):
func()
Args:
... | 5.984676 | 15.825037 | 0.378178 |
context = _AssertRaisesContext(
expected_exception, expected_regex, extras=extras)
return context | def assert_raises_regex(expected_exception,
expected_regex,
extras=None,
*args,
**kwargs) | Assert that an exception is raised when a function is called.
If no exception is raised, test fail. If an exception is raised but not
of the expected type, the exception is let through. If an exception of the
expected type is raised but the error message does not match the
expected_regex, test fail.
... | 5.317381 | 12.773215 | 0.416291 |
if timeout:
if timeout > MAX_TIMEOUT:
raise Error(
self._ad,
'Specified timeout %s is longer than max timeout %s.' %
(timeout, MAX_TIMEOUT))
# Convert to milliseconds for java side.
timeout_ms = int(... | def waitAndGet(self, event_name, timeout=DEFAULT_TIMEOUT) | Blocks until an event of the specified name has been received and
return the event, or timeout.
Args:
event_name: string, name of the event to get.
timeout: float, the number of seconds to wait before giving up.
Returns:
SnippetEvent, the oldest entry of the... | 4.444499 | 4.096648 | 1.084911 |
deadline = time.time() + timeout
while time.time() <= deadline:
# Calculate the max timeout for the next event rpc call.
rpc_timeout = deadline - time.time()
if rpc_timeout < 0:
break
# A single RPC call cannot exceed MAX_TIMEOUT.
... | def waitForEvent(self, event_name, predicate, timeout=DEFAULT_TIMEOUT) | Wait for an event of a specific name that satisfies the predicate.
This call will block until the expected event has been received or time
out.
The predicate function defines the condition the event is expected to
satisfy. It takes an event and returns True if the condition is
... | 4.140801 | 4.076609 | 1.015747 |
raw_events = self._event_client.eventGetAll(self._id, event_name)
return [snippet_event.from_dict(msg) for msg in raw_events] | def getAll(self, event_name) | Gets all the events of a certain name that have been received so
far. This is a non-blocking call.
Args:
callback_id: The id of the callback.
event_name: string, the name of the event to get.
Returns:
A list of SnippetEvent, each representing an event from t... | 8.626051 | 7.918792 | 1.089314 |
required_keys = [KEY_ADDRESS, KEY_MODEL, KEY_PORT, KEY_PATHS]
for key in required_keys:
if key not in config:
raise Error("Required key %s missing from config %s",
(key, config)) | def _validate_config(config) | Verifies that a config dict for an attenuator device is valid.
Args:
config: A dict that is the configuration for an attenuator device.
Raises:
attenuator.Error: A config is not valid. | 5.393656 | 5.051659 | 1.0677 |
objs = []
for s in serials:
objs.append(Monsoon(serial=s))
return objs | def get_instances(serials) | Create Monsoon instances from a list of serials.
Args:
serials: A list of Monsoon (integer) serials.
Returns:
A list of Monsoon objects. | 5.358485 | 5.42668 | 0.987433 |
# status packet format
STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH"
STATUS_FIELDS = [
"packetType",
"firmwareVersion",
"protocolVersion",
"mainFineCurrent",
"usbFineCurrent",
"auxFineCurrent",
... | def GetStatus(self) | Requests and waits for status.
Returns:
status dictionary. | 3.453069 | 3.449471 | 1.001043 |
if v == 0:
self._SendStruct("BBB", 0x01, 0x01, 0x00)
else:
self._SendStruct("BBB", 0x01, 0x01, int((v - 2.0) * 100)) | def SetVoltage(self, v) | Set the output voltage, 0 to disable. | 3.170421 | 3.066751 | 1.033804 |
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0x0a, val & 0xff)
self._SendStruct("BBB", 0x01, 0x0b, val >> 8) | def SetMaxCurrent(self, i) | Set the max output current. | 5.449091 | 5.13025 | 1.062149 |
if i < 0 or i > 8:
raise MonsoonError(("Target max current %sA, is out of acceptable "
"range [0, 8].") % i)
val = 1023 - int((i / 8) * 1023)
self._SendStruct("BBB", 0x01, 0x08, val & 0xff)
self._SendStruct("BBB", 0x01, 0x09, val >> 8) | def SetMaxPowerUpCurrent(self, i) | Set the max power up current. | 5.325202 | 5.263758 | 1.011673 |
while 1: # loop until we get data or a timeout
_bytes = self._ReadPacket()
if not _bytes:
return None
if len(_bytes) < 4 + 8 + 1 or _bytes[0] < 0x20 or _bytes[0] > 0x2F:
logging.warning("Wanted data, dropped type=0x%02x, len=%d",
... | def CollectData(self) | Return some current samples. Call StartDataCollection() first. | 3.158224 | 3.129699 | 1.009114 |
data = struct.pack(fmt, *args)
data_len = len(data) + 1
checksum = (data_len + sum(bytearray(data))) % 256
out = struct.pack("B", data_len) + data + struct.pack("B", checksum)
self.ser.write(out) | def _SendStruct(self, fmt, *args) | Pack a struct (without length or checksum) and send it. | 2.5773 | 2.322634 | 1.109645 |
len_char = self.ser.read(1)
if not len_char:
logging.error("Reading from serial port timed out.")
return None
data_len = ord(len_char)
if not data_len:
return ""
result = self.ser.read(int(data_len))
result = bytearray(result)... | def _ReadPacket(self) | Read a single data record as a string (without length or checksum). | 2.754127 | 2.660593 | 1.035155 |
self.ser.flush()
flushed = 0
while True:
ready_r, ready_w, ready_x = select.select([self.ser], [],
[self.ser], 0)
if len(ready_x) > 0:
logging.error("Exception from serial port.")
... | def _FlushInput(self) | Flush all read data until no more available. | 3.947399 | 3.710784 | 1.063764 |
len_data_pt = len(self.data_points)
if len_data_pt == 0:
return 0
cur = sum(self.data_points) * 1000 / len_data_pt
return round(cur, self.sr) | def average_current(self) | Average current in the unit of mA. | 4.226754 | 3.736956 | 1.131069 |
charge = (sum(self.data_points) / self.hz) * 1000 / 3600
return round(charge, self.sr) | def total_charge(self) | Total charged used in the unit of mAh. | 8.273581 | 7.237081 | 1.143221 |
power = self.average_current * self.voltage
return round(power, self.sr) | def total_power(self) | Total power used. | 13.669625 | 11.753776 | 1.162999 |
lines = data_str.strip().split('\n')
err_msg = ("Invalid input string format. Is this string generated by "
"MonsoonData class?")
conditions = [
len(lines) <= 4, "Average Current:" not in lines[1],
"Voltage: " not in lines[2], "Total Power: " n... | def from_string(data_str) | Creates a MonsoonData object from a string representation generated
by __str__.
Args:
str: The string representation of a MonsoonData.
Returns:
A MonsoonData object. | 3.814585 | 3.627873 | 1.051466 |
if not monsoon_data:
raise MonsoonError("Attempting to write empty Monsoon data to "
"file, abort")
utils.create_dir(os.path.dirname(file_path))
with io.open(file_path, 'w', encoding='utf-8') as f:
for md in monsoon_data:
... | def save_to_text_file(monsoon_data, file_path) | Save multiple MonsoonData objects to a text file.
Args:
monsoon_data: A list of MonsoonData objects to write to a text
file.
file_path: The full path of the file to save to, including the file
name. | 3.649222 | 3.525793 | 1.035008 |
results = []
with io.open(file_path, 'r', encoding='utf-8') as f:
data_strs = f.read().split(MonsoonData.delimiter)
for data_str in data_strs:
results.append(MonsoonData.from_string(data_str))
return results | def from_text_file(file_path) | Load MonsoonData objects from a text file generated by
MonsoonData.save_to_text_file.
Args:
file_path: The full path of the file load from, including the file
name.
Returns:
A list of MonsoonData objects. | 3.424327 | 2.625129 | 1.304441 |
msg = "Error! Expected {} timestamps, found {}.".format(
len(self._data_points), len(self._timestamps))
if len(self._data_points) != len(self._timestamps):
raise MonsoonError(msg) | def _validate_data(self) | Verifies that the data points contained in the class are valid. | 5.812568 | 4.756492 | 1.222028 |
self.offset = new_offset
self.data_points = self._data_points[self.offset:]
self.timestamps = self._timestamps[self.offset:] | def update_offset(self, new_offset) | Updates how many data points to skip in caculations.
Always use this function to update offset instead of directly setting
self.offset.
Args:
new_offset: The new offset. | 3.300457 | 3.37763 | 0.977152 |
result = []
for t, d in zip(self.timestamps, self.data_points):
result.append(t, round(d, self.lr))
return result | def get_data_with_timestamps(self) | Returns the data points with timestamps.
Returns:
A list of tuples in the format of (timestamp, data) | 6.348106 | 6.069279 | 1.045941 |
history_deque = collections.deque()
averages = []
for d in self.data_points:
history_deque.appendleft(d)
if len(history_deque) > n:
history_deque.pop()
avg = sum(history_deque) / len(history_deque)
averages.append(round(avg... | def get_average_record(self, n) | Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values. | 2.94988 | 3.073711 | 0.959713 |
if ramp:
self.mon.RampVoltage(self.mon.start_voltage, volt)
else:
self.mon.SetVoltage(volt) | def set_voltage(self, volt, ramp=False) | Sets the output voltage of monsoon.
Args:
volt: Voltage to set the output to.
ramp: If true, the output voltage will be increased gradually to
prevent tripping Monsoon overvoltage. | 3.748325 | 4.350166 | 0.861651 |
sys.stdout.flush()
voltage = self.mon.GetVoltage()
self.log.info("Taking samples at %dhz for %ds, voltage %.2fv.",
sample_hz, (sample_num / sample_hz), voltage)
sample_num += sample_offset
# Make sure state is normal
self.mon.StopDataCollect... | def take_samples(self, sample_hz, sample_num, sample_offset=0, live=False) | Take samples of the current value supplied by monsoon.
This is the actual measurement for power consumption. This function
blocks until the number of samples requested has been fulfilled.
Args:
hz: Number of points to take for every second.
sample_num: Number of samples... | 5.353123 | 5.184853 | 1.032454 |
state_lookup = {"off": 0, "on": 1, "auto": 2}
state = state.lower()
if state in state_lookup:
current_state = self.mon.GetUsbPassthrough()
while (current_state != state_lookup[state]):
self.mon.SetUsbPassthrough(state_lookup[state])
... | def usb(self, state) | Sets the monsoon's USB passthrough mode. This is specific to the
USB port in front of the monsoon box which connects to the powered
device, NOT the USB that is used to talk to the monsoon itself.
"Off" means USB always off.
"On" means USB always on.
"Auto" means USB is automatic... | 2.742073 | 2.423341 | 1.131526 |
num = duration * hz
oset = offset * hz
data = None
self.usb("auto")
time.sleep(1)
with self.dut.handle_usb_disconnect():
time.sleep(1)
try:
data = self.take_samples(hz, num, sample_offset=oset)
if not data:
... | def measure_power(self, hz, duration, tag, offset=30) | Measure power consumption of the attached device.
Because it takes some time for the device to calm down after the usb
connection is cut, an offset is set for each measurement. The default
is 30s. The total time taken to measure will be (duration + offset).
Args:
hz: Number... | 6.319917 | 5.847809 | 1.080732 |
objs = []
for c in configs:
sniffer_type = c["Type"]
sniffer_subtype = c["SubType"]
interface = c["Interface"]
base_configs = c["BaseConfigs"]
module_name = "mobly.controllers.sniffer_lib.{}.{}".format(
sniffer_type, sniffer_subtype)
module = impo... | def create(configs) | Initializes the sniffer structures based on the JSON configuration. The
expected keys are:
* Type: A first-level type of sniffer. Planned to be 'local' for
sniffers running on the local machine, or 'remote' for sniffers
running remotely.
* SubType: The specific sniffer type ... | 3.753265 | 2.627586 | 1.428408 |
if uid is None:
raise ValueError('UID cannot be None.')
def decorate(test_func):
@functools.wraps(test_func)
def wrapper(*args, **kwargs):
return test_func(*args, **kwargs)
setattr(wrapper, 'uid', uid)
return wrapper
return decorate | def uid(uid) | Decorator specifying the unique identifier (UID) of a test case.
The UID will be recorded in the test's record when executed by Mobly.
If you use any other decorator for the test method, you may want to use
this as the outer-most one.
Note a common UID system is the Universal Unitque Identifier (UUID... | 2.431311 | 2.405394 | 1.010774 |
try:
self.details = str(content)
except UnicodeEncodeError:
if sys.version_info < (3, 0):
# If Py2 threw encode error, convert to unicode.
self.details = unicode(content)
else:
# We should never hit this in Py3,... | def _set_details(self, content) | Sets the `details` field.
Args:
content: the content to extract details from. | 5.293218 | 5.286735 | 1.001226 |
with io.open(utils.abs_path(path), 'r', encoding='utf-8') as f:
conf = yaml.load(f)
return conf | def _load_config_file(path) | Loads a test config file.
The test config file has to be in YAML format.
Args:
path: A string that is the full path to the config file, including the
file name.
Returns:
A dict that represents info in the config file. | 3.752618 | 4.623056 | 0.811718 |
# Should not load snippet with the same name more than once.
if name in self._snippet_clients:
raise Error(
self,
'Name "%s" is already registered with package "%s", it cannot '
'be used again.' %
(name, self._snippet_c... | def add_snippet_client(self, name, package) | Adds a snippet client to the management.
Args:
name: string, the attribute name to which to attach the snippet
client. E.g. `name='maps'` attaches the snippet client to
`ad.maps`.
package: string, the package name of the snippet apk to connect to.
... | 3.599546 | 3.505978 | 1.026688 |
if name not in self._snippet_clients:
raise Error(self._device, MISSING_SNIPPET_CLIENT_MSG % name)
client = self._snippet_clients.pop(name)
client.stop_app() | def remove_snippet_client(self, name) | Removes a snippet client from management.
Args:
name: string, the name of the snippet client to remove.
Raises:
Error: if no snippet client is managed under the specified name. | 4.408646 | 4.543736 | 0.970269 |
for client in self._snippet_clients.values():
if not client.is_alive:
self._device.log.debug('Starting SnippetClient<%s>.',
client.package)
client.start_app_and_connect()
else:
self._device.lo... | def start(self) | Starts all the snippet clients under management. | 5.799239 | 4.486761 | 1.292522 |
for client in self._snippet_clients.values():
if client.is_alive:
self._device.log.debug('Stopping SnippetClient<%s>.',
client.package)
client.stop_app()
else:
self._device.log.debug(
... | def stop(self) | Stops all the snippet clients under management. | 5.00387 | 3.851289 | 1.299271 |
for client in self._snippet_clients.values():
self._device.log.debug(
'Clearing host port %d of SnippetClient<%s>.',
client.host_port, client.package)
client.clear_host_port() | def pause(self) | Pauses all the snippet clients under management.
This clears the host port of a client because a new port will be
allocated in `resume`. | 10.335026 | 5.664397 | 1.824559 |
for client in self._snippet_clients.values():
# Resume is only applicable if a client is alive and does not have
# a host port.
if client.is_alive and client.host_port is None:
self._device.log.debug('Resuming SnippetClient<%s>.',
... | def resume(self) | Resumes all paused snippet clients. | 5.733519 | 4.741592 | 1.209197 |
while self.started:
event_obj = None
event_name = None
try:
event_obj = self._sl4a.eventWait(50000)
except:
if self.started:
print("Exception happened during polling.")
print(tracebac... | def poll_events(self) | Continuously polls all types of events from sl4a.
Events are sorted by name and store in separate queues.
If there are registered handlers, the handlers will be called with
corresponding event immediately upon event discovery, and the event
won't be stored. If exceptions occur, stop the... | 3.546865 | 3.321396 | 1.067884 |
if self.started:
raise IllegalStateError(("Can't register service after polling is"
" started"))
self.lock.acquire()
try:
if event_name in self.handlers:
raise DuplicateError('A handler for {} already exists'.f... | def register_handler(self, handler, event_name, args) | Registers an event handler.
One type of event can only have one event handler associated with it.
Args:
handler: The event handler function to be registered.
event_name: Name of the event the handler is for.
args: User arguments to be passed to the handler when it's... | 3.899937 | 3.460111 | 1.127113 |
if not self.started:
self.started = True
self.executor = ThreadPoolExecutor(max_workers=32)
self.poller = self.executor.submit(self.poll_events)
else:
raise IllegalStateError("Dispatcher is already started.") | def start(self) | Starts the event dispatcher.
Initiates executor and start polling events.
Raises:
IllegalStateError: Can't start a dispatcher again when it's already
running. | 4.321346 | 3.033018 | 1.424768 |
if not self.started:
return
self.started = False
self.clear_all_events()
# At this point, the sl4a apk is destroyed and nothing is listening on
# the socket. Avoid sending any sl4a commands; just clean up the socket
# and return.
self._sl4a.di... | def clean_up(self) | Clean up and release resources after the event dispatcher polling
loop has been broken.
The following things happen:
1. Clear all events and flags.
2. Close the sl4a client the event_dispatcher object holds.
3. Shut down executor without waiting. | 9.719412 | 7.549861 | 1.287363 |
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
e_queue = self.get_event_q(event_name)
if not e_queue:
raise TypeError("Failed to get an event queue for {}".format(
event_name))
... | def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT) | Pop an event from its queue.
Return and remove the oldest entry of an event.
Block until an event of specified name is available or
times out if timeout is set.
Args:
event_name: Name of the event to be popped.
timeout: Number of seconds to wait when event is no... | 3.84859 | 3.504517 | 1.09818 |
deadline = time.time() + timeout
while True:
event = None
try:
event = self.pop_event(event_name, 1)
except queue.Empty:
pass
if event and predicate(event, *args, **kwargs):
return event
... | def wait_for_event(self,
event_name,
predicate,
timeout=DEFAULT_TIMEOUT,
*args,
**kwargs) | Wait for an event that satisfies a predicate to appear.
Continuously pop events of a particular name and check against the
predicate until an event that satisfies the predicate is popped or
timed out. Note this will remove all the events of the same name that
do not satisfy the predicat... | 2.444282 | 2.586117 | 0.945155 |
if not self.started:
raise IllegalStateError(
"Dispatcher needs to be started before popping.")
deadline = time.time() + timeout
while True:
#TODO: fix the sleep loop
results = self._match_and_pop(regex_pattern)
if len(resu... | def pop_events(self, regex_pattern, timeout) | Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
... | 4.145346 | 3.500934 | 1.184069 |
results = []
self.lock.acquire()
for name in self.event_dict.keys():
if re.match(regex_pattern, name):
q = self.event_dict[name]
if q:
try:
results.append(q.get(False))
except:
... | def _match_and_pop(self, regex_pattern) | Pop one event from each of the event queues whose names
match (in a sense of regular expression) regex_pattern. | 2.902293 | 2.236068 | 1.297945 |
self.lock.acquire()
if not event_name in self.event_dict or self.event_dict[
event_name] is None:
self.event_dict[event_name] = queue.Queue()
self.lock.release()
event_queue = self.event_dict[event_name]
return event_queue | def get_event_q(self, event_name) | Obtain the queue storing events of the specified name.
If no event of this name has been polled, wait for one to.
Returns:
A queue storing all the events of the specified name.
None if timed out.
Raises:
queue.Empty: Raised if the queue does not exist and t... | 2.295891 | 2.409705 | 0.952768 |
handler, args = self.handlers[event_name]
self.executor.submit(handler, event_obj, *args) | def handle_subscribed_event(self, event_obj, event_name) | Execute the registered handler of an event.
Retrieve the handler and its arguments, and execute the handler in a
new thread.
Args:
event_obj: Json object of the event.
event_name: Name of the event to call handler for. | 4.403926 | 5.486266 | 0.802718 |
if cond:
cond.wait(cond_timeout)
event = self.pop_event(event_name, event_timeout)
return event_handler(event, *user_args) | def _handle(self, event_handler, event_name, user_args, event_timeout,
cond, cond_timeout) | Pop an event of specified type and calls its handler on it. If
condition is not None, block until condition is met or timeout. | 3.109696 | 2.723754 | 1.141695 |
worker = self.executor.submit(self._handle, event_handler, event_name,
user_args, event_timeout, cond,
cond_timeout)
return worker | def handle_event(self,
event_handler,
event_name,
user_args,
event_timeout=None,
cond=None,
cond_timeout=None) | Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
event_handler: Handler for the event, which should take at least
... | 3.37001 | 3.718264 | 0.90634 |
if not self.started:
raise IllegalStateError(("Dispatcher needs to be started before "
"popping."))
results = []
try:
self.lock.acquire()
while True:
e = self.event_dict[event_name].get(block=False)... | def pop_all(self, event_name) | Return and remove all stored events of a specified name.
Pops all events from their queue. May miss the latest ones.
If no event is available, return immediately.
Args:
event_name: Name of the events to be popped.
Returns:
List of the desired events.
R... | 4.161123 | 3.44635 | 1.2074 |
self.lock.acquire()
try:
q = self.get_event_q(event_name)
q.queue.clear()
except queue.Empty:
return
finally:
self.lock.release() | def clear_events(self, event_name) | Clear all events of a particular name.
Args:
event_name: Name of the events to be popped. | 3.443454 | 3.637224 | 0.946726 |
self.lock.acquire()
self.event_dict.clear()
self.lock.release() | def clear_all_events(self) | Clear all event queues and their cached events. | 4.367799 | 4.498515 | 0.970942 |
return SnippetEvent(
callback_id=event_dict['callbackId'],
name=event_dict['name'],
creation_time=event_dict['time'],
data=event_dict['data']) | def from_dict(event_dict) | Create a SnippetEvent object from a dictionary.
Args:
event_dict: a dictionary representing an event.
Returns:
A SnippetEvent object. | 4.234366 | 4.393181 | 0.96385 |
full_path = abs_path(path)
if not os.path.exists(full_path):
try:
os.makedirs(full_path)
except OSError as e:
# ignore the error for dir already exist.
if e.errno != os.errno.EEXIST:
raise | def create_dir(path) | Creates a directory if it does not exist already.
Args:
path: The path of the directory to create. | 2.685294 | 3.296234 | 0.814655 |
if platform.system() == 'Windows' and not alias_path.endswith('.lnk'):
alias_path += '.lnk'
if os.path.lexists(alias_path):
os.remove(alias_path)
if platform.system() == 'Windows':
from win32com import client
shell = client.Dispatch('WScript.Shell')
shortcut = sh... | def create_alias(target_path, alias_path) | Creates an alias at 'alias_path' pointing to the file 'target_path'.
On Unix, this is implemented via symlink. On Windows, this is done by
creating a Windows shortcut file.
Args:
target_path: Destination path that the alias should point to.
alias_path: Path at which to create the new alias... | 1.766468 | 1.852397 | 0.953612 |
if isinstance(epoch_time, int):
try:
d = datetime.datetime.fromtimestamp(epoch_time / 1000)
return d.strftime("%m-%d-%Y %H:%M:%S ")
except ValueError:
return None | def epoch_to_human_time(epoch_time) | Converts an epoch timestamp to human readable time.
This essentially converts an output of get_current_epoch_time to an output
of get_current_human_time
Args:
epoch_time: An integer representing an epoch timestamp in milliseconds.
Returns:
A time string representing the input time.
... | 2.772766 | 2.848528 | 0.973403 |
tzoffset = int(time.timezone / 3600)
gmt = None
if tzoffset <= 0:
gmt = "GMT+{}".format(-tzoffset)
else:
gmt = "GMT-{}".format(tzoffset)
return GMT_to_olson[gmt] | def get_timezone_olson_id() | Return the Olson ID of the local (non-DST) timezone.
Returns:
A string representing one of the Olson IDs of the local (non-DST)
timezone. | 3.357615 | 3.798085 | 0.884028 |
file_list = []
for path in paths:
p = abs_path(path)
for dirPath, _, fileList in os.walk(p):
for fname in fileList:
name, ext = os.path.splitext(fname)
if file_predicate(name, ext):
file_list.append((dirPath, name, ext))
re... | def find_files(paths, file_predicate) | Locate files whose names and extensions match the given predicate in
the specified directories.
Args:
paths: A list of directory paths where to find the files.
file_predicate: A function that returns True if the file name and
extension are desired.
Returns:
A list of fi... | 2.321352 | 2.720913 | 0.853152 |
path = abs_path(f_path)
with io.open(path, 'rb') as f:
f_bytes = f.read()
base64_str = base64.b64encode(f_bytes).decode("utf-8")
return base64_str | def load_file_to_base64_str(f_path) | Loads the content of a file into a base64 string.
Args:
f_path: full path to the file including the file name.
Returns:
A base64 string representing the content of the file in utf-8 encoding. | 2.221691 | 2.658044 | 0.835837 |
for item in item_list:
if comparator(item, cond) and target_field in item:
return item[target_field]
return None | def find_field(item_list, cond, comparator, target_field) | Finds the value of a field in a dict object that satisfies certain
conditions.
Args:
item_list: A list of dict objects.
cond: A param that defines the condition.
comparator: A function that checks if an dict satisfies the condition.
target_field: Name of the field whose value to... | 2.330694 | 2.821178 | 0.826142 |
letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]
return ''.join(letters) | def rand_ascii_str(length) | Generates a random string of specified length, composed of ascii letters
and digits.
Args:
length: The number of characters in the string.
Returns:
The random string generated. | 3.631618 | 5.420127 | 0.670024 |
with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
# Start the load operations and mark each future with its params
future_to_params = {executor.submit(func, *p): p for p in param_list}
return_vals = []
for future in concurrent.futures.as_completed(future_to... | def concurrent_exec(func, param_list) | Executes a function with different parameters pseudo-concurrently.
This is basically a map function. Each element (should be an iterable) in
the param_list is unpacked and passed into the function. Due to Python's
GIL, there's no true concurrency. This is suited for IO-bound tasks.
Args:
func:... | 1.794188 | 1.934389 | 0.927522 |
# Only import psutil when actually needed.
# psutil may cause import error in certain env. This way the utils module
# doesn't crash upon import.
import psutil
if stdout is None:
stdout = subprocess.PIPE
if stderr is None:
stderr = subprocess.PIPE
process = psutil.Popen(... | def run_command(cmd,
stdout=None,
stderr=None,
shell=False,
timeout=None,
cwd=None,
env=None) | Runs a command in a subprocess.
This function is very similar to subprocess.check_output. The main
difference is that it returns the return code and std error output as well
as supporting a timeout parameter.
Args:
cmd: string or list of strings, the command to run.
See subprocess.... | 3.720519 | 3.768756 | 0.987201 |
logging.debug('Starting standing subprocess with: %s', cmd)
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=shell,
env=env)
# Leaving stdin open causes problems for input, e.g. breaking the
# ... | def start_standing_subprocess(cmd, shell=False, env=None) | Starts a long-running subprocess.
This is not a blocking call and the subprocess started by it should be
explicitly terminated with stop_standing_subprocess.
For short-running commands, you should use subprocess.check_call, which
blocks.
Args:
cmd: string, the command to start the subproc... | 4.827556 | 4.878857 | 0.989485 |
# Only import psutil when actually needed.
# psutil may cause import error in certain env. This way the utils module
# doesn't crash upon import.
import psutil
pid = proc.pid
logging.debug('Stopping standing subprocess %d', pid)
process = psutil.Process(pid)
failed = []
try:
... | def stop_standing_subprocess(proc) | Stops a subprocess started by start_standing_subprocess.
Before killing the process, we check if the process is running, if it has
terminated, Error is raised.
Catches and ignores the PermissionError which only happens on Macs.
Args:
proc: Subprocess to terminate.
Raises:
Error: ... | 2.857973 | 2.912343 | 0.981331 |
# Only import adb module if needed.
from mobly.controllers.android_device_lib import adb
for _ in range(MAX_PORT_ALLOCATION_RETRY):
port = portpicker.PickUnusedPort()
# Make sure adb is not using this port so we don't accidentally
# interrupt ongoing runs by trying to bind to th... | def get_available_host_port() | Gets a host port number available for adb forward.
Returns:
An integer representing a port number on the host available for adb
forward.
Raises:
Error: when no port is found after MAX_PORT_ALLOCATION_RETRY times. | 5.390495 | 4.418389 | 1.220014 |
lines = output.decode('utf-8').strip().splitlines()
results = []
for line in lines:
if re.search(regex, line):
results.append(line.strip())
return results | def grep(regex, output) | Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the expected pattern.
output:... | 2.261757 | 3.07797 | 0.734821 |
if isinstance(args, basestring):
# Return directly if it's already a string.
return args
return ' '.join([pipes.quote(arg) for arg in args]) | def cli_cmd_to_string(args) | Converts a cmd arg list to string.
Args:
args: list of strings, the arguments of a command.
Returns:
String representation of the command. | 3.939008 | 4.648649 | 0.847345 |
cmd = ' '.join(cmds)
proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
(out, err) = proc.communicate()
if not err:
return out
return err | def exe_cmd(*cmds) | Executes commands in a new shell. Directing stderr to PIPE.
This is fastboot's own exe_cmd because of its peculiar way of writing
non-error info to stderr.
Args:
cmds: A sequence of commands and arguments.
Returns:
The output of the command run.
Raises:
Exception: An erro... | 2.269266 | 3.168237 | 0.716255 |
required_attributes = ('create', 'destroy', 'MOBLY_CONTROLLER_CONFIG_NAME')
for attr in required_attributes:
if not hasattr(module, attr):
raise signals.ControllerError(
'Module %s missing required controller module attribute'
' %s.' % (module.__name__, a... | def verify_controller_module(module) | Verifies a module object follows the required interface for
controllers.
The interface is explained in the docstring of
`base_test.BaseTestClass.register_controller`.
Args:
module: An object that is a controller module. This is usually
imported with import statements or loaded by i... | 4.666199 | 3.993284 | 1.168512 |
verify_controller_module(module)
# Use the module's name as the ref name
module_ref_name = module.__name__.split('.')[-1]
if module_ref_name in self._controller_objects:
raise signals.ControllerError(
'Controller module %s has already been registered.... | def register_controller(self, module, required=True, min_number=1) | Loads a controller module and returns its loaded devices.
This is to be used in a mobly test class.
Args:
module: A module that follows the controller module interface.
required: A bool. If True, failing to register the specified
controller module raises excepti... | 3.123619 | 2.901958 | 1.076383 |
# TODO(xpconanfan): actually record these errors instead of just
# logging them.
for name, module in self._controller_modules.items():
logging.debug('Destroying %s.', name)
with expects.expect_no_raises(
'Exception occurred destroying %s.' % n... | def unregister_controllers(self) | Destroy controller objects and clear internal registry.
This will be called after each test class. | 8.542534 | 8.251526 | 1.035267 |
module = self._controller_modules[controller_module_name]
controller_info = None
try:
controller_info = module.get_info(
copy.copy(self._controller_objects[controller_module_name]))
except AttributeError:
logging.warning('No optional debug... | def _create_controller_info_record(self, controller_module_name) | Creates controller info record for a particular controller type.
Info is retrieved from all the controller objects spawned from the
specified module, using the controller module's `get_info` function.
Args:
controller_module_name: string, the name of the controller module
... | 4.237444 | 4.067768 | 1.041712 |
info_records = []
for controller_module_name in self._controller_objects.keys():
with expects.expect_no_raises(
'Failed to collect controller info from %s' %
controller_module_name):
record = self._create_controller_info_record... | def get_controller_info_records(self) | Get the info records for all the controller objects in the manager.
New info records for each controller object are created for every call
so the latest info is included.
Returns:
List of records.ControllerInfoRecord objects. Each opject conatins
the info of a type of c... | 4.156841 | 4.424856 | 0.93943 |
if d is None:
return d
op_types = ('create', 'delete', 'index', 'update')
if op_type not in op_types:
msg = 'Unknown operation type "{}", must be one of: {}'
raise Exception(msg.format(op_type, ', '.join(op_types)))
if 'id' not in d:
raise Exception('"id" key not f... | def dict_to_op(d, index_name, doc_type, op_type='index') | Create a bulk-indexing operation from the given dictionary. | 2.176985 | 2.167399 | 1.004423 |
if not isinstance(obj.test, str):
# TODO: can we handle this in the DB?
# Reftests used to use tuple indicies, which we can't support.
# This is fixed upstream, but we also need to handle it here to allow
# for older branches.
return
keys = [
'id',
'... | def to_dict(obj) | Create a filtered dict from the given object.
Note: This function is currently specific to the FailureLine model. | 8.172943 | 7.8581 | 1.040066 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.