text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> returns a connection object to AWS EC2 <END_TASK> <USER_TASK:> Description: def connect_to_ec2(region, access_key_id, secret_access_key): """ returns a connection object to AWS EC2 """
conn = boto.ec2.connect_to_region(region, aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key) return conn
<SYSTEM_TASK:> returns a connection object to Rackspace <END_TASK> <USER_TASK:> Description: def connect_to_rackspace(region, access_key_id, secret_access_key): """ returns a connection object to Rackspace """
pyrax.set_setting('identity_type', 'rackspace') pyrax.set_default_region(region) pyrax.set_credentials(access_key_id, secret_access_key) nova = pyrax.connect_to_cloudservers(region=region) return nova
<SYSTEM_TASK:> Shuts down the instance and creates and image from the disk. <END_TASK> <USER_TASK:> Description: def create_gce_image(zone, project, instance_name, name, description): """ Shuts down the instance and creates and image from the disk. Assumes that the disk name is the same as the instance_name (this is the default behavior for boot disks on GCE). """
disk_name = instance_name try: down_gce(instance_name=instance_name, project=project, zone=zone) except HttpError as e: if e.resp.status == 404: log_yellow("the instance {} is already down".format(instance_name)) else: raise e body = { "rawDisk": {}, "name": name, "sourceDisk": "projects/{}/zones/{}/disks/{}".format( project, zone, disk_name ), "description": description } compute = _get_gce_compute() gce_wait_until_done( compute.images().insert(project=project, body=body).execute() ) return name
<SYSTEM_TASK:> proxy call for ec2, rackspace create ami backend functions <END_TASK> <USER_TASK:> Description: def create_image(cloud, **kwargs): """ proxy call for ec2, rackspace create ami backend functions """
if cloud == 'ec2': return create_ami(**kwargs) if cloud == 'rackspace': return create_rackspace_image(**kwargs) if cloud == 'gce': return create_gce_image(**kwargs)
<SYSTEM_TASK:> Perform a GCE operation, blocking until the operation completes. <END_TASK> <USER_TASK:> Description: def gce_wait_until_done(operation): """ Perform a GCE operation, blocking until the operation completes. This function will then poll the operation until it reaches state 'DONE' or times out, and then returns the final operation resource dict. :param operation: A dict representing a pending GCE operation resource. :returns dict: A dict representing the concluded GCE operation resource. """
operation_name = operation['name'] if 'zone' in operation: zone_url_parts = operation['zone'].split('/') project = zone_url_parts[-3] zone = zone_url_parts[-1] def get_zone_operation(): return _get_gce_compute().zoneOperations().get( project=project, zone=zone, operation=operation_name ) update = get_zone_operation else: project = operation['selfLink'].split('/')[-4] def get_global_operation(): return _get_gce_compute().globalOperations().get( project=project, operation=operation_name ) update = get_global_operation done = False latest_operation = None start = time() timeout = 5*60 # seconds while not done: latest_operation = update().execute() log_yellow("waiting for operation") if (latest_operation['status'] == 'DONE' or time() - start > timeout): done = True else: sleep(10) print "waiting for operation" return latest_operation
<SYSTEM_TASK:> For now, jclouds is broken for GCE and we will have static slaves <END_TASK> <USER_TASK:> Description: def startup_gce_instance(instance_name, project, zone, username, machine_type, image, public_key, disk_name=None): """ For now, jclouds is broken for GCE and we will have static slaves in Jenkins. Use this to boot them. """
log_green("Started...") log_yellow("...Creating GCE Jenkins Slave Instance...") instance_config = get_gce_instance_config( instance_name, project, zone, machine_type, image, username, public_key, disk_name ) operation = _get_gce_compute().instances().insert( project=project, zone=zone, body=instance_config ).execute() result = gce_wait_until_done(operation) if not result: raise RuntimeError("Creation of VM timed out or returned no result") log_green("Instance has booted")
<SYSTEM_TASK:> Creates EC2 Instance and saves it state in a local json file <END_TASK> <USER_TASK:> Description: def _create_server_ec2(region, access_key_id, secret_access_key, disk_name, disk_size, ami, key_pair, instance_type, username, tags={}, security_groups=None): """ Creates EC2 Instance and saves it state in a local json file """
conn = connect_to_ec2(region, access_key_id, secret_access_key) log_green("Started...") log_yellow("...Creating EC2 instance...") # we need a larger boot device to store our cached images ebs_volume = EBSBlockDeviceType() ebs_volume.size = disk_size bdm = BlockDeviceMapping() bdm[disk_name] = ebs_volume # get an ec2 ami image object with our choosen ami image = conn.get_all_images(ami)[0] # start a new instance reservation = image.run(1, 1, key_name=key_pair, security_groups=security_groups, block_device_map=bdm, instance_type=instance_type) # and get our instance_id instance = reservation.instances[0] # and loop and wait until ssh is available while instance.state == u'pending': log_yellow("Instance state: %s" % instance.state) sleep(10) instance.update() log_green("Instance state: %s" % instance.state) wait_for_ssh(instance.public_dns_name) # update the EBS volumes to be deleted on instance termination for dev, bd in instance.block_device_mapping.items(): instance.modify_attribute('BlockDeviceMapping', ["%s=%d" % (dev, 1)]) # add a tag to our instance conn.create_tags([instance.id], tags) log_green("Public dns: %s" % instance.public_dns_name) # finally save the details or our new instance into the local state file save_ec2_state_locally(instance_id=instance.id, region=region, username=username, access_key_id=access_key_id, secret_access_key=secret_access_key)
<SYSTEM_TASK:> configures marathon to start with authentication <END_TASK> <USER_TASK:> Description: def enable_marathon_basic_authentication(principal, password): """ configures marathon to start with authentication """
upstart_file = '/etc/init/marathon.conf' with hide('running', 'stdout'): sudo('echo -n "{}" > /etc/marathon-mesos.credentials'.format(password)) boot_args = ' '.join(['exec', '/usr/bin/marathon', '--http_credentials', '"{}:{}"'.format(principal, password), '--mesos_authentication_principal', principal, '--mesos_authentication_secret_file', '/etc/marathon-mesos.credentials']) # check if the init conf file contains the exact user and password if not file_contains(upstart_file, boot_args, use_sudo=True): sed(upstart_file, 'exec /usr/bin/marathon.*', boot_args, use_sudo=True) file_attribs(upstart_file, mode=700, sudo=True) restart_service('marathon')
<SYSTEM_TASK:> enables and adds a new authorized principal <END_TASK> <USER_TASK:> Description: def enable_mesos_basic_authentication(principal, password): """ enables and adds a new authorized principal """
restart = False secrets_file = '/etc/mesos/secrets' secrets_entry = '%s %s' % (principal, password) if not file_contains(filename=secrets_file, text=secrets_entry, use_sudo=True): file_append(filename=secrets_file, text=secrets_entry, use_sudo=True) file_attribs(secrets_file, mode=700, sudo=True) restart = True # set new startup parameters for mesos-master with quiet(): if secrets_file not in sudo('cat /etc/mesos-master/credentials'): sudo('echo %s > /etc/mesos-master/credentials' % secrets_file) restart = True if not exists('/etc/mesos-master/\?authenticate', use_sudo=True): sudo('touch /etc/mesos-master/\?authenticate') file_attribs('/etc/mesos-master/\?authenticate', mode=700, sudo=True) restart = True if restart: restart_service('mesos-master')
<SYSTEM_TASK:> returns an ipaddress for a rackspace instance <END_TASK> <USER_TASK:> Description: def get_ip_address_from_rackspace_server(server_id): """ returns an ipaddress for a rackspace instance """
nova = connect_to_rackspace() server = nova.servers.get(server_id) # the server was assigned IPv4 and IPv6 addresses, locate the IPv4 address ip_address = None for network in server.networks['public']: if re.match('\d+\.\d+\.\d+\.\d+', network): ip_address = network break # find out if we have an ip address if ip_address is None: log_red('No IP address assigned') return False else: return ip_address
<SYSTEM_TASK:> inserts a line in the middle of a file <END_TASK> <USER_TASK:> Description: def insert_line_in_file_after_regex(path, line, after_regex, use_sudo=False): """ inserts a line in the middle of a file """
tmpfile = str(uuid.uuid4()) get_file(path, tmpfile, use_sudo=use_sudo) with open(tmpfile) as f: original = f.read() if line not in original: outfile = str(uuid.uuid4()) with open(outfile, 'w') as output: for l in original.split('\n'): output.write(l + '\n') if re.match(after_regex, l) is not None: output.write(line + '\n') upload_file(local_path=outfile, remote_path=path, use_sudo=use_sudo) os.unlink(outfile) os.unlink(tmpfile)
<SYSTEM_TASK:> checks if vagrant plugin is installed <END_TASK> <USER_TASK:> Description: def is_vagrant_plugin_installed(plugin, use_sudo=False): """ checks if vagrant plugin is installed """
cmd = 'vagrant plugin list' if use_sudo: results = sudo(cmd) else: results = run(cmd) installed_plugins = [] for line in results: plugin = re.search('^(\S.*) \((.*)\)$', line) installed_plugins.append({'name': plugin.group(0), 'version': plugin.group(1)}) return installed_plugins
<SYSTEM_TASK:> checks if a particular deb package is installed <END_TASK> <USER_TASK:> Description: def is_deb_package_installed(pkg): """ checks if a particular deb package is installed """
with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): result = sudo('dpkg-query -l "%s" | grep -q ^.i' % pkg) return not bool(result.return_code)
<SYSTEM_TASK:> checks if ssh port is open <END_TASK> <USER_TASK:> Description: def is_ssh_available(host, port=22): """ checks if ssh port is open """
s = socket.socket() try: s.connect((host, port)) return True except: return False
<SYSTEM_TASK:> loads the state from a local data.json file <END_TASK> <USER_TASK:> Description: def load_state_from_disk(): """ loads the state from a local data.json file """
if is_there_state(): with open('data.json', 'r') as f: data = json.load(f) return data else: return False
<SYSTEM_TASK:> syncs the src code to the remote box <END_TASK> <USER_TASK:> Description: def rsync(): """ syncs the src code to the remote box """
log_green('syncing code to remote box...') data = load_state_from_disk() if 'SOURCE_PATH' in os.environ: with lcd(os.environ['SOURCE_PATH']): local("rsync -a " "--info=progress2 " "--exclude .git " "--exclude .tox " "--exclude .vagrant " "--exclude venv " ". " "-e 'ssh -C -i " + env.ec2_key_filename + "' " "%s@%s:" % (env.user, data['ip_address'])) else: print('please export SOURCE_PATH before running rsync') exit(1)
<SYSTEM_TASK:> queries EC2 for details about a particular instance_id and <END_TASK> <USER_TASK:> Description: def save_ec2_state_locally(instance_id, region, username, access_key_id, secret_access_key): """ queries EC2 for details about a particular instance_id and stores those details locally """
# retrieve the IP information from the instance data = get_ec2_info(instance_id, region, access_key_id, secret_access_key, username) return _save_state_locally(data)
<SYSTEM_TASK:> opens a ssh shell to the host <END_TASK> <USER_TASK:> Description: def ssh_session(key_filename, username, ip_address, *cli): """ opens a ssh shell to the host """
local('ssh -t -i %s %s@%s %s' % (key_filename, username, ip_address, "".join(chain.from_iterable(cli))))
<SYSTEM_TASK:> probes the ssh port and waits until it is available <END_TASK> <USER_TASK:> Description: def wait_for_ssh(host, port=22, timeout=600): """ probes the ssh port and waits until it is available """
log_yellow('waiting for ssh...') for iteration in xrange(1, timeout): #noqa sleep(1) if is_ssh_available(host, port): return True else: log_yellow('waiting for ssh...')
<SYSTEM_TASK:> List model instances. <END_TASK> <USER_TASK:> Description: def list(self, filters=None): """List model instances. Currently this gets *everything* and iterates through all possible pages in the API. This may be unsuitable for production environments with huge databases, so finer grained page support should likely be added at some point. Args: filters (dict, optional): API query filters to apply to the request. For example: .. code-block:: python {'name__startswith': 'azure', 'user__in': [1, 2, 3, 4],} See saltant's API reference at https://saltant-org.github.io/saltant/ for each model's available filters. Returns: list: A list of :class:`saltant.models.resource.Model` subclass instances (for example, container task type model instances). """
# Add in the page and page_size parameters to the filter, such # that our request gets *all* objects in the list. However, # don't do this if the user has explicitly included these # parameters in the filter. if not filters: filters = {} if "page" not in filters: filters["page"] = 1 if "page_size" not in filters: # The below "magic number" is 2^63 - 1, which is the largest # number you can hold in a 64 bit integer. The main point # here is that we want to get everything in one page (unless # otherwise specified, of course). filters["page_size"] = 9223372036854775807 # Form the request URL - first add in the query filters query_filter_sub_url = "" for idx, filter_param in enumerate(filters): # Prepend '?' or '&' if idx == 0: query_filter_sub_url += "?" else: query_filter_sub_url += "&" # Add in the query filter query_filter_sub_url += "{param}={val}".format( param=filter_param, val=filters[filter_param] ) # Stitch together all sub-urls request_url = ( self._client.base_api_url + self.list_url + query_filter_sub_url ) # Make the request response = self._client.session.get(request_url) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_200_OK, ) # Return a list of model instances return self.response_data_to_model_instances_list(response.json())
<SYSTEM_TASK:> Get the model instance with a given id. <END_TASK> <USER_TASK:> Description: def get(self, id): """Get the model instance with a given id. Args: id (int or str): The primary identifier (e.g., pk or UUID) for the task instance to get. Returns: :class:`saltant.models.resource.Model`: A :class:`saltant.models.resource.Model` subclass instance representing the resource requested. """
# Get the object request_url = self._client.base_api_url + self.detail_url.format(id=id) response = self._client.session.get(request_url) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_200_OK, ) # Return a model instance return self.response_data_to_model_instance(response.json())
<SYSTEM_TASK:> Validates that a request was successful. <END_TASK> <USER_TASK:> Description: def validate_request_success( response_text, request_url, status_code, expected_status_code ): """Validates that a request was successful. Args: response_text (str): The response body of the request. request_url (str): The URL the request was made at. status_code (int): The status code of the response. expected_status_code (int): The expected status code of the response. Raises: :class:`saltant.exceptions.BadHttpRequestError`: The HTTP request failed. """
try: assert status_code == expected_status_code except AssertionError: msg = ( "Request to {url} failed with status {status_code}:\n" "The reponse from the request was as follows:\n\n" "{content}" ).format( url=request_url, status_code=status_code, content=response_text ) raise BadHttpRequestError(msg)
<SYSTEM_TASK:> Create a task instance. <END_TASK> <USER_TASK:> Description: def create(self, task_type_id, task_queue_id, arguments=None, name=""): """Create a task instance. Args: task_type_id (int): The ID of the task type to base the task instance on. task_queue_id (int): The ID of the task queue to run the job on. arguments (dict, optional): The arguments to give the task type. name (str, optional): A non-unique name to give the task instance. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance just created. """
# Make arguments an empty dictionary if None if arguments is None: arguments = {} # Create the object request_url = self._client.base_api_url + self.list_url data_to_post = { "name": name, "arguments": json.dumps(arguments), "task_type": task_type_id, "task_queue": task_queue_id, } response = self._client.session.post(request_url, data=data_to_post) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_201_CREATED, ) # Return a model instance representing the task instance return self.response_data_to_model_instance(response.json())
<SYSTEM_TASK:> Clone the task instance with given UUID. <END_TASK> <USER_TASK:> Description: def clone(self, uuid): """Clone the task instance with given UUID. Args: uuid (str): The UUID of the task instance to clone. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance created due to the clone. """
# Clone the object request_url = self._client.base_api_url + self.clone_url.format( id=uuid ) response = self._client.session.post(request_url) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_201_CREATED, ) # Return a model instance return self.response_data_to_model_instance(response.json())
<SYSTEM_TASK:> Terminate the task instance with given UUID. <END_TASK> <USER_TASK:> Description: def terminate(self, uuid): """Terminate the task instance with given UUID. Args: uuid (str): The UUID of the task instance to terminate. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance that was told to terminate. """
# Clone the object request_url = self._client.base_api_url + self.terminate_url.format( id=uuid ) response = self._client.session.post(request_url) # Validate that the request was successful self.validate_request_success( response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_202_ACCEPTED, ) # Return a model instance return self.response_data_to_model_instance(response.json())
<SYSTEM_TASK:> Convert response data to a task instance model. <END_TASK> <USER_TASK:> Description: def response_data_to_model_instance(self, response_data): """Convert response data to a task instance model. Args: response_data (dict): The data from the request's response. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstance`: A task instance model instance representing the task instance from the reponse data. """
# Coerce datetime strings into datetime objects response_data["datetime_created"] = dateutil.parser.parse( response_data["datetime_created"] ) if response_data["datetime_finished"]: response_data["datetime_finished"] = dateutil.parser.parse( response_data["datetime_finished"] ) # Instantiate a model for the task instance return super( BaseTaskInstanceManager, self ).response_data_to_model_instance(response_data)
<SYSTEM_TASK:> Ensure all column names are unique identifiers. <END_TASK> <USER_TASK:> Description: def _ids_and_column_names(names, force_lower_case=False): """Ensure all column names are unique identifiers."""
fixed = OrderedDict() for name in names: identifier = RowWrapper._make_identifier(name) if force_lower_case: identifier = identifier.lower() while identifier in fixed: identifier = RowWrapper._increment_numeric_suffix(identifier) fixed[identifier] = name return fixed
<SYSTEM_TASK:> List all backends for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_backends(self, service_id, version_number): """List all backends for a particular service and version."""
content = self._fetch("/service/%s/version/%d/backend" % (service_id, version_number)) return map(lambda x: FastlyBackend(self, x), content)
<SYSTEM_TASK:> Create a backend for a particular service and version. <END_TASK> <USER_TASK:> Description: def create_backend(self, service_id, version_number, name, address, use_ssl=False, port=80, connect_timeout=1000, first_byte_timeout=15000, between_bytes_timeout=10000, error_threshold=0, max_conn=20, weight=100, auto_loadbalance=False, shield=None, request_condition=None, healthcheck=None, comment=None): """Create a backend for a particular service and version."""
body = self._formdata({ "name": name, "address": address, "use_ssl": use_ssl, "port": port, "connect_timeout": connect_timeout, "first_byte_timeout": first_byte_timeout, "between_bytes_timeout": between_bytes_timeout, "error_threshold": error_threshold, "max_conn": max_conn, "weight": weight, "auto_loadbalance": auto_loadbalance, "shield": shield, "request_condition": request_condition, "healthcheck": healthcheck, "comment": comment, }, FastlyBackend.FIELDS) content = self._fetch("/service/%s/version/%d/backend" % (service_id, version_number), method="POST", body=body) return FastlyBackend(self, content)
<SYSTEM_TASK:> Get the backend for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_backend(self, service_id, version_number, name): """Get the backend for a particular service and version."""
content = self._fetch("/service/%s/version/%d/backend/%s" % (service_id, version_number, name)) return FastlyBackend(self, content)
<SYSTEM_TASK:> Update the backend for a particular service and version. <END_TASK> <USER_TASK:> Description: def update_backend(self, service_id, version_number, name_key, **kwargs): """Update the backend for a particular service and version."""
body = self._formdata(kwargs, FastlyBackend.FIELDS) content = self._fetch("/service/%s/version/%d/backend/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyBackend(self, content)
<SYSTEM_TASK:> Get a list of all cache settings for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_cache_settings(self, service_id, version_number): """Get a list of all cache settings for a particular service and version."""
content = self._fetch("/service/%s/version/%d/cache_settings" % (service_id, version_number)) return map(lambda x: FastlyCacheSettings(self, x), content)
<SYSTEM_TASK:> Gets all conditions for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_conditions(self, service_id, version_number): """Gets all conditions for a particular service and version."""
content = self._fetch("/service/%s/version/%d/condition" % (service_id, version_number)) return map(lambda x: FastlyCondition(self, x), content)
<SYSTEM_TASK:> Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server. <END_TASK> <USER_TASK:> Description: def content_edge_check(self, url): """Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server."""
prefixes = ["http://", "https://"] for prefix in prefixes: if url.startswith(prefix): url = url[len(prefix):] break content = self._fetch("/content/edge_check/%s" % url) return content
<SYSTEM_TASK:> List all users from a specified customer id. <END_TASK> <USER_TASK:> Description: def list_customer_users(self, customer_id): """List all users from a specified customer id."""
content = self._fetch("/customer/users/%s" % customer_id) return map(lambda x: FastlyUser(self, x), content)
<SYSTEM_TASK:> List the directors for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_directors(self, service_id, version_number): """List the directors for a particular service and version."""
content = self._fetch("/service/%s/version/%d/director" % (service_id, version_number)) return map(lambda x: FastlyDirector(self, x), content)
<SYSTEM_TASK:> Create a director for a particular service and version. <END_TASK> <USER_TASK:> Description: def create_director(self, service_id, version_number, name, quorum=75, _type=FastlyDirectorType.RANDOM, retries=5, shield=None): """Create a director for a particular service and version."""
body = self._formdata({ "name": name, "quorum": quorum, "type": _type, "retries": retries, "shield": shield, }, FastlyDirector.FIELDS) content = self._fetch("/service/%s/version/%d/director" % (service_id, version_number), method="POST", body=body) return FastlyDirector(self, content)
<SYSTEM_TASK:> Get the director for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_director(self, service_id, version_number, name): """Get the director for a particular service and version."""
content = self._fetch("/service/%s/version/%d/director/%s" % (service_id, version_number, name)) return FastlyDirector(self, content)
<SYSTEM_TASK:> Update the director for a particular service and version. <END_TASK> <USER_TASK:> Description: def update_director(self, service_id, version_number, name_key, **kwargs): """Update the director for a particular service and version."""
body = self._formdata(kwargs, FastlyDirector.FIELDS) content = self._fetch("/service/%s/version/%d/director/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyDirector(self, content)
<SYSTEM_TASK:> Returns the relationship between a Backend and a Director. If the Backend has been associated with the Director, it returns a simple record indicating this. Otherwise, returns a 404. <END_TASK> <USER_TASK:> Description: def get_director_backend(self, service_id, version_number, director_name, backend_name): """Returns the relationship between a Backend and a Director. If the Backend has been associated with the Director, it returns a simple record indicating this. Otherwise, returns a 404."""
content = self._fetch("/service/%s/version/%d/director/%s/backend/%s" % (service_id, version_number, director_name, backend_name), method="GET") return FastlyDirectorBackend(self, content)
<SYSTEM_TASK:> Deletes the relationship between a Backend and a Director. The Backend is no longer considered a member of the Director and thus will not have traffic balanced onto it from this Director. <END_TASK> <USER_TASK:> Description: def delete_director_backend(self, service_id, version_number, director_name, backend_name): """Deletes the relationship between a Backend and a Director. The Backend is no longer considered a member of the Director and thus will not have traffic balanced onto it from this Director."""
content = self._fetch("/service/%s/version/%d/director/%s/backend/%s" % (service_id, version_number, director_name, backend_name), method="DELETE") return self._status(content)
<SYSTEM_TASK:> List the domains for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_domains(self, service_id, version_number): """List the domains for a particular service and version."""
content = self._fetch("/service/%s/version/%d/domain" % (service_id, version_number)) return map(lambda x: FastlyDomain(self, x), content)
<SYSTEM_TASK:> Create a domain for a particular service and version. <END_TASK> <USER_TASK:> Description: def create_domain(self, service_id, version_number, name, comment=None): """Create a domain for a particular service and version."""
body = self._formdata({ "name": name, "comment": comment, }, FastlyDomain.FIELDS) content = self._fetch("/service/%s/version/%d/domain" % (service_id, version_number), method="POST", body=body) return FastlyDomain(self, content)
<SYSTEM_TASK:> Get the domain for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_domain(self, service_id, version_number, name): """Get the domain for a particular service and version."""
content = self._fetch("/service/%s/version/%d/domain/%s" % (service_id, version_number, name)) return FastlyDomain(self, content)
<SYSTEM_TASK:> Update the domain for a particular service and version. <END_TASK> <USER_TASK:> Description: def update_domain(self, service_id, version_number, name_key, **kwargs): """Update the domain for a particular service and version."""
body = self._formdata(kwargs, FastlyDomain.FIELDS) content = self._fetch("/service/%s/version/%d/domain/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyDomain(self, content)
<SYSTEM_TASK:> Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly. <END_TASK> <USER_TASK:> Description: def check_domain(self, service_id, version_number, name): """Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly."""
content = self._fetch("/service/%s/version/%d/domain/%s/check" % (service_id, version_number, name)) return FastlyDomainCheck(self, content)
<SYSTEM_TASK:> Get the specified event log. <END_TASK> <USER_TASK:> Description: def get_event_log(self, object_id): """Get the specified event log."""
content = self._fetch("/event_log/%s" % object_id, method="GET") return FastlyEventLog(self, content)
<SYSTEM_TASK:> Retrieves all Header objects for a particular Version of a Service. <END_TASK> <USER_TASK:> Description: def list_headers(self, service_id, version_number): """Retrieves all Header objects for a particular Version of a Service."""
content = self._fetch("/service/%s/version/%d/header" % (service_id, version_number)) return map(lambda x: FastlyHeader(self, x), content)
<SYSTEM_TASK:> Modifies an existing Header object by name. <END_TASK> <USER_TASK:> Description: def update_header(self, service_id, version_number, name_key, **kwargs): """Modifies an existing Header object by name."""
body = self._formdata(kwargs, FastlyHeader.FIELDS) content = self._fetch("/service/%s/version/%d/header/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyHeader(self, content)
<SYSTEM_TASK:> List all of the healthchecks for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_healthchecks(self, service_id, version_number): """List all of the healthchecks for a particular service and version."""
content = self._fetch("/service/%s/version/%d/healthcheck" % (service_id, version_number)) return map(lambda x: FastlyHealthCheck(self, x), content)
<SYSTEM_TASK:> Create a healthcheck for a particular service and version. <END_TASK> <USER_TASK:> Description: def create_healthcheck(self, service_id, version_number, name, host, method="HEAD", path="/", http_version="1.1", timeout=1000, check_interval=5000, expected_response=200, window=5, threshold=3, initial=1): """Create a healthcheck for a particular service and version."""
body = self._formdata({ "name": name, "method": method, "host": host, "path": path, "http_version": http_version, "timeout": timeout, "check_interval": check_interval, "expected_response": expected_response, "window": window, "threshold": threshold, "initial": initial, }, FastlyHealthCheck.FIELDS) content = self._fetch("/service/%s/version/%d/healthcheck" % (service_id, version_number), method="POST", body=body) return FastlyHealthCheck(self, content)
<SYSTEM_TASK:> Get the healthcheck for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_healthcheck(self, service_id, version_number, name): """Get the healthcheck for a particular service and version."""
content = self._fetch("/service/%s/version/%d/healthcheck/%s" % (service_id, version_number, name)) return FastlyHealthCheck(self, content)
<SYSTEM_TASK:> Get the status and times of a recently completed purge. <END_TASK> <USER_TASK:> Description: def check_purge_status(self, purge_id): """Get the status and times of a recently completed purge."""
content = self._fetch("/purge?id=%s" % purge_id) return map(lambda x: FastlyPurgeStatus(self, x), content)
<SYSTEM_TASK:> Returns a list of all Request Settings objects for the given service and version. <END_TASK> <USER_TASK:> Description: def list_request_settings(self, service_id, version_number): """Returns a list of all Request Settings objects for the given service and version."""
content = self._fetch("/service/%s/version/%d/request_settings" % (service_id, version_number)) return map(lambda x: FastlyRequestSetting(self, x), content)
<SYSTEM_TASK:> Gets the specified Request Settings object. <END_TASK> <USER_TASK:> Description: def get_request_setting(self, service_id, version_number, name): """Gets the specified Request Settings object."""
content = self._fetch("/service/%s/version/%d/request_settings/%s" % (service_id, version_number, name)) return FastlyRequestSetting(self, content)
<SYSTEM_TASK:> Updates the specified Request Settings object. <END_TASK> <USER_TASK:> Description: def update_request_setting(self, service_id, version_number, name_key, **kwargs): """Updates the specified Request Settings object."""
body = self._formdata(kwargs, FastlyHealthCheck.FIELDS) content = self._fetch("/service/%s/version/%d/request_settings/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyRequestSetting(self, content)
<SYSTEM_TASK:> Returns all Response Objects for the specified service and version. <END_TASK> <USER_TASK:> Description: def list_response_objects(self, service_id, version_number): """Returns all Response Objects for the specified service and version."""
content = self._fetch("/service/%s/version/%d/response_object" % (service_id, version_number)) return map(lambda x: FastlyResponseObject(self, x), content)
<SYSTEM_TASK:> Creates a new Response Object. <END_TASK> <USER_TASK:> Description: def create_response_object(self, service_id, version_number, name, status="200", response="OK", content="", request_condition=None, cache_condition=None): """Creates a new Response Object."""
body = self._formdata({ "name": name, "status": status, "response": response, "content": content, "request_condition": request_condition, "cache_condition": cache_condition, }, FastlyResponseObject.FIELDS) content = self._fetch("/service/%s/version/%d/response_object" % (service_id, version_number), method="POST", body=body) return FastlyResponseObject(self, content)
<SYSTEM_TASK:> Gets the specified Response Object. <END_TASK> <USER_TASK:> Description: def get_response_object(self, service_id, version_number, name): """Gets the specified Response Object."""
content = self._fetch("/service/%s/version/%d/response_object/%s" % (service_id, version_number, name)) return FastlyResponseObject(self, content)
<SYSTEM_TASK:> Updates the specified Response Object. <END_TASK> <USER_TASK:> Description: def update_response_object(self, service_id, version_number, name_key, **kwargs): """Updates the specified Response Object."""
body = self._formdata(kwargs, FastlyResponseObject.FIELDS) content = self._fetch("/service/%s/version/%d/response_object/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyResponseObject(self, content)
<SYSTEM_TASK:> List detailed information on a specified service. <END_TASK> <USER_TASK:> Description: def get_service_details(self, service_id): """List detailed information on a specified service."""
content = self._fetch("/service/%s/details" % service_id) return FastlyService(self, content)
<SYSTEM_TASK:> Get a specific service by name. <END_TASK> <USER_TASK:> Description: def get_service_by_name(self, service_name): """Get a specific service by name."""
content = self._fetch("/service/search?name=%s" % service_name) return FastlyService(self, content)
<SYSTEM_TASK:> List the domains within a service. <END_TASK> <USER_TASK:> Description: def list_domains_by_service(self, service_id): """List the domains within a service."""
content = self._fetch("/service/%s/domain" % service_id, method="GET") return map(lambda x: FastlyDomain(self, x), content)
<SYSTEM_TASK:> Purge everything from a service. <END_TASK> <USER_TASK:> Description: def purge_service(self, service_id): """Purge everything from a service."""
content = self._fetch("/service/%s/purge_all" % service_id, method="POST") return self._status(content)
<SYSTEM_TASK:> Purge a particular service by a key. <END_TASK> <USER_TASK:> Description: def purge_service_by_key(self, service_id, key): """Purge a particular service by a key."""
content = self._fetch("/service/%s/purge/%s" % (service_id, key), method="POST") return self._status(content)
<SYSTEM_TASK:> Get the settings for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_settings(self, service_id, version_number): """Get the settings for a particular service and version."""
content = self._fetch("/service/%s/version/%d/settings" % (service_id, version_number)) return FastlySettings(self, content)
<SYSTEM_TASK:> Update the settings for a particular service and version. <END_TASK> <USER_TASK:> Description: def update_settings(self, service_id, version_number, settings={}): """Update the settings for a particular service and version."""
body = urllib.urlencode(settings) content = self._fetch("/service/%s/version/%d/settings" % (service_id, version_number), method="PUT", body=body) return FastlySettings(self, content)
<SYSTEM_TASK:> List all of the Syslogs for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_syslogs(self, service_id, version_number): """List all of the Syslogs for a particular service and version."""
content = self._fetch("/service/%s/version/%d/syslog" % (service_id, version_number)) return map(lambda x: FastlySyslog(self, x), content)
<SYSTEM_TASK:> Create a Syslog for a particular service and version. <END_TASK> <USER_TASK:> Description: def create_syslog(self, service_id, version_number, name, address, port=514, use_tls="0", tls_ca_cert=None, token=None, _format=None, response_condition=None): """Create a Syslog for a particular service and version."""
body = self._formdata({ "name": name, "address": address, "port": port, "use_tls": use_tls, "tls_ca_cert": tls_ca_cert, "token": token, "format": _format, "response_condition": response_condition, }, FastlySyslog.FIELDS) content = self._fetch("/service/%s/version/%d/syslog" % (service_id, version_number), method="POST", body=body) return FastlySyslog(self, content)
<SYSTEM_TASK:> Get the Syslog for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_syslog(self, service_id, version_number, name): """Get the Syslog for a particular service and version."""
content = self._fetch("/service/%s/version/%d/syslog/%s" % (service_id, version_number, name)) return FastlySyslog(self, content)
<SYSTEM_TASK:> Update the Syslog for a particular service and version. <END_TASK> <USER_TASK:> Description: def update_syslog(self, service_id, version_number, name_key, **kwargs): """Update the Syslog for a particular service and version."""
body = self._formdata(kwargs, FastlySyslog.FIELDS) content = self._fetch("/service/%s/version/%d/syslog/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlySyslog(self, content)
<SYSTEM_TASK:> Requests a password reset for the specified user. <END_TASK> <USER_TASK:> Description: def request_password_reset(self, user_id): """Requests a password reset for the specified user."""
content = self._fetch("/user/%s/password/request_reset" % (user_id), method="POST") return FastlyUser(self, content)
<SYSTEM_TASK:> List the uploaded VCLs for a particular service and version. <END_TASK> <USER_TASK:> Description: def list_vcls(self, service_id, version_number): """List the uploaded VCLs for a particular service and version."""
content = self._fetch("/service/%s/version/%d/vcl" % (service_id, version_number)) return map(lambda x: FastlyVCL(self, x), content)
<SYSTEM_TASK:> Upload a VCL for a particular service and version. <END_TASK> <USER_TASK:> Description: def upload_vcl(self, service_id, version_number, name, content, main=None, comment=None): """Upload a VCL for a particular service and version."""
body = self._formdata({ "name": name, "content": content, "comment": comment, "main": main, }, FastlyVCL.FIELDS) content = self._fetch("/service/%s/version/%d/vcl" % (service_id, version_number), method="POST", body=body) return FastlyVCL(self, content)
<SYSTEM_TASK:> Get the uploaded VCL for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_vcl(self, service_id, version_number, name, include_content=True): """Get the uploaded VCL for a particular service and version."""
content = self._fetch("/service/%s/version/%d/vcl/%s?include_content=%d" % (service_id, version_number, name, int(include_content))) return FastlyVCL(self, content)
<SYSTEM_TASK:> Get the uploaded VCL for a particular service and version with HTML syntax highlighting. <END_TASK> <USER_TASK:> Description: def get_vcl_html(self, service_id, version_number, name): """Get the uploaded VCL for a particular service and version with HTML syntax highlighting."""
content = self._fetch("/service/%s/version/%d/vcl/%s/content" % (service_id, version_number, name)) return content.get("content", None)
<SYSTEM_TASK:> Display the generated VCL for a particular service and version. <END_TASK> <USER_TASK:> Description: def get_generated_vcl(self, service_id, version_number): """Display the generated VCL for a particular service and version."""
content = self._fetch("/service/%s/version/%d/generated_vcl" % (service_id, version_number)) return FastlyVCL(self, content)
<SYSTEM_TASK:> Display the content of generated VCL with HTML syntax highlighting. <END_TASK> <USER_TASK:> Description: def get_generated_vcl_html(self, service_id, version_number): """Display the content of generated VCL with HTML syntax highlighting."""
content = self._fetch("/service/%s/version/%d/generated_vcl/content" % (service_id, version_number)) return content.get("content", None)
<SYSTEM_TASK:> Set the specified VCL as the main. <END_TASK> <USER_TASK:> Description: def set_main_vcl(self, service_id, version_number, name): """Set the specified VCL as the main."""
content = self._fetch("/service/%s/version/%d/vcl/%s/main" % (service_id, version_number, name), method="PUT") return FastlyVCL(self, content)
<SYSTEM_TASK:> Update the uploaded VCL for a particular service and version. <END_TASK> <USER_TASK:> Description: def update_vcl(self, service_id, version_number, name_key, **kwargs): """Update the uploaded VCL for a particular service and version."""
body = self._formdata(kwargs, FastlyVCL.FIELDS) content = self._fetch("/service/%s/version/%d/vcl/%s" % (service_id, version_number, name_key), method="PUT", body=body) return FastlyVCL(self, content)
<SYSTEM_TASK:> Create a version for a particular service. <END_TASK> <USER_TASK:> Description: def create_version(self, service_id, inherit_service_id=None, comment=None): """Create a version for a particular service."""
body = self._formdata({ "service_id": service_id, "inherit_service_id": inherit_service_id, "comment": comment, }, FastlyVersion.FIELDS) content = self._fetch("/service/%s/version" % service_id, method="POST", body=body) return FastlyVersion(self, content)
<SYSTEM_TASK:> Get the version for a particular service. <END_TASK> <USER_TASK:> Description: def get_version(self, service_id, version_number): """Get the version for a particular service."""
content = self._fetch("/service/%s/version/%d" % (service_id, version_number)) return FastlyVersion(self, content)
<SYSTEM_TASK:> Update a particular version for a particular service. <END_TASK> <USER_TASK:> Description: def update_version(self, service_id, version_number, **kwargs): """Update a particular version for a particular service."""
body = self._formdata(kwargs, FastlyVersion.FIELDS) content = self._fetch("/service/%s/version/%d/" % (service_id, version_number), method="PUT", body=body) return FastlyVersion(self, content)
<SYSTEM_TASK:> Clone the current configuration into a new version. <END_TASK> <USER_TASK:> Description: def clone_version(self, service_id, version_number): """Clone the current configuration into a new version."""
content = self._fetch("/service/%s/version/%d/clone" % (service_id, version_number), method="PUT") return FastlyVersion(self, content)
<SYSTEM_TASK:> Activate the current version. <END_TASK> <USER_TASK:> Description: def activate_version(self, service_id, version_number): """Activate the current version."""
content = self._fetch("/service/%s/version/%d/activate" % (service_id, version_number), method="PUT") return FastlyVersion(self, content)
<SYSTEM_TASK:> Deactivate the current version. <END_TASK> <USER_TASK:> Description: def deactivate_version(self, service_id, version_number): """Deactivate the current version."""
content = self._fetch("/service/%s/version/%d/deactivate" % (service_id, version_number), method="PUT") return FastlyVersion(self, content)
<SYSTEM_TASK:> Validate the version for a particular service and version. <END_TASK> <USER_TASK:> Description: def validate_version(self, service_id, version_number): """Validate the version for a particular service and version."""
content = self._fetch("/service/%s/version/%d/validate" % (service_id, version_number)) return self._status(content)
<SYSTEM_TASK:> Locks the specified version. <END_TASK> <USER_TASK:> Description: def lock_version(self, service_id, version_number): """Locks the specified version."""
content = self._fetch("/service/%s/version/%d/lock" % (service_id, version_number)) return self._status(content)
<SYSTEM_TASK:> Get all of the wordpresses for a specified service and version. <END_TASK> <USER_TASK:> Description: def list_wordpressess(self, service_id, version_number): """Get all of the wordpresses for a specified service and version."""
content = self._fetch("/service/%s/version/%d/wordpress" % (service_id, version_number)) return map(lambda x: FastlyWordpress(self, x), content)
<SYSTEM_TASK:> Create a wordpress for the specified service and version. <END_TASK> <USER_TASK:> Description: def create_wordpress(self, service_id, version_number, name, path, comment=None): """Create a wordpress for the specified service and version."""
body = self._formdata({ "name": name, "path": path, "comment": comment, }, FastlyWordpress.FIELDS) content = self._fetch("/service/%s/version/%d/wordpress" % (service_id, version_number), method="POST", body=body) return FastlyWordpress(self, content)
<SYSTEM_TASK:> Create attributes storing the best results for the O and H types <END_TASK> <USER_TASK:> Description: def serotype_escherichia(self): """ Create attributes storing the best results for the O and H types """
for sample in self.runmetadata.samples: # Initialise negative results to be overwritten when necessary sample[self.analysistype].best_o_pid = '-' sample[self.analysistype].o_genes = ['-'] sample[self.analysistype].o_set = ['-'] sample[self.analysistype].best_h_pid = '-' sample[self.analysistype].h_genes = ['-'] sample[self.analysistype].h_set = ['-'] if sample.general.bestassemblyfile != 'NA': if sample.general.closestrefseqgenus == 'Escherichia': o = dict() h = dict() for result, percentid in sample[self.analysistype].results.items(): if 'O' in result.split('_')[-1]: o.update({result: float(percentid)}) if 'H' in result.split('_')[-1]: h.update({result: float(percentid)}) # O try: sorted_o = sorted(o.items(), key=operator.itemgetter(1), reverse=True) sample[self.analysistype].best_o_pid = str(sorted_o[0][1]) sample[self.analysistype].o_genes = [gene for gene, pid in o.items() if str(pid) == sample[self.analysistype].best_o_pid] sample[self.analysistype].o_set = \ list(set(gene.split('_')[-1] for gene in sample[self.analysistype].o_genes)) except (KeyError, IndexError): pass # H try: sorted_h = sorted(h.items(), key=operator.itemgetter(1), reverse=True) sample[self.analysistype].best_h_pid = str(sorted_h[0][1]) sample[self.analysistype].h_genes = [gene for gene, pid in h.items() if str(pid) == sample[self.analysistype].best_h_pid] sample[self.analysistype].h_set = \ list(set(gene.split('_')[-1] for gene in sample[self.analysistype].h_genes)) except (KeyError, IndexError): pass
<SYSTEM_TASK:> Extract the names of the user-supplied targets <END_TASK> <USER_TASK:> Description: def gene_names(self): """ Extract the names of the user-supplied targets """
# Iterate through all the target names in the formatted targets file for record in SeqIO.parse(self.targets, 'fasta'): # Append all the gene names to the list of names self.genes.append(record.id)
<SYSTEM_TASK:> Create the report for the user-supplied targets <END_TASK> <USER_TASK:> Description: def report(self): """ Create the report for the user-supplied targets """
# Add all the genes to the header header = 'Sample,' data = str() with open(os.path.join(self.reportpath, '{at}.csv'.format(at=self.analysistype)), 'w') as report: write_header = True for sample in self.runmetadata: data += sample.name + ',' # Iterate through all the user-supplied target names for target in sorted(self.genes): write_results = False # There was an issue with 'target' not matching 'name' due to a dash being replaced by an underscore # only in 'name'. This will hopefully address this issue target = target.replace('-', '_') if write_header: header += '{target}_match_details,{target},'.format(target=target) for name, identity in sample[self.analysistype].results.items(): # Ensure that all dashes are replaced with underscores name = name.replace('-', '_') # If the current target matches the target in the header, add the data to the string if name == target: write_results = True gene_results = '{percent_id}% ({avgdepth} +/- {stddev}),{record},'\ .format(percent_id=identity, avgdepth=sample[self.analysistype].avgdepth[name], stddev=sample[self.analysistype].standarddev[name], record=sample[self.analysistype].sequences[target]) # Populate the data string appropriately data += gene_results # If the target is not present, write dashes to represent the results and sequence if not write_results: data += '-,-,' data += ' \n' write_header = False header += '\n' # Write the strings to the report report.write(header) report.write(data)
<SYSTEM_TASK:> we cant to call set_data to manually update <END_TASK> <USER_TASK:> Description: def set_data(self, *args): """we cant to call set_data to manually update"""
db = self.begining.get_data() or formats.DATE_DEFAULT df = self.end.get_data() or formats.DATE_DEFAULT jours = max((df - db).days + 1, 0) self.setText(str(jours) + (jours >= 2 and " jours" or " jour"))
<SYSTEM_TASK:> Store the modification. `value` should be dumped in DB compatible format. <END_TASK> <USER_TASK:> Description: def modifie(self, key: str, value: Any) -> None: """Store the modification. `value` should be dumped in DB compatible format."""
if key in self.FIELDS_OPTIONS: self.modifie_options(key, value) else: self.modifications[key] = value
<SYSTEM_TASK:> Convenience function which calls modifie on each element of dic <END_TASK> <USER_TASK:> Description: def modifie_many(self, dic: dict): """Convenience function which calls modifie on each element of dic"""
for i, v in dic.items(): self.modifie(i, v)
<SYSTEM_TASK:> Set options in modifications. <END_TASK> <USER_TASK:> Description: def modifie_options(self, field_option, value): """Set options in modifications. All options will be stored since it should be grouped in the DB."""
options = dict(self["options"] or {}, **{field_option: value}) self.modifications["options"] = options
<SYSTEM_TASK:> Takes a list of dict like objects and uses `champ_id` field as Id <END_TASK> <USER_TASK:> Description: def _from_list_dict(cls, list_dic): """Takes a list of dict like objects and uses `champ_id` field as Id"""
return cls({_convert_id(dic[cls.CHAMP_ID]): dict(dic) for dic in list_dic})
<SYSTEM_TASK:> Return a collection of access matching `pattern`. <END_TASK> <USER_TASK:> Description: def base_recherche_rapide(self, base, pattern, to_string_hook=None): """ Return a collection of access matching `pattern`. `to_string_hook` is an optionnal callable dict -> str to map record to string. Default to _record_to_string """
Ac = self.ACCES if pattern == "*": return groups.Collection(Ac(base, i) for i in self) if len(pattern) >= MIN_CHAR_SEARCH: # Needed chars. sub_patterns = pattern.split(" ") try: regexps = tuple(re.compile(sub_pattern, flags=re.I) for sub_pattern in sub_patterns) except re.error: return groups.Collection() def search(string): for regexp in regexps: if not regexp.search(string): return False return True to_string_hook = to_string_hook or self._record_to_string return groups.Collection(Ac(base, i) for i, p in self.items() if search(to_string_hook(p))) return groups.Collection()
<SYSTEM_TASK:> Return collection of acces whose field equal value <END_TASK> <USER_TASK:> Description: def select_by_field(self, base, field, value): """Return collection of acces whose field equal value"""
Ac = self.ACCES return groups.Collection(Ac(base, i) for i, row in self.items() if row[field] == value)