text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_subnet(self, name): """Checks if the subnet exists. :param str name: name of the subnet :return: str - subnet id of the subnet :raises: `SubnetError` if group does not exist """
# Subnets only exist in VPCs, so we don't need to worry about # the EC2 Classic case here. subnets = self._vpc_connection.get_all_subnets( filters={'vpcId': self._vpc_id}) matching_subnets = [ subnet for subnet in subnets if name in [subnet.tags.get('Name'), subnet.id] ] if len(matching_subnets) == 0: raise SubnetError( "the specified subnet %s does not exist" % name) elif len(matching_subnets) == 1: return matching_subnets[0].id else: raise SubnetError( "the specified subnet name %s matches more than " "one subnet" % name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_image_id(self, image_id): """Finds an image id to a given id or name. :param str image_id: name or id of image :return: str - identifier of image """
if not self._images: connection = self._connect() self._images = connection.get_all_images() image_id_cloud = None for i in self._images: if i.id == image_id or i.name == image_id: image_id_cloud = i.id break if image_id_cloud: return image_id_cloud else: raise ImageError( "Could not find given image id `%s`" % image_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def migrate_cluster(cluster): """Called when loading a cluster when it comes from an older version of elasticluster"""
for old, new in [('_user_key_public', 'user_key_public'), ('_user_key_private', 'user_key_private'), ('_user_key_name', 'user_key_name'),]: if hasattr(cluster, old): setattr(cluster, new, getattr(cluster, old)) delattr(cluster, old) for kind, nodes in cluster.nodes.items(): for node in nodes: if hasattr(node, 'image'): image_id = getattr(node, 'image_id', None) or node.image setattr(node, 'image_id', image_id) delattr(node, 'image') # Possibly related to issue #129 if not hasattr(cluster, 'thread_pool_max_size'): cluster.thread_pool_max_size = 10 return cluster
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, name): """Retrieves the cluster by the given name. :param str name: name of the cluster (identifier) :return: instance of :py:class:`elasticluster.cluster.Cluster` that matches the given name """
if name not in self.clusters: raise ClusterNotFound("Cluster %s not found." % name) return self.clusters.get(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, cluster): """Deletes the cluster from memory. :param cluster: cluster to delete :type cluster: :py:class:`elasticluster.cluster.Cluster` """
if cluster.name not in self.clusters: raise ClusterNotFound( "Unable to delete non-existent cluster %s" % cluster.name) del self.clusters[cluster.name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all(self): """Retrieves all clusters from the persistent state. :return: list of :py:class:`elasticluster.cluster.Cluster` """
clusters = [] cluster_files = glob.glob("%s/*.%s" % (self.storage_path, self.file_ending)) for fname in cluster_files: try: name = fname[:-len(self.file_ending)-1] clusters.append(self.get(name)) except (ImportError, AttributeError) as ex: log.error("Unable to load cluster %s: `%s`", fname, ex) log.error("If cluster %s was created with a previous version of elasticluster, you may need to run `elasticluster migrate %s %s` to update it.", cluster_file, self.storage_path, fname) return clusters
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, cluster): """Deletes the cluster from persistent state. :param cluster: cluster to delete from persistent state :type cluster: :py:class:`elasticluster.cluster.Cluster` """
path = self._get_cluster_storage_path(cluster.name) if os.path.exists(path): os.unlink(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, fp): """Load cluster from file descriptor fp"""
cluster = pickle.load(fp) cluster.repository = self return cluster
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initdb(): """Initialize the database."""
click.echo('Init the db...') db.create_all() for i in range(30): click.echo("Creating user/address combo #{}...".format(i)) address = Address(description='Address#2' + str(i).rjust(2, "0")) db.session.add(address) user = User(name='User#1' + str(i).rjust(2, "0")) user.address = address db.session.add(user) sleep(1) db.session.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_regex(regex): """ Escape any regex special characters other than alternation. :param regex: regex from datatables interface :type regex: str :rtype: str with regex to use with database """
# copy for return ret_regex = regex # these characters are escaped (all except alternation | and escape \) # see http://www.regular-expressions.info/refquick.html escape_chars = '[^$.?*+(){}' # remove any escape chars ret_regex = ret_regex.replace('\\', '') # escape any characters which are used by regex # could probably concoct something incomprehensible using re.sub() but # prefer to write clear code with this loop # note expectation that no characters have already been escaped for c in escape_chars: ret_regex = ret_regex.replace(c, '\\' + c) # remove any double alternations until these don't exist any more while True: old_regex = ret_regex ret_regex = ret_regex.replace('||', '|') if old_regex == ret_regex: break # if last char is alternation | remove it because this # will cause operational error # this can happen as user is typing in global search box while len(ret_regex) >= 1 and ret_regex[-1] == '|': ret_regex = ret_regex[:-1] # and back to the caller return ret_regex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def output_result(self): """Output results in the format needed by DataTables."""
output = {} output['draw'] = str(int(self.params.get('draw', 1))) output['recordsTotal'] = str(self.cardinality) output['recordsFiltered'] = str(self.cardinality_filtered) if self.error: output['error'] = self.error return output output['data'] = self.results for k, v in self.yadcf_params: output[k] = v return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Launch filtering, sorting and paging to output results."""
query = self.query # count before filtering self.cardinality = query.add_columns(self.columns[0].sqla_expr).count() self._set_column_filter_expressions() self._set_global_filter_expression() self._set_sort_expressions() self._set_yadcf_data(query) # apply filters query = query.filter( *[e for e in self.filter_expressions if e is not None]) self.cardinality_filtered = query.add_columns( self.columns[0].sqla_expr).count() # apply sorts query = query.order_by( *[e for e in self.sort_expressions if e is not None]) # add paging options length = int(self.params.get('length')) if length >= 0: query = query.limit(length) elif length == -1: pass else: raise (ValueError( 'Length should be a positive integer or -1 to disable')) query = query.offset(int(self.params.get('start'))) # add columns to query query = query.add_columns(*[c.sqla_expr for c in self.columns]) # fetch the result of the queries column_names = [ col.mData if col.mData else str(i) for i, col in enumerate(self.columns) ] self.results = [{k: v for k, v in zip(column_names, row)} for row in query.all()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_query_value(combined_value): """Parse value in form of '>value' to a lambda and a value."""
split = len(combined_value) - len(combined_value.lstrip('<>=')) operator = combined_value[:split] if operator == '': operator = '=' try: operator_func = search_operators[operator] except KeyError: raise ValueError( 'Numeric query should start with operator, choose from %s' % ', '.join(search_operators.keys())) value = combined_value[split:].strip() return operator_func, value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def home(request): """Try to connect to database, and list available examples."""
try: DBSession.query(User).first() except DBAPIError: return Response( conn_err_msg, content_type="text/plain", status_int=500, ) return {"project": "pyramid_tut"}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(global_config, **settings): """Return a Pyramid WSGI application."""
engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include("pyramid_jinja2") config.include("pyramid_debugtoolbar") config.add_route("home", "/") config.add_route("data", "/data") config.add_route("data_advanced", "/data_advanced") config.add_route("data_yadcf", "/data_yadcf") config.add_route("dt_110x", "/dt_110x") config.add_route("dt_110x_custom_column", "/dt_110x_custom_column") config.add_route("dt_110x_basic_column_search", "/dt_110x_basic_column_search") config.add_route("dt_110x_advanced_column_search", "/dt_110x_advanced_column_search") config.add_route("dt_110x_yadcf", "/dt_110x_yadcf") config.scan() json_renderer = JSON() json_renderer.add_adapter(date, date_adapter) config.add_renderer("json_with_dates", json_renderer) config.add_jinja2_renderer('.html') return config.make_wsgi_app()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv=sys.argv): """Populate database with 30 users."""
if len(argv) < 2: usage(argv) config_uri = argv[1] setup_logging(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) Base.metadata.create_all(engine) for i in range(30): with transaction.manager: address = Address(description="Address#2" + str(i).rjust(2, "0")) DBSession.add(address) user = User( name="User#1" + str(i).rjust(2, "0"), birthday=date(1980 + i % 8, i % 12 + 1, i % 10 + 1)) user.address = address DBSession.add(user)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_logline_timestamp(t): """Parses a logline timestamp into a tuple. Args: t: Timestamp in logline format. Returns: An iterable of date and time elements in the order of month, day, hour, minute, second, microsecond. """
date, time = t.split(' ') month, day = date.split('-') h, m, s = time.split(':') s, ms = s.split('.') return (month, day, h, m, s, ms)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logline_timestamp_comparator(t1, t2): """Comparator for timestamps in logline format. Args: t1: Timestamp in logline format. t2: Timestamp in logline format. Returns: -1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. """
dt1 = _parse_logline_timestamp(t1) dt2 = _parse_logline_timestamp(t2) for u1, u2 in zip(dt1, dt2): if u1 < u2: return -1 elif u1 > u2: return 1 return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def epoch_to_log_line_timestamp(epoch_time, time_zone=None): """Converts an epoch timestamp in ms to log line timestamp format, which is readible for humans. Args: epoch_time: integer, an epoch timestamp in ms. time_zone: instance of tzinfo, time zone information. Using pytz rather than python 3.2 time_zone implementation for python 2 compatibility reasons. Returns: A string that is the corresponding timestamp in log line timestamp format. """
s, ms = divmod(epoch_time, 1000) d = datetime.datetime.fromtimestamp(s, tz=time_zone) return d.strftime('%m-%d %H:%M:%S.') + str(ms)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_suite(test_classes, argv=None): """Executes multiple test classes as a suite. This is the default entry point for running a test suite script file directly. Args: test_classes: List of python classes containing Mobly tests. argv: A list that is then parsed as cli args. If None, defaults to cli input. """
# Parse cli args. parser = argparse.ArgumentParser(description='Mobly Suite Executable.') parser.add_argument( '-c', '--config', nargs=1, type=str, required=True, metavar='<PATH>', help='Path to the test configuration file.') parser.add_argument( '--tests', '--test_case', nargs='+', type=str, metavar='[ClassA[.test_a] ClassB[.test_b] ...]', help='A list of test classes and optional tests to execute.') if not argv: argv = sys.argv[1:] args = parser.parse_args(argv) # Load test config file. test_configs = config_parser.load_test_config_file(args.config[0]) # Check the classes that were passed in for test_class in test_classes: if not issubclass(test_class, base_test.BaseTestClass): logging.error('Test class %s does not extend ' 'mobly.base_test.BaseTestClass', test_class) sys.exit(1) # Find the full list of tests to execute selected_tests = compute_selected_tests(test_classes, args.tests) # Execute the suite ok = True for config in test_configs: runner = test_runner.TestRunner(config.log_path, config.test_bed_name) for (test_class, tests) in selected_tests.items(): runner.add_test_class(config, test_class, tests) try: runner.run() ok = runner.results.is_all_pass and ok except signals.TestAbortAll: pass except: logging.exception('Exception when executing %s.', config.test_bed_name) ok = False if not ok: sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_device(self, serial=None): """Creates an AndroidDevice for the given serial number. If no serial is given, it will read from the ANDROID_SERIAL environmental variable. If the environmental variable is not set, then it will read from 'adb devices' if there is only one. """
serials = android_device.list_adb_devices() if not serials: raise Error('No adb device found!') # No serial provided, try to pick up the device automatically. if not serial: env_serial = os.environ.get('ANDROID_SERIAL', None) if env_serial is not None: serial = env_serial elif len(serials) == 1: serial = serials[0] else: raise Error( 'Expected one phone, but %d found. Use the -s flag or ' 'specify ANDROID_SERIAL.' % len(serials)) if serial not in serials: raise Error('Device "%s" is not found by adb.' % serial) ads = android_device.get_instances([serial]) assert len(ads) == 1 self._ad = ads[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, host, port=23): """Opens a telnet connection to the desired AttenuatorDevice and queries basic information. Args: host: A valid hostname (IP address or DNS-resolvable name) to an MC-DAT attenuator instrument. port: An optional port number (defaults to telnet default 23) """
self._telnet_client.open(host, port) config_str = self._telnet_client.cmd("MN?") if config_str.startswith("MN="): config_str = config_str[len("MN="):] self.properties = dict( zip(['model', 'max_freq', 'max_atten'], config_str.split("-", 2))) self.max_atten = float(self.properties['max_atten'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_atten(self, idx, value): """Sets the attenuation value for a particular signal path. Args: idx: Zero-based index int which is the identifier for a particular signal path in an instrument. For instruments that only has one channel, this is ignored by the device. value: A float that is the attenuation value to set. Raises: Error: The underlying telnet connection to the instrument is not open. IndexError: The index of the attenuator is greater than the maximum index of the underlying instrument. ValueError: The requested set value is greater than the maximum attenuation value. """
if not self.is_open: raise attenuator.Error( "Connection to attenuator at %s is not open!" % self._telnet_client.host) if idx + 1 > self.path_count: raise IndexError("Attenuator index out of range!", self.path_count, idx) if value > self.max_atten: raise ValueError("Attenuator value out of range!", self.max_atten, value) # The actual device uses one-based index for channel numbers. self._telnet_client.cmd("CHAN:%s:SETATT:%s" % (idx + 1, value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_atten(self, idx=0): """This function returns the current attenuation from an attenuator at a given index in the instrument. Args: idx: This zero-based index is the identifier for a particular attenuator in an instrument. Raises: Error: The underlying telnet connection to the instrument is not open. Returns: A float that is the current attenuation value. """
if not self.is_open: raise attenuator.Error( "Connection to attenuator at %s is not open!" % self._telnet_client.host) if idx + 1 > self.path_count or idx < 0: raise IndexError("Attenuator index out of range!", self.path_count, idx) atten_val_str = self._telnet_client.cmd("CHAN:%s:ATT?" % (idx + 1)) atten_val = float(atten_val_str) return atten_val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_app_connection(self, port=None): """Restores the sl4a after device got disconnected. Instead of creating new instance of the client: - Uses the given port (or find a new available host_port if none is given). - Tries to connect to remote server with selected port. Args: port: If given, this is the host port from which to connect to remote device port. If not provided, find a new available port as host port. Raises: AppRestoreConnectionError: When the app was not able to be started. """
self.host_port = port or utils.get_available_host_port() self._retry_connect() self.ed = self._start_event_client()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_app_connection(self, port=None): """Restores the app after device got reconnected. Instead of creating new instance of the client: - Uses the given port (or find a new available host_port if none is given). - Tries to connect to remote server with selected port. Args: port: If given, this is the host port from which to connect to remote device port. If not provided, find a new available port as host port. Raises: AppRestoreConnectionError: When the app was not able to be started. """
self.host_port = port or utils.get_available_host_port() self._adb.forward( ['tcp:%d' % self.host_port, 'tcp:%d' % self.device_port]) try: self.connect() except: # Log the original error and raise AppRestoreConnectionError. self.log.exception('Failed to re-connect to app.') raise jsonrpc_client_base.AppRestoreConnectionError( self._ad, ('Failed to restore app connection for %s at host port %s, ' 'device port %s') % (self.package, self.host_port, self.device_port)) # Because the previous connection was lost, update self._proc self._proc = None self._restore_event_client()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _restore_event_client(self): """Restores previously created event client."""
if not self._event_client: self._event_client = self._start_event_client() return self._event_client.host_port = self.host_port self._event_client.device_port = self.device_port self._event_client.connect()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_protocol_line(self): """Reads the next line of instrumentation output relevant to snippets. This method will skip over lines that don't start with 'SNIPPET' or 'INSTRUMENTATION_RESULT'. Returns: (str) Next line of snippet-related instrumentation output, stripped. Raises: jsonrpc_client_base.AppStartError: If EOF is reached without any protocol lines being read. """
while True: line = self._proc.stdout.readline().decode('utf-8') if not line: raise jsonrpc_client_base.AppStartError( self._ad, 'Unexpected EOF waiting for app to start') # readline() uses an empty string to mark EOF, and a single newline # to mark regular empty lines in the output. Don't move the strip() # call above the truthiness check, or this method will start # considering any blank output line to be EOF. line = line.strip() if (line.startswith('INSTRUMENTATION_RESULT:') or line.startswith('SNIPPET ')): self.log.debug( 'Accepted line from instrumentation output: "%s"', line) return line self.log.debug('Discarded line from instrumentation output: "%s"', line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_persist_command(self): """Check availability and return path of command if available."""
for command in [_SETSID_COMMAND, _NOHUP_COMMAND]: try: if command in self._adb.shell(['which', command]).decode('utf-8'): return command except adb.AdbError: continue self.log.warning( 'No %s and %s commands available to launch instrument ' 'persistently, tests that depend on UiAutomator and ' 'at the same time performs USB disconnection may fail', _SETSID_COMMAND, _NOHUP_COMMAND) return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def help(self, print_output=True): """Calls the help RPC, which returns the list of RPC calls available. This RPC should normally be used in an interactive console environment where the output should be printed instead of returned. Otherwise, newlines will be escaped, which will make the output difficult to read. Args: print_output: A bool for whether the output should be printed. Returns: A str containing the help output otherwise None if print_output wasn't set. """
help_text = self._rpc('help') if print_output: print(help_text) else: return help_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_any_alive(self): """True if any service is alive; False otherwise."""
for service in self._service_objects.values(): if service.is_alive: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, alias): """Unregisters a service instance. Stops a service and removes it from the manager. Args: alias: string, the alias of the service instance to unregister. """
if alias not in self._service_objects: raise Error(self._device, 'No service is registered with alias "%s".' % alias) service_obj = self._service_objects.pop(alias) if service_obj.is_alive: with expects.expect_no_raises( 'Failed to stop service instance "%s".' % alias): service_obj.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister_all(self): """Safely unregisters all active instances. Errors occurred here will be recorded but not raised. """
aliases = list(self._service_objects.keys()) for alias in aliases: self.unregister(alias)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_all(self): """Starts all inactive service instances."""
for alias, service in self._service_objects.items(): if not service.is_alive: with expects.expect_no_raises( 'Failed to start service "%s".' % alias): service.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_all(self): """Stops all active service instances."""
for alias, service in self._service_objects.items(): if service.is_alive: with expects.expect_no_raises( 'Failed to stop service "%s".' % alias): service.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause_all(self): """Pauses all service instances."""
for alias, service in self._service_objects.items(): with expects.expect_no_raises( 'Failed to pause service "%s".' % alias): service.pause()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume_all(self): """Resumes all service instances."""
for alias, service in self._service_objects.items(): with expects.expect_no_raises( 'Failed to pause service "%s".' % alias): service.resume()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(configs): """Creates AndroidDevice controller objects. Args: configs: A list of dicts, each representing a configuration for an Android device. Returns: A list of AndroidDevice objects. """
if not configs: raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG) elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN: ads = get_all_instances() elif not isinstance(configs, list): raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG) elif isinstance(configs[0], dict): # Configs is a list of dicts. ads = get_instances_with_configs(configs) elif isinstance(configs[0], basestring): # Configs is a list of strings representing serials. ads = get_instances(configs) else: raise Error('No valid config found in: %s' % configs) valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id() for ad in ads: if ad.serial not in valid_ad_identifiers: raise DeviceError(ad, 'Android device is specified in config but' ' is not attached.') _start_services_on_ads(ads) return ads
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(ads): """Cleans up AndroidDevice objects. Args: ads: A list of AndroidDevice objects. """
for ad in ads: try: ad.services.stop_all() except: ad.log.exception('Failed to clean up properly.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start_services_on_ads(ads): """Starts long running services on multiple AndroidDevice objects. If any one AndroidDevice object fails to start services, cleans up all existing AndroidDevice objects and their services. Args: ads: A list of AndroidDevice objects whose services to start. """
running_ads = [] for ad in ads: running_ads.append(ad) start_logcat = not getattr(ad, KEY_SKIP_LOGCAT, DEFAULT_VALUE_SKIP_LOGCAT) try: ad.services.register( SERVICE_NAME_LOGCAT, logcat.Logcat, start_service=start_logcat) except Exception: is_required = getattr(ad, KEY_DEVICE_REQUIRED, DEFAULT_VALUE_DEVICE_REQUIRED) if is_required: ad.log.exception('Failed to start some services, abort!') destroy(running_ads) raise else: ad.log.exception('Skipping this optional device because some ' 'services failed to start.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_device_list(device_list_str, key): """Parses a byte string representing a list of devices. The string is generated by calling either adb or fastboot. The tokens in each string is tab-separated. Args: device_list_str: Output of adb or fastboot. key: The token that signifies a device in device_list_str. Returns: A list of android device serial numbers. """
clean_lines = new_str(device_list_str, 'utf-8').strip().split('\n') results = [] for line in clean_lines: tokens = line.strip().split('\t') if len(tokens) == 2 and tokens[1] == key: results.append(tokens[0]) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_adb_devices_by_usb_id(): """List the usb id of all android devices connected to the computer that are detected by adb. Returns: A list of strings that are android device usb ids. Empty if there's none. """
out = adb.AdbProxy().devices(['-l']) clean_lines = new_str(out, 'utf-8').strip().split('\n') results = [] for line in clean_lines: tokens = line.strip().split() if len(tokens) > 2 and tokens[1] == 'device': results.append(tokens[2]) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_instances(serials): """Create AndroidDevice instances from a list of serials. Args: serials: A list of android device serials. Returns: A list of AndroidDevice objects. """
results = [] for s in serials: results.append(AndroidDevice(s)) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_instances_with_configs(configs): """Create AndroidDevice instances from a list of dict configs. Each config should have the required key-value pair 'serial'. Args: configs: A list of dicts each representing the configuration of one android device. Returns: A list of AndroidDevice objects. """
results = [] for c in configs: try: serial = c.pop('serial') except KeyError: raise Error( 'Required value "serial" is missing in AndroidDevice config %s.' % c) is_required = c.get(KEY_DEVICE_REQUIRED, True) try: ad = AndroidDevice(serial) ad.load_config(c) except Exception: if is_required: raise ad.log.exception('Skipping this optional device due to error.') continue results.append(ad) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_instances(include_fastboot=False): """Create AndroidDevice instances for all attached android devices. Args: include_fastboot: Whether to include devices in bootloader mode or not. Returns: A list of AndroidDevice objects each representing an android device attached to the computer. """
if include_fastboot: serial_list = list_adb_devices() + list_fastboot_devices() return get_instances(serial_list) return get_instances(list_adb_devices())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_devices(ads, func): """Finds the AndroidDevice instances from a list that match certain conditions. Args: ads: A list of AndroidDevice instances. func: A function that takes an AndroidDevice object and returns True if the device satisfies the filter condition. Returns: A list of AndroidDevice instances that satisfy the filter condition. """
results = [] for ad in ads: if func(ad): results.append(ad) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_devices(ads, **kwargs): """Finds a list of AndroidDevice instance from a list that has specific attributes of certain values. Example: get_devices(android_devices, label='foo', phone_number='1234567890') get_devices(android_devices, model='angler') Args: ads: A list of AndroidDevice instances. kwargs: keyword arguments used to filter AndroidDevice instances. Returns: A list of target AndroidDevice instances. Raises: Error: No devices are matched. """
def _get_device_filter(ad): for k, v in kwargs.items(): if not hasattr(ad, k): return False elif getattr(ad, k) != v: return False return True filtered = filter_devices(ads, _get_device_filter) if not filtered: raise Error( 'Could not find a target device that matches condition: %s.' % kwargs) else: return filtered
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_device(ads, **kwargs): """Finds a unique AndroidDevice instance from a list that has specific attributes of certain values. Deprecated, use `get_devices(ads, **kwargs)[0]` instead. This method will be removed in 1.8. Example: get_device(android_devices, label='foo', phone_number='1234567890') get_device(android_devices, model='angler') Args: ads: A list of AndroidDevice instances. kwargs: keyword arguments used to filter AndroidDevice instances. Returns: The target AndroidDevice instance. Raises: Error: None or more than one device is matched. """
filtered = get_devices(ads, **kwargs) if len(filtered) == 1: return filtered[0] else: serials = [ad.serial for ad in filtered] raise Error('More than one device matched: %s' % serials)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take_bug_reports(ads, test_name, begin_time, destination=None): """Takes bug reports on a list of android devices. If you want to take a bug report, call this function with a list of android_device objects in on_fail. But reports will be taken on all the devices in the list concurrently. Bug report takes a relative long time to take, so use this cautiously. Args: ads: A list of AndroidDevice instances. test_name: Name of the test method that triggered this bug report. begin_time: timestamp taken when the test started, can be either string or int. destination: string, path to the directory where the bugreport should be saved. """
begin_time = mobly_logger.normalize_log_line_timestamp(str(begin_time)) def take_br(test_name, begin_time, ad, destination): ad.take_bug_report(test_name, begin_time, destination=destination) args = [(test_name, begin_time, ad, destination) for ad in ads] utils.concurrent_exec(take_br, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalized_serial(self): """Normalized serial name for usage in log filename. Some Android emulators use ip:port as their serial names, while on Windows `:` is not valid in filename, it should be sanitized first. """
if self._serial is None: return None normalized_serial = self._serial.replace(' ', '_') normalized_serial = normalized_serial.replace(':', '-') return normalized_serial
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_info(self): """Information to be pulled into controller info. The latest serial, model, and build_info are included. Additional info can be added via `add_device_info`. """
info = { 'serial': self.serial, 'model': self.model, 'build_info': self.build_info, 'user_added_info': self._user_added_device_info } return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug_tag(self, tag): """Setter for the debug tag. By default, the tag is the serial of the device, but sometimes it may be more descriptive to use a different tag of the user's choice. Changing debug tag changes part of the prefix of debug info emitted by this object, like log lines and the message of DeviceError. Example: By default, the device's serial number is used: 'INFO [AndroidDevice|abcdefg12345] One pending call ringing.' The tag can be customized with `ad.debug_tag = 'Caller'`: 'INFO [AndroidDevice|Caller] One pending call ringing.' """
self.log.info('Logging debug tag set to "%s"', tag) self._debug_tag = tag self.log.extra['tag'] = tag
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_path(self, new_path): """Setter for `log_path`, use with caution."""
if self.has_active_service: raise DeviceError( self, 'Cannot change `log_path` when there is service running.') old_path = self._log_path if new_path == old_path: return if os.listdir(new_path): raise DeviceError( self, 'Logs already exist at %s, cannot override.' % new_path) if os.path.exists(old_path): # Remove new path so copytree doesn't complain. shutil.rmtree(new_path, ignore_errors=True) shutil.copytree(old_path, new_path) shutil.rmtree(old_path, ignore_errors=True) self._log_path = new_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_serial(self, new_serial): """Updates the serial number of a device. The "serial number" used with adb's `-s` arg is not necessarily the actual serial number. For remote devices, it could be a combination of host names and port numbers. This is used for when such identifier of remote devices changes during a test. For example, when a remote device reboots, it may come back with a different serial number. This is NOT meant for switching the object to represent another device. We intentionally did not make it a regular setter of the serial property so people don't accidentally call this without understanding the consequences. Args: new_serial: string, the new serial number for the same device. Raises: DeviceError: tries to update serial when any service is running. """
new_serial = str(new_serial) if self.has_active_service: raise DeviceError( self, 'Cannot change device serial number when there is service running.' ) if self._debug_tag == self.serial: self._debug_tag = new_serial self._serial = new_serial self.adb.serial = new_serial self.fastboot.serial = new_serial
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_reboot(self): """Properly manage the service life cycle when the device needs to temporarily disconnect. The device can temporarily lose adb connection due to user-triggered reboot. Use this function to make sure the services started by Mobly are properly stopped and restored afterwards. For sample usage, see self.reboot(). """
self.services.stop_all() try: yield finally: self.wait_for_boot_completion() if self.is_rootable: self.root_adb() self.services.start_all()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_info(self): """Get the build info of this Android device, including build id and build type. This is not available if the device is in bootloader mode. Returns: A dict with the build info of this Android device, or None if the device is in bootloader mode. """
if self.is_bootloader: self.log.error('Device is in fastboot mode, could not get build ' 'info.') return info = {} info['build_id'] = self.adb.getprop('ro.build.id') info['build_type'] = self.adb.getprop('ro.build.type') return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_adb_root(self): """True if adb is running as root for this device. """
try: return '0' == self.adb.shell('id -u').decode('utf-8').strip() except adb.AdbError: # Wait a bit and retry to work around adb flakiness for this cmd. time.sleep(0.2) return '0' == self.adb.shell('id -u').decode('utf-8').strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model(self): """The Android code name for the device. """
# If device is in bootloader mode, get mode name from fastboot. if self.is_bootloader: out = self.fastboot.getvar('product').strip() # 'out' is never empty because of the 'total time' message fastboot # writes to stderr. lines = out.decode('utf-8').split('\n', 1) if lines: tokens = lines[0].split(' ') if len(tokens) > 1: return tokens[1].lower() return None model = self.adb.getprop('ro.build.product').lower() if model == 'sprout': return model return self.adb.getprop('ro.product.name').lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_config(self, config): """Add attributes to the AndroidDevice object based on config. Args: config: A dictionary representing the configs. Raises: Error: The config is trying to overwrite an existing attribute. """
for k, v in config.items(): if hasattr(self, k): raise DeviceError( self, ('Attribute %s already exists with value %s, cannot set ' 'again.') % (k, getattr(self, k))) setattr(self, k, v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def root_adb(self): """Change adb to root mode for this device if allowed. If executed on a production build, adb will not be switched to root mode per security restrictions. """
self.adb.root() self.adb.wait_for_device( timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_snippet(self, name, package): """Starts the snippet apk with the given package name and connects. Examples: .. code-block:: python ad.load_snippet( name='maps', package='com.google.maps.snippets') ad.maps.activateZoom('3') 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. Raises: SnippetError: Illegal load operations are attempted. """
# Should not load snippet with an existing attribute. if hasattr(self, name): raise SnippetError( self, 'Attribute "%s" already exists, please use a different name.' % name) self.services.snippets.add_snippet_client(name, package)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take_bug_report(self, test_name, begin_time, timeout=300, destination=None): """Takes a bug report on the device and stores it in a file. Args: test_name: Name of the test method that triggered this bug report. begin_time: Timestamp of when the test started. timeout: float, the number of seconds to wait for bugreport to complete, default is 5min. destination: string, path to the directory where the bugreport should be saved. """
new_br = True try: stdout = self.adb.shell('bugreportz -v').decode('utf-8') # This check is necessary for builds before N, where adb shell's ret # code and stderr are not propagated properly. if 'not found' in stdout: new_br = False except adb.AdbError: new_br = False if destination: br_path = utils.abs_path(destination) else: br_path = os.path.join(self.log_path, 'BugReports') utils.create_dir(br_path) base_name = ',%s,%s.txt' % (begin_time, self._normalized_serial) if new_br: base_name = base_name.replace('.txt', '.zip') test_name_len = utils.MAX_FILENAME_LEN - len(base_name) out_name = test_name[:test_name_len] + base_name full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ ')) # in case device restarted, wait for adb interface to return self.wait_for_boot_completion() self.log.info('Taking bugreport for %s.', test_name) if new_br: out = self.adb.shell('bugreportz', timeout=timeout).decode('utf-8') if not out.startswith('OK'): raise DeviceError(self, 'Failed to take bugreport: %s' % out) br_out_path = out.split(':')[1].strip() self.adb.pull([br_out_path, full_out_path]) else: # shell=True as this command redirects the stdout to a local file # using shell redirection. self.adb.bugreport( ' > "%s"' % full_out_path, shell=True, timeout=timeout) self.log.info('Bugreport for %s taken at %s.', test_name, full_out_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_iperf_client(self, server_host, extra_args=''): """Start iperf client on the device. Return status as true if iperf client start successfully. And data flow information as results. Args: server_host: Address of the iperf server. extra_args: A string representing extra arguments for iperf client, e.g. '-i 1 -t 30'. Returns: status: true if iperf client start successfully. results: results have data flow information """
out = self.adb.shell('iperf3 -c %s %s' % (server_host, extra_args)) clean_out = new_str(out, 'utf-8').strip().split('\n') if 'error' in clean_out[0].lower(): return False, clean_out return True, clean_out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_boot_completion( self, timeout=DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND): """Waits for Android framework to broadcast ACTION_BOOT_COMPLETED. This function times out after 15 minutes. Args: timeout: float, the number of seconds to wait before timing out. If not specified, no timeout takes effect. """
timeout_start = time.time() self.adb.wait_for_device(timeout=timeout) while time.time() < timeout_start + timeout: try: if self.is_boot_completed(): return except adb.AdbError: # adb shell calls may fail during certain period of booting # process, which is normal. Ignoring these errors. pass time.sleep(5) raise DeviceError(self, 'Booting process timed out')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_boot_completed(self): """Checks if device boot is completed by verifying system property."""
completed = self.adb.getprop('sys.boot_completed') if completed == '1': self.log.debug('Device boot completed.') return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_adb_detectable(self): """Checks if USB is on and device is ready by verifying adb devices."""
serials = list_adb_devices() if self.serial in serials: self.log.debug('Is now adb detectable.') return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect_true(condition, msg, extras=None): """Expects an expression evaluates to True. If the expectation is not met, the test is marked as fail after its execution finishes. Args: expr: The expression that is evaluated. msg: A string explaining the details in case of failure. extras: An optional field for extra information to be included in test result. """
try: asserts.assert_true(condition, msg, extras) except signals.TestSignal as e: logging.exception('Expected a `True` value, got `False`.') recorder.add_error(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect_false(condition, msg, extras=None): """Expects an expression evaluates to False. If the expectation is not met, the test is marked as fail after its execution finishes. Args: expr: The expression that is evaluated. msg: A string explaining the details in case of failure. extras: An optional field for extra information to be included in test result. """
try: asserts.assert_false(condition, msg, extras) except signals.TestSignal as e: logging.exception('Expected a `False` value, got `True`.') recorder.add_error(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect_equal(first, second, msg=None, extras=None): """Expects the equality of objects, otherwise fail the test. If the expectation is not met, the test is marked as fail after its execution finishes. 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 about the failure. extras: An optional field for extra information to be included in test result. """
try: asserts.assert_equal(first, second, msg, extras) except signals.TestSignal as e: logging.exception('Expected %s equals to %s, but they are not.', first, second) recorder.add_error(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expect_no_raises(message=None, extras=None): """Expects no exception is raised in a context. If the expectation is not met, the test is marked as fail after its execution finishes. A default message is added to the exception `details`. Args: message: string, custom message to add to exception's `details`. extras: An optional field for extra information to be included in test result. """
try: yield except Exception as e: e_record = records.ExceptionRecord(e) if extras: e_record.extras = extras msg = message or 'Got an unexpected exception' details = '%s: %s' % (msg, e_record.details) logging.exception(details) e_record.details = details recorder.add_error(e_record)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_internal_states(self, record=None): """Resets the internal state of the recorder. Args: record: records.TestResultRecord, the test record for a test. """
self._record = None self._count = 0 self._record = record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_error(self, error): """Record an error from expect APIs. This method generates a position stamp for the expect. The stamp is composed of a timestamp and the number of errors recorded so far. Args: error: Exception or signals.ExceptionRecord, the error to add. """
self._count += 1 self._record.add_error('expect@%s+%s' % (time.time(), self._count), error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _enable_logpersist(self): """Attempts to enable logpersist daemon to persist logs."""
# Logpersist is only allowed on rootable devices because of excessive # reads/writes for persisting logs. if not self._ad.is_rootable: return logpersist_warning = ('%s encountered an error enabling persistent' ' logs, logs may not get saved.') # Android L and older versions do not have logpersist installed, # so check that the logpersist scripts exists before trying to use # them. if not self._ad.adb.has_shell_command('logpersist.start'): logging.warning(logpersist_warning, self) return try: # Disable adb log spam filter for rootable devices. Have to stop # and clear settings first because 'start' doesn't support --clear # option before Android N. self._ad.adb.shell('logpersist.stop --clear') self._ad.adb.shell('logpersist.start') except adb.AdbError: logging.warning(logpersist_warning, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_adb_log(self): """Clears cached adb content."""
try: self._ad.adb.logcat('-c') except adb.AdbError as e: # On Android O, the clear command fails due to a known bug. # Catching this so we don't crash from this Android issue. if b'failed to clear' in e.stderr: self._ad.log.warning( 'Encountered known Android error to clear logcat.') else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cat_adb_log(self, tag, begin_time): """Takes an excerpt of the adb logcat log from a certain time point to current time. Args: tag: An identifier of the time period, usualy the name of a test. begin_time: Logline format timestamp of the beginning of the time period. """
if not self.adb_logcat_file_path: raise Error( self._ad, 'Attempting to cat adb log when none has been collected.') end_time = mobly_logger.get_log_line_timestamp() self._ad.log.debug('Extracting adb log from logcat.') adb_excerpt_path = os.path.join(self._ad.log_path, 'AdbLogExcerpts') utils.create_dir(adb_excerpt_path) f_name = os.path.basename(self.adb_logcat_file_path) out_name = f_name.replace('adblog,', '').replace('.txt', '') out_name = ',%s,%s.txt' % (begin_time, out_name) out_name = out_name.replace(':', '-') tag_len = utils.MAX_FILENAME_LEN - len(out_name) tag = tag[:tag_len] out_name = tag + out_name full_adblog_path = os.path.join(adb_excerpt_path, out_name) with io.open(full_adblog_path, 'w', encoding='utf-8') as out: in_file = self.adb_logcat_file_path with io.open( in_file, 'r', encoding='utf-8', errors='replace') as f: in_range = False while True: line = None try: line = f.readline() if not line: break except: continue line_time = line[:mobly_logger.log_line_timestamp_len] if not mobly_logger.is_valid_logline_timestamp(line_time): continue if self._is_timestamp_in_range(line_time, begin_time, end_time): in_range = True if not line.endswith('\n'): line += '\n' out.write(line) else: if in_range: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Starts a standing adb logcat collection. The collection runs in a separate subprocess and saves logs in a file. """
self._assert_not_running() if self._configs.clear_log: self.clear_adb_log() self._start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start(self): """The actual logic of starting logcat."""
self._enable_logpersist() logcat_file_path = self._configs.output_file_path if not logcat_file_path: f_name = 'adblog,%s,%s.txt' % (self._ad.model, self._ad._normalized_serial) logcat_file_path = os.path.join(self._ad.log_path, f_name) utils.create_dir(os.path.dirname(logcat_file_path)) cmd = '"%s" -s %s logcat -v threadtime %s >> "%s"' % ( adb.ADB, self._ad.serial, self._configs.logcat_params, logcat_file_path) process = utils.start_standing_subprocess(cmd, shell=True) self._adb_logcat_process = process self.adb_logcat_file_path = logcat_file_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stops the adb logcat service."""
if not self._adb_logcat_process: return try: utils.stop_standing_subprocess(self._adb_logcat_process) except: self._ad.log.exception('Failed to stop adb logcat.') self._adb_logcat_process = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, uid=UNKNOWN_UID, cmd=JsonRpcCommand.INIT): """Opens a connection to a JSON RPC server. Opens a connection to a remote client. The connection attempt will time out if it takes longer than _SOCKET_CONNECTION_TIMEOUT seconds. Each subsequent operation over this socket will time out after _SOCKET_READ_TIMEOUT seconds as well. Args: uid: int, The uid of the session to join, or UNKNOWN_UID to start a new session. cmd: JsonRpcCommand, The command to use for creating the connection. Raises: IOError: Raised when the socket times out from io error socket.timeout: Raised when the socket waits to long for connection. ProtocolError: Raised when there is an error in the protocol. """
self._counter = self._id_counter() self._conn = socket.create_connection(('localhost', self.host_port), _SOCKET_CONNECTION_TIMEOUT) self._conn.settimeout(_SOCKET_READ_TIMEOUT) self._client = self._conn.makefile(mode='brw') resp = self._cmd(cmd, uid) if not resp: raise ProtocolError(self._ad, ProtocolError.NO_RESPONSE_FROM_HANDSHAKE) result = json.loads(str(resp, encoding='utf8')) if result['status']: self.uid = result['uid'] else: self.uid = UNKNOWN_UID
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_host_port(self): """Stops the adb port forwarding of the host port used by this client. """
if self.host_port: self._adb.forward(['--remove', 'tcp:%d' % self.host_port]) self.host_port = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _client_send(self, msg): """Sends an Rpc message through the connection. Args: msg: string, the message to send. Raises: Error: a socket error occurred during the send. """
try: self._client.write(msg.encode("utf8") + b'\n') self._client.flush() self.log.debug('Snippet sent %s.', msg) except socket.error as e: raise Error( self._ad, 'Encountered socket error "%s" sending RPC message "%s"' % (e, msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 through, however executed with errors. """
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 ProtocolError(self._ad, ProtocolError.NO_RESPONSE_FROM_SERVER) result = json.loads(str(response, encoding='utf8')) if result['error']: raise ApiError(self._ad, result['error']) if result['id'] != apiid: raise ProtocolError(self._ad, ProtocolError.MISMATCHED_API_ID) if result.get('callback') is not None: if self._event_client is None: self._event_client = self._start_event_client() return callback_handler.CallbackHandler( callback_id=result['callback'], event_client=self._event_client, ret_value=result['result'], method_name=method, ad=self._ad) return result['result']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_hidden_api_blacklist(self): """If necessary and possible, disables hidden api blacklist."""
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. if self._ad.is_rootable and (sdk_version >= 28 or version_codename == 'P'): self._ad.adb.shell( 'settings put global hidden_api_blacklist_exemptions "*"')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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) cmd = '%s %s > %s' % (self.iperf_str, extra_args, full_out_path) self.iperf_process = utils.start_standing_subprocess(cmd, shell=True) self.log_files.append(full_out_path) self.started = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_process(self): """Utility function which is executed after a capture is done. It moves the capture file to the requested location. """
self._process = None shutil.move(self._temp_capture_file_path, self._capture_file_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Returns: A list of integers representing occupied host ports. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. timeout: float, the number of seconds to wait before timing out. If not specified, no timeout takes effect. stderr: a Byte stream, like io.BytesIO, stderr of the command will be written to this object if provided. Returns: The output of the adb command run if exit code is 0. Raises: ValueError: timeout value is invalid. AdbError: The adb command exit code is not 0. AdbTimeoutError: The adb command timed out. """
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( cmd=args, timeout=timeout, serial=self.serial) if stderr: stderr.write(err) logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', utils.cli_cmd_to_string(args), out, err, ret) if ret == 0: return out else: raise AdbError( cmd=args, stdout=out, stderr=err, ret_code=ret, serial=self.serial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 subprocess.Popen() docs. handler: func, a function to handle adb stdout line by line. Returns: The stderr of the adb command run if exit code is 0. Raises: AdbError: The adb command exit code is not 0. """
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 # and will continue until it runs out of stdout to process. while True: line = proc.stdout.readline() if line: handler(line) else: break finally: # Note, communicate will not contain any buffered output. (unexpected_out, err) = proc.communicate() if unexpected_out: out = '[unexpected stdout] %s' % unexpected_out for line in unexpected_out.splitlines(): handler(line) ret = proc.returncode logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', utils.cli_cmd_to_string(args), out, err, ret) if ret == 0: return err else: raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. shell: bool, True to run this command through the system shell, False to invoke it directly. See subprocess.Proc() docs. Returns: The adb command in a format appropriate for subprocess. If shell is True, then this is a string; otherwise, this is a list of strings. """
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: adb_cmd = '"%s" -s "%s" %s %s' % (ADB, self.serial, name, args) else: adb_cmd = '"%s" %s %s' % (ADB, name, args) else: adb_cmd = [ADB] if self.serial: adb_cmd.extend(['-s', self.serial]) adb_cmd.append(name) if args: if isinstance(args, basestring): adb_cmd.append(args) else: adb_cmd.extend(args) return adb_cmd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
return self.shell( ['getprop', prop_name], timeout=DEFAULT_GETPROP_TIMEOUT_SEC).decode('utf-8').strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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. return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.TestSuite', }, ) Args: package: string, the package of the instrumentation tests. options: dict, the instrumentation options including the test class. runner: string, the test runner name, which defaults to DEFAULT_INSTRUMENTATION_RUNNER. handler: optional func, when specified the function is used to parse the instrumentation stdout line by line as the output is generated; otherwise, the stdout is simply returned once the instrumentation is finished. Returns: The stdout of instrumentation command or the stderr if the handler is set. """
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 = ' '.join(options_list) instrumentation_command = 'am instrument -r -w %s %s/%s' % ( options_string, package, runner) logging.info('AndroidDevice|%s: Executing adb shell %s', self.serial, instrumentation_command) if handler is None: # Flow kept for backwards-compatibility reasons self._exec_adb_cmd( 'shell', instrumentation_command, shell=False, timeout=None, stderr=None) else: return self._execute_adb_and_process_stdout( 'shell', instrumentation_command, shell=False, handler=handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 about the failure. extras: An optional field for extra information to be included in test result. """
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 having two tracebacks. if my_msg is not None: raise signals.TestFailure(my_msg, extras=extras)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 specified event. Raises: Error: If the specified timeout is longer than the max timeout supported. TimeoutError: The expected event does not occur within time limit. """
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(timeout * 1000) try: raw_event = self._event_client.eventWaitAndGet( self._id, event_name, timeout_ms) except Exception as e: if 'EventSnippetException: timeout.' in str(e): raise TimeoutError( self._ad, 'Timed out after waiting %ss for event "%s" triggered by' ' %s (%s).' % (timeout, event_name, self._method_name, self._id)) raise return snippet_event.from_dict(raw_event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 satisfied, False otherwise. Note all events of the same name that are received but don't satisfy the predicate will be discarded and not be available for further consumption. Args: event_name: string, the name of the event to wait for. predicate: function, a function that takes an event (dictionary) and returns a bool. timeout: float, default is 120s. Returns: dictionary, the event that satisfies the predicate if received. Raises: TimeoutError: raised if no event that satisfies the predicate is received after timeout seconds. """
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. rpc_timeout = min(rpc_timeout, MAX_TIMEOUT) try: event = self.waitAndGet(event_name, rpc_timeout) except TimeoutError: # Ignoring TimeoutError since we need to throw one with a more # specific message. break if predicate(event): return event raise TimeoutError( self._ad, 'Timed out after %ss waiting for an "%s" event that satisfies the ' 'predicate "%s".' % (timeout, event_name, predicate.__name__))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 the Java side. """
raw_events = self._event_client.eventGetAll(self._id, event_name) return [snippet_event.from_dict(msg) for msg in raw_events]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. """
objs = [] for s in serials: objs.append(Monsoon(serial=s)) return objs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetStatus(self): """Requests and waits for status. Returns: status dictionary. """
# status packet format STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH" STATUS_FIELDS = [ "packetType", "firmwareVersion", "protocolVersion", "mainFineCurrent", "usbFineCurrent", "auxFineCurrent", "voltage1", "mainCoarseCurrent", "usbCoarseCurrent", "auxCoarseCurrent", "voltage2", "outputVoltageSetting", "temperature", "status", "leds", "mainFineResistor", "serialNumber", "sampleRate", "dacCalLow", "dacCalHigh", "powerUpCurrentLimit", "runTimeCurrentLimit", "powerUpTime", "usbFineResistor", "auxFineResistor", "initialUsbVoltage", "initialAuxVoltage", "hardwareRevision", "temperatureLimit", "usbPassthroughMode", "mainCoarseResistor", "usbCoarseResistor", "auxCoarseResistor", "defMainFineResistor", "defUsbFineResistor", "defAuxFineResistor", "defMainCoarseResistor", "defUsbCoarseResistor", "defAuxCoarseResistor", "eventCode", "eventData", ] self._SendStruct("BBB", 0x01, 0x00, 0x00) while 1: # Keep reading, discarding non-status packets read_bytes = self._ReadPacket() if not read_bytes: return None calsize = struct.calcsize(STATUS_FORMAT) if len(read_bytes) != calsize or read_bytes[0] != 0x10: logging.warning("Wanted status, dropped type=0x%02x, len=%d", read_bytes[0], len(read_bytes)) continue status = dict( zip(STATUS_FIELDS, struct.unpack(STATUS_FORMAT, read_bytes))) p_type = status["packetType"] if p_type != 0x10: raise MonsoonError("Package type %s is not 0x10." % p_type) for k in status.keys(): if k.endswith("VoltageSetting"): status[k] = 2.0 + status[k] * 0.01 elif k.endswith("FineCurrent"): pass # needs calibration data elif k.endswith("CoarseCurrent"): pass # needs calibration data elif k.startswith("voltage") or k.endswith("Voltage"): status[k] = status[k] * 0.000125 elif k.endswith("Resistor"): status[k] = 0.05 + status[k] * 0.0001 if k.startswith("aux") or k.startswith("defAux"): status[k] += 0.05 elif k.endswith("CurrentLimit"): status[k] = 8 * (1023 - status[k]) / 1023.0 return status