text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Read all messages from the queue and persist them to local file. <END_TASK> <USER_TASK:> Description: def save_to_filename(self, file_name, sep='\n'): """ Read all messages from the queue and persist them to local file. Messages are written to the file and the 'sep' string is written in between messages. Messages are deleted from the queue after being written to the file. Returns the number of messages saved. """
fp = open(file_name, 'wb') n = self.save_to_file(fp, sep) fp.close() return n
<SYSTEM_TASK:> Load messages previously saved to S3. <END_TASK> <USER_TASK:> Description: def load_from_s3(self, bucket, prefix=None): """ Load messages previously saved to S3. """
n = 0 if prefix: prefix = '%s/' % prefix else: prefix = '%s/' % self.id[1:] rs = bucket.list(prefix=prefix) for key in rs: n += 1 m = self.new_message(key.get_contents_as_string()) self.write(m) return n
<SYSTEM_TASK:> Utility function to load messages from a file-like object to a queue <END_TASK> <USER_TASK:> Description: def load_from_file(self, fp, sep='\n'): """Utility function to load messages from a file-like object to a queue"""
n = 0 body = '' l = fp.readline() while l: if l == sep: m = Message(self, body) self.write(m) n += 1 print 'writing message %d' % n body = '' else: body = body + l l = fp.readline() return n
<SYSTEM_TASK:> Utility function to load messages from a local filename to a queue <END_TASK> <USER_TASK:> Description: def load_from_filename(self, file_name, sep='\n'): """Utility function to load messages from a local filename to a queue"""
fp = open(file_name, 'rb') n = self.load_from_file(fp, sep) fp.close() return n
<SYSTEM_TASK:> Echo a json dump of an object using click <END_TASK> <USER_TASK:> Description: def echo_event(data): """Echo a json dump of an object using click"""
return click.echo(json.dumps(data, sort_keys=True, indent=2))
<SYSTEM_TASK:> Connects to a Riemann server to send events or query the index <END_TASK> <USER_TASK:> Description: def main(ctx, host, port, transport_type, timeout, ca_certs): """Connects to a Riemann server to send events or query the index By default, will attempt to contact Riemann on localhost:5555 over TCP. The RIEMANN_HOST and RIEMANN_PORT environment variables can be used to configure the host and port used. Command line parameters will override the environment variables. Use `-T none` to test commands without actually connecting to a server. """
if transport_type == 'udp': if timeout is not None: ctx.fail('--timeout cannot be used with the UDP transport') transport = riemann_client.transport.UDPTransport(host, port) elif transport_type == 'tcp': transport = riemann_client.transport.TCPTransport(host, port, timeout) elif transport_type == 'tls': if ca_certs is None: ctx.fail('--ca-certs must be set when using the TLS transport') transport = riemann_client.transport.TLSTransport( host, port, timeout, ca_certs) elif transport_type == 'none': transport = riemann_client.transport.BlankTransport() ctx.obj = transport
<SYSTEM_TASK:> Send a single event to Riemann <END_TASK> <USER_TASK:> Description: def send(transport, time, state, host, description, service, tag, attribute, ttl, metric_f, echo): """Send a single event to Riemann"""
client = CommandLineClient(transport) event = client.create_event({ 'time': time, 'state': state, 'host': host, 'description': description, 'service': service, 'tags': tag, 'attributes': dict(attribute), 'ttl': ttl, 'metric_f': metric_f }) with client: client.send_event(event) if echo: echo_event(client.create_dict(event))
<SYSTEM_TASK:> Save just these few attributes, not the whole object <END_TASK> <USER_TASK:> Description: def put_attributes(self, attrs): """ Save just these few attributes, not the whole object :param attrs: Attributes to save, key->value dict :type attrs: dict :return: self :rtype: :class:`boto.sdb.db.model.Model` """
assert(isinstance(attrs, dict)), "Argument must be a dict of key->values to save" for prop_name in attrs: value = attrs[prop_name] prop = self.find_property(prop_name) assert(prop), "Property not found: %s" % prop_name self._manager.set_property(prop, self, prop_name, value) self.reload() return self
<SYSTEM_TASK:> Delete just these attributes, not the whole object. <END_TASK> <USER_TASK:> Description: def delete_attributes(self, attrs): """ Delete just these attributes, not the whole object. :param attrs: Attributes to save, as a list of string names :type attrs: list :return: self :rtype: :class:`boto.sdb.db.model.Model` """
assert(isinstance(attrs, list)), "Argument must be a list of names of keys to delete." self._manager.domain.delete_attributes(self.id, attrs) self.reload() return self
<SYSTEM_TASK:> Find a subclass with a given name <END_TASK> <USER_TASK:> Description: def find_subclass(cls, name): """Find a subclass with a given name"""
if name == cls.__name__: return cls for sc in cls.__sub_classes__: r = sc.find_subclass(name) if r != None: return r
<SYSTEM_TASK:> In the case where you have accessed an existing health check on a <END_TASK> <USER_TASK:> Description: def update(self): """ In the case where you have accessed an existing health check on a load balancer, this method applies this instance's health check values to the load balancer it is attached to. .. note:: This method will not do anything if the :py:attr:`access_point` attribute isn't set, as is the case with a newly instantiated HealthCheck instance. """
if not self.access_point: return new_hc = self.connection.configure_health_check(self.access_point, self) self.interval = new_hc.interval self.target = new_hc.target self.healthy_threshold = new_hc.healthy_threshold self.unhealthy_threshold = new_hc.unhealthy_threshold self.timeout = new_hc.timeout
<SYSTEM_TASK:> Utility method to handle calls to ECS and parsing of responses. <END_TASK> <USER_TASK:> Description: def get_response(self, action, params, page=0, itemSet=None): """ Utility method to handle calls to ECS and parsing of responses. """
params['Service'] = "AWSECommerceService" params['Operation'] = action if page: params['ItemPage'] = page response = self.make_request(None, params, "/onca/xml") body = response.read() boto.log.debug(body) if response.status != 200: boto.log.error('%s %s' % (response.status, response.reason)) boto.log.error('%s' % body) raise self.ResponseError(response.status, response.reason, body) if itemSet == None: rs = ItemSet(self, action, params, page) else: rs = itemSet h = handler.XmlHandler(rs, self) xml.sax.parseString(body, h) return rs
<SYSTEM_TASK:> Replace all uploaded file references in a content string with the <END_TASK> <USER_TASK:> Description: def render_uploads(content, template_path="adminfiles/render/"): """ Replace all uploaded file references in a content string with the results of rendering a template found under ``template_path`` with the ``FileUpload`` instance and the key=value options found in the file reference. So if "<<<my-uploaded-file:key=val:key2=val2>>>" is found in the content string, it will be replaced with the results of rendering the selected template with ``upload`` set to the ``FileUpload`` instance with slug "my-uploaded-file" and ``options`` set to {'key': 'val', 'key2': 'val2'}. If the given slug is not found, the reference is replaced with the empty string. If ``djangoembed`` or ``django-oembed`` is installed, also replaces OEmbed URLs with the appropriate embed markup. """
def _replace(match): upload, options = parse_match(match) return render_upload(upload, template_path, **options) return oembed_replace(substitute_uploads(content, _replace))
<SYSTEM_TASK:> Given a list of paths and a list of binary images this returns a <END_TASK> <USER_TASK:> Description: def find_debug_images(dsym_paths, binary_images): """Given a list of paths and a list of binary images this returns a dictionary of image addresses to the locations on the file system for all found images. """
images_to_load = set() with timedsection('iterimages0'): for image in binary_images: if get_image_cpu_name(image) is not None: images_to_load.add(image['uuid'].lower()) images = {} # Step one: load images that are named by their UUID with timedsection('loadimages-fast'): for uuid in list(images_to_load): for dsym_path in dsym_paths: fn = os.path.join(dsym_path, uuid) if os.path.isfile(fn): images[uuid] = fn images_to_load.discard(uuid) break # Otherwise fall back to loading images from the dsym bundle. Because # this loading strategy is pretty slow we do't actually want to use it # unless we have a path that looks like a bundle. As a result we # find all the paths which are bundles and then only process those. if images_to_load: slow_paths = [] for dsym_path in dsym_paths: if os.path.isdir(os.path.join(dsym_path, 'Contents')): slow_paths.append(dsym_path) with timedsection('loadimages-slow'): for dsym_path in slow_paths: dwarf_base = os.path.join(dsym_path, 'Contents', 'Resources', 'DWARF') if os.path.isdir(dwarf_base): for fn in os.listdir(dwarf_base): # Looks like a UUID we loaded, skip it if fn in images: continue full_fn = os.path.join(dwarf_base, fn) try: di = DebugInfo.open_path(full_fn) except DebugInfoError: continue for variant in di.get_variants(): uuid = str(variant.uuid) if uuid in images_to_load: images[uuid] = full_fn images_to_load.discard(uuid) rv = {} # Now resolve all the images. with timedsection('resolveimages'): for image in binary_images: cpu_name = get_image_cpu_name(image) if cpu_name is None: continue uid = image['uuid'].lower() if uid not in images: continue rv[parse_addr(image['image_addr'])] = images[uid] return rv
<SYSTEM_TASK:> Given an instruction address this locates the image this address <END_TASK> <USER_TASK:> Description: def find_image(self, addr): """Given an instruction address this locates the image this address is contained in. """
idx = bisect.bisect_left(self._image_addresses, parse_addr(addr)) if idx > 0: return self.images[self._image_addresses[idx - 1]]
<SYSTEM_TASK:> Add an AWS API-compatible parameter list to a dictionary. <END_TASK> <USER_TASK:> Description: def _build_list_params(self, params, items, label): """Add an AWS API-compatible parameter list to a dictionary. :type params: dict :param params: The parameter dictionary :type items: list :param items: Items to be included in the list :type label: string :param label: The parameter list's name """
if isinstance(items, basestring): items = [items] for i in range(1, len(items) + 1): params['%s.%d' % (label, i)] = items[i - 1]
<SYSTEM_TASK:> Make a call to the SES API. <END_TASK> <USER_TASK:> Description: def _make_request(self, action, params=None): """Make a call to the SES API. :type action: string :param action: The API method to use (e.g. SendRawEmail) :type params: dict :param params: Parameters that will be sent as POST data with the API call. """
ct = 'application/x-www-form-urlencoded; charset=UTF-8' headers = {'Content-Type': ct} params = params or {} params['Action'] = action for k, v in params.items(): if isinstance(v, unicode): # UTF-8 encode only if it's Unicode params[k] = v.encode('utf-8') response = super(SESConnection, self).make_request( 'POST', '/', headers=headers, data=urllib.urlencode(params) ) body = response.read() if response.status == 200: list_markers = ('VerifiedEmailAddresses', 'SendDataPoints') e = boto.jsonresponse.Element(list_marker=list_markers) h = boto.jsonresponse.XmlHandler(e, None) h.parse(body) return e else: # HTTP codes other than 200 are considered errors. Go through # some error handling to determine which exception gets raised, self._handle_error(response, body)
<SYSTEM_TASK:> Handle raising the correct exception, depending on the error. Many <END_TASK> <USER_TASK:> Description: def _handle_error(self, response, body): """ Handle raising the correct exception, depending on the error. Many errors share the same HTTP response code, meaning we have to get really kludgey and do string searches to figure out what went wrong. """
boto.log.error('%s %s' % (response.status, response.reason)) boto.log.error('%s' % body) if "Address blacklisted." in body: # Delivery failures happened frequently enough with the recipient's # email address for Amazon to blacklist it. After a day or three, # they'll be automatically removed, and delivery can be attempted # again (if you write the code to do so in your application). ExceptionToRaise = ses_exceptions.SESAddressBlacklistedError exc_reason = "Address blacklisted." elif "Email address is not verified." in body: # This error happens when the "Reply-To" value passed to # send_email() hasn't been verified yet. ExceptionToRaise = ses_exceptions.SESAddressNotVerifiedError exc_reason = "Email address is not verified." elif "Daily message quota exceeded." in body: # Encountered when your account exceeds the maximum total number # of emails per 24 hours. ExceptionToRaise = ses_exceptions.SESDailyQuotaExceededError exc_reason = "Daily message quota exceeded." elif "Maximum sending rate exceeded." in body: # Your account has sent above its allowed requests a second rate. ExceptionToRaise = ses_exceptions.SESMaxSendingRateExceededError exc_reason = "Maximum sending rate exceeded." elif "Domain ends with dot." in body: # Recipient address ends with a dot/period. This is invalid. ExceptionToRaise = ses_exceptions.SESDomainEndsWithDotError exc_reason = "Domain ends with dot." else: # This is either a common AWS error, or one that we don't devote # its own exception to. ExceptionToRaise = self.ResponseError exc_reason = response.reason raise ExceptionToRaise(response.status, exc_reason, body)
<SYSTEM_TASK:> Composes an email message based on input data, and then immediately <END_TASK> <USER_TASK:> Description: def send_email(self, source, subject, body, to_addresses, cc_addresses=None, bcc_addresses=None, format='text', reply_addresses=None, return_path=None, text_body=None, html_body=None): """Composes an email message based on input data, and then immediately queues the message for sending. :type source: string :param source: The sender's email address. :type subject: string :param subject: The subject of the message: A short summary of the content, which will appear in the recipient's inbox. :type body: string :param body: The message body. :type to_addresses: list of strings or string :param to_addresses: The To: field(s) of the message. :type cc_addresses: list of strings or string :param cc_addresses: The CC: field(s) of the message. :type bcc_addresses: list of strings or string :param bcc_addresses: The BCC: field(s) of the message. :type format: string :param format: The format of the message's body, must be either "text" or "html". :type reply_addresses: list of strings or string :param reply_addresses: The reply-to email address(es) for the message. If the recipient replies to the message, each reply-to address will receive the reply. :type return_path: string :param return_path: The email address to which bounce notifications are to be forwarded. If the message cannot be delivered to the recipient, then an error message will be returned from the recipient's ISP; this message will then be forwarded to the email address specified by the ReturnPath parameter. :type text_body: string :param text_body: The text body to send with this email. :type html_body: string :param html_body: The html body to send with this email. """
format = format.lower().strip() if body is not None: if format == "text": if text_body is not None: raise Warning("You've passed in both a body and a text_body; please choose one or the other.") text_body = body else: if html_body is not None: raise Warning("You've passed in both a body and an html_body; please choose one or the other.") html_body = body params = { 'Source': source, 'Message.Subject.Data': subject, } if return_path: params['ReturnPath'] = return_path if html_body is not None: params['Message.Body.Html.Data'] = html_body if text_body is not None: params['Message.Body.Text.Data'] = text_body if(format not in ("text","html")): raise ValueError("'format' argument must be 'text' or 'html'") if(not (html_body or text_body)): raise ValueError("No text or html body found for mail") self._build_list_params(params, to_addresses, 'Destination.ToAddresses.member') if cc_addresses: self._build_list_params(params, cc_addresses, 'Destination.CcAddresses.member') if bcc_addresses: self._build_list_params(params, bcc_addresses, 'Destination.BccAddresses.member') if reply_addresses: self._build_list_params(params, reply_addresses, 'ReplyToAddresses.member') return self._make_request('SendEmail', params)
<SYSTEM_TASK:> Sends an email message, with header and content specified by the <END_TASK> <USER_TASK:> Description: def send_raw_email(self, raw_message, source=None, destinations=None): """Sends an email message, with header and content specified by the client. The SendRawEmail action is useful for sending multipart MIME emails, with attachments or inline content. The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent. :type source: string :param source: The sender's email address. Amazon's docs say: If you specify the Source parameter, then bounce notifications and complaints will be sent to this email address. This takes precedence over any Return-Path header that you might include in the raw text of the message. :type raw_message: string :param raw_message: The raw text of the message. The client is responsible for ensuring the following: - Message must contain a header and a body, separated by a blank line. - All required header fields must be present. - Each part of a multipart MIME message must be formatted properly. - MIME content types must be among those supported by Amazon SES. Refer to the Amazon SES Developer Guide for more details. - Content must be base64-encoded, if MIME requires it. :type destinations: list of strings or string :param destinations: A list of destinations for the message. """
params = { 'RawMessage.Data': base64.b64encode(raw_message), } if source: params['Source'] = source if destinations: self._build_list_params(params, destinations, 'Destinations.member') return self._make_request('SendRawEmail', params)
<SYSTEM_TASK:> Create a SimpleDB domain. <END_TASK> <USER_TASK:> Description: def create_domain(self, domain_name): """ Create a SimpleDB domain. :type domain_name: string :param domain_name: The name of the new domain :rtype: :class:`boto.sdb.domain.Domain` object :return: The newly created domain """
params = {'DomainName':domain_name} d = self.get_object('CreateDomain', params, Domain) d.name = domain_name return d
<SYSTEM_TASK:> Delete a SimpleDB domain. <END_TASK> <USER_TASK:> Description: def delete_domain(self, domain_or_name): """ Delete a SimpleDB domain. .. caution:: This will delete the domain and all items within the domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :rtype: bool :return: True if successful """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name} return self.get_status('DeleteDomain', params)
<SYSTEM_TASK:> Get the Metadata for a SimpleDB domain. <END_TASK> <USER_TASK:> Description: def domain_metadata(self, domain_or_name): """ Get the Metadata for a SimpleDB domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :rtype: :class:`boto.sdb.domain.DomainMetaData` object :return: The newly created domain metadata object """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name} d = self.get_object('DomainMetadata', params, DomainMetaData) d.domain = domain return d
<SYSTEM_TASK:> Retrieve attributes for a given item in a domain. <END_TASK> <USER_TASK:> Description: def get_attributes(self, domain_or_name, item_name, attribute_names=None, consistent_read=False, item=None): """ Retrieve attributes for a given item in a domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :type item_name: string :param item_name: The name of the item whose attributes are being retrieved. :type attribute_names: string or list of strings :param attribute_names: An attribute name or list of attribute names. This parameter is optional. If not supplied, all attributes will be retrieved for the item. :type consistent_read: bool :param consistent_read: When set to true, ensures that the most recent data is returned. :type item: :class:`boto.sdb.item.Item` :keyword item: Instead of instantiating a new Item object, you may specify one to update. :rtype: :class:`boto.sdb.item.Item` :return: An Item with the requested attribute name/values set on it """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName' : domain_name, 'ItemName' : item_name} if consistent_read: params['ConsistentRead'] = 'true' if attribute_names: if not isinstance(attribute_names, list): attribute_names = [attribute_names] self.build_list_params(params, attribute_names, 'AttributeName') response = self.make_request('GetAttributes', params) body = response.read() if response.status == 200: if item == None: item = self.item_cls(domain, item_name) h = handler.XmlHandler(item, self) xml.sax.parseString(body, h) return item else: raise SDBResponseError(response.status, response.reason, body)
<SYSTEM_TASK:> Delete attributes from a given item in a domain. <END_TASK> <USER_TASK:> Description: def delete_attributes(self, domain_or_name, item_name, attr_names=None, expected_value=None): """ Delete attributes from a given item in a domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :type item_name: string :param item_name: The name of the item whose attributes are being deleted. :type attributes: dict, list or :class:`boto.sdb.item.Item` :param attributes: Either a list containing attribute names which will cause all values associated with that attribute name to be deleted or a dict or Item containing the attribute names and keys and list of values to delete as the value. If no value is supplied, all attribute name/values for the item will be deleted. :type expected_value: list :param expected_value: If supplied, this is a list or tuple consisting of a single attribute name and expected value. The list can be of the form: * ['name', 'value'] In which case the call will first verify that the attribute "name" of this item has a value of "value". If it does, the delete will proceed, otherwise a ConditionalCheckFailed error will be returned. The list can also be of the form: * ['name', True|False] which will simply check for the existence (True) or non-existence (False) of the attribute. :rtype: bool :return: True if successful """
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name, 'ItemName' : item_name} if attr_names: if isinstance(attr_names, list): self._build_name_list(params, attr_names) elif isinstance(attr_names, dict) or isinstance(attr_names, self.item_cls): self._build_name_value_list(params, attr_names) if expected_value: self._build_expected_value(params, expected_value) return self.get_status('DeleteAttributes', params)
<SYSTEM_TASK:> Retrieve information about your VPCs. You can filter results to <END_TASK> <USER_TASK:> Description: def get_all_vpcs(self, vpc_ids=None, filters=None): """ Retrieve information about your VPCs. You can filter results to return information only about those VPCs that match your search parameters. Otherwise, all VPCs associated with your account are returned. :type vpc_ids: list :param vpc_ids: A list of strings with the desired VPC ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the VPC (pending or available) - *cidrBlock*, CIDR block of the VPC - *dhcpOptionsId*, the ID of a set of DHCP options :rtype: list :return: A list of :class:`boto.vpc.vpc.VPC` """
params = {} if vpc_ids: self.build_list_params(params, vpc_ids, 'VpcId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1' % i)] = filter[1] i += 1 return self.get_list('DescribeVpcs', params, [('item', VPC)])
<SYSTEM_TASK:> Retrieve information about your routing tables. You can filter results <END_TASK> <USER_TASK:> Description: def get_all_route_tables(self, route_table_ids=None, filters=None): """ Retrieve information about your routing tables. You can filter results to return information only about those route tables that match your search parameters. Otherwise, all route tables associated with your account are returned. :type route_table_ids: list :param route_table_ids: A list of strings with the desired route table IDs. :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. :rtype: list :return: A list of :class:`boto.vpc.routetable.RouteTable` """
params = {} if route_table_ids: self.build_list_params(params, route_table_ids, "RouteTableId") if filters: self.build_filter_params(params, dict(filters)) return self.get_list('DescribeRouteTables', params, [('item', RouteTable)])
<SYSTEM_TASK:> Associates a route table with a specific subnet. <END_TASK> <USER_TASK:> Description: def associate_route_table(self, route_table_id, subnet_id): """ Associates a route table with a specific subnet. :type route_table_id: str :param route_table_id: The ID of the route table to associate. :type subnet_id: str :param subnet_id: The ID of the subnet to associate with. :rtype: str :return: The ID of the association created """
params = { 'RouteTableId': route_table_id, 'SubnetId': subnet_id } result = self.get_object('AssociateRouteTable', params, ResultSet) return result.associationId
<SYSTEM_TASK:> Creates a new route in the route table within a VPC. The route's target <END_TASK> <USER_TASK:> Description: def create_route(self, route_table_id, destination_cidr_block, gateway_id=None, instance_id=None): """ Creates a new route in the route table within a VPC. The route's target can be either a gateway attached to the VPC or a NAT instance in the VPC. :type route_table_id: str :param route_table_id: The ID of the route table for the route. :type destination_cidr_block: str :param destination_cidr_block: The CIDR address block used for the destination match. :type gateway_id: str :param gateway_id: The ID of the gateway attached to your VPC. :type instance_id: str :param instance_id: The ID of a NAT instance in your VPC. :rtype: bool :return: True if successful """
params = { 'RouteTableId': route_table_id, 'DestinationCidrBlock': destination_cidr_block } if gateway_id is not None: params['GatewayId'] = gateway_id elif instance_id is not None: params['InstanceId'] = instance_id return self.get_status('CreateRoute', params)
<SYSTEM_TASK:> Deletes a route from a route table within a VPC. <END_TASK> <USER_TASK:> Description: def delete_route(self, route_table_id, destination_cidr_block): """ Deletes a route from a route table within a VPC. :type route_table_id: str :param route_table_id: The ID of the route table with the route. :type destination_cidr_block: str :param destination_cidr_block: The CIDR address block used for destination match. :rtype: bool :return: True if successful """
params = { 'RouteTableId': route_table_id, 'DestinationCidrBlock': destination_cidr_block } return self.get_status('DeleteRoute', params)
<SYSTEM_TASK:> Get a list of internet gateways. You can filter results to return information <END_TASK> <USER_TASK:> Description: def get_all_internet_gateways(self, internet_gateway_ids=None, filters=None): """ Get a list of internet gateways. You can filter results to return information about only those gateways that you're interested in. :type internet_gateway_ids: list :param internet_gateway_ids: A list of strings with the desired gateway IDs. :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. """
params = {} if internet_gateway_ids: self.build_list_params(params, internet_gateway_ids, 'InternetGatewayId') if filters: self.build_filter_params(params, dict(filters)) return self.get_list('DescribeInternetGateways', params, [('item', InternetGateway)])
<SYSTEM_TASK:> Attach an internet gateway to a specific VPC. <END_TASK> <USER_TASK:> Description: def attach_internet_gateway(self, internet_gateway_id, vpc_id): """ Attach an internet gateway to a specific VPC. :type internet_gateway_id: str :param internet_gateway_id: The ID of the internet gateway to delete. :type vpc_id: str :param vpc_id: The ID of the VPC to attach to. :rtype: Bool :return: True if successful """
params = { 'InternetGatewayId': internet_gateway_id, 'VpcId': vpc_id } return self.get_status('AttachInternetGateway', params)
<SYSTEM_TASK:> Detach an internet gateway from a specific VPC. <END_TASK> <USER_TASK:> Description: def detach_internet_gateway(self, internet_gateway_id, vpc_id): """ Detach an internet gateway from a specific VPC. :type internet_gateway_id: str :param internet_gateway_id: The ID of the internet gateway to delete. :type vpc_id: str :param vpc_id: The ID of the VPC to attach to. :rtype: Bool :return: True if successful """
params = { 'InternetGatewayId': internet_gateway_id, 'VpcId': vpc_id } return self.get_status('DetachInternetGateway', params)
<SYSTEM_TASK:> Retrieve information about your CustomerGateways. You can filter results to <END_TASK> <USER_TASK:> Description: def get_all_customer_gateways(self, customer_gateway_ids=None, filters=None): """ Retrieve information about your CustomerGateways. You can filter results to return information only about those CustomerGateways that match your search parameters. Otherwise, all CustomerGateways associated with your account are returned. :type customer_gateway_ids: list :param customer_gateway_ids: A list of strings with the desired CustomerGateway ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the CustomerGateway (pending,available,deleting,deleted) - *type*, the type of customer gateway (ipsec.1) - *ipAddress* the IP address of customer gateway's internet-routable external inteface :rtype: list :return: A list of :class:`boto.vpc.customergateway.CustomerGateway` """
params = {} if customer_gateway_ids: self.build_list_params(params, customer_gateway_ids, 'CustomerGatewayId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1')] = filter[1] i += 1 return self.get_list('DescribeCustomerGateways', params, [('item', CustomerGateway)])
<SYSTEM_TASK:> Create a new Customer Gateway <END_TASK> <USER_TASK:> Description: def create_customer_gateway(self, type, ip_address, bgp_asn): """ Create a new Customer Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type ip_address: str :param ip_address: Internet-routable IP address for customer's gateway. Must be a static address. :type bgp_asn: str :param bgp_asn: Customer gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN) :rtype: The newly created CustomerGateway :return: A :class:`boto.vpc.customergateway.CustomerGateway` object """
params = {'Type' : type, 'IpAddress' : ip_address, 'BgpAsn' : bgp_asn} return self.get_object('CreateCustomerGateway', params, CustomerGateway)
<SYSTEM_TASK:> Retrieve information about your VpnGateways. You can filter results to <END_TASK> <USER_TASK:> Description: def get_all_vpn_gateways(self, vpn_gateway_ids=None, filters=None): """ Retrieve information about your VpnGateways. You can filter results to return information only about those VpnGateways that match your search parameters. Otherwise, all VpnGateways associated with your account are returned. :type vpn_gateway_ids: list :param vpn_gateway_ids: A list of strings with the desired VpnGateway ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the VpnGateway (pending,available,deleting,deleted) - *type*, the type of customer gateway (ipsec.1) - *availabilityZone*, the Availability zone the VPN gateway is in. :rtype: list :return: A list of :class:`boto.vpc.customergateway.VpnGateway` """
params = {} if vpn_gateway_ids: self.build_list_params(params, vpn_gateway_ids, 'VpnGatewayId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1')] = filter[1] i += 1 return self.get_list('DescribeVpnGateways', params, [('item', VpnGateway)])
<SYSTEM_TASK:> Create a new Vpn Gateway <END_TASK> <USER_TASK:> Description: def create_vpn_gateway(self, type, availability_zone=None): """ Create a new Vpn Gateway :type type: str :param type: Type of VPN Connection. Only valid valid currently is 'ipsec.1' :type availability_zone: str :param availability_zone: The Availability Zone where you want the VPN gateway. :rtype: The newly created VpnGateway :return: A :class:`boto.vpc.vpngateway.VpnGateway` object """
params = {'Type' : type} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateVpnGateway', params, VpnGateway)
<SYSTEM_TASK:> Attaches a VPN gateway to a VPC. <END_TASK> <USER_TASK:> Description: def attach_vpn_gateway(self, vpn_gateway_id, vpc_id): """ Attaches a VPN gateway to a VPC. :type vpn_gateway_id: str :param vpn_gateway_id: The ID of the vpn_gateway to attach :type vpc_id: str :param vpc_id: The ID of the VPC you want to attach the gateway to. :rtype: An attachment :return: a :class:`boto.vpc.vpngateway.Attachment` """
params = {'VpnGatewayId': vpn_gateway_id, 'VpcId' : vpc_id} return self.get_object('AttachVpnGateway', params, Attachment)
<SYSTEM_TASK:> Retrieve information about your Subnets. You can filter results to <END_TASK> <USER_TASK:> Description: def get_all_subnets(self, subnet_ids=None, filters=None): """ Retrieve information about your Subnets. You can filter results to return information only about those Subnets that match your search parameters. Otherwise, all Subnets associated with your account are returned. :type subnet_ids: list :param subnet_ids: A list of strings with the desired Subnet ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the Subnet (pending,available) - *vpdId*, the ID of teh VPC the subnet is in. - *cidrBlock*, CIDR block of the subnet - *availabilityZone*, the Availability Zone the subnet is in. :rtype: list :return: A list of :class:`boto.vpc.subnet.Subnet` """
params = {} if subnet_ids: self.build_list_params(params, subnet_ids, 'SubnetId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1' % i)] = filter[1] i += 1 return self.get_list('DescribeSubnets', params, [('item', Subnet)])
<SYSTEM_TASK:> Create a new Subnet <END_TASK> <USER_TASK:> Description: def create_subnet(self, vpc_id, cidr_block, availability_zone=None): """ Create a new Subnet :type vpc_id: str :param vpc_id: The ID of the VPC where you want to create the subnet. :type cidr_block: str :param cidr_block: The CIDR block you want the subnet to cover. :type availability_zone: str :param availability_zone: The AZ you want the subnet in :rtype: The newly created Subnet :return: A :class:`boto.vpc.customergateway.Subnet` object """
params = {'VpcId' : vpc_id, 'CidrBlock' : cidr_block} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateSubnet', params, Subnet)
<SYSTEM_TASK:> Create a new DhcpOption <END_TASK> <USER_TASK:> Description: def create_dhcp_options(self, vpc_id, cidr_block, availability_zone=None): """ Create a new DhcpOption :type vpc_id: str :param vpc_id: The ID of the VPC where you want to create the subnet. :type cidr_block: str :param cidr_block: The CIDR block you want the subnet to cover. :type availability_zone: str :param availability_zone: The AZ you want the subnet in :rtype: The newly created DhcpOption :return: A :class:`boto.vpc.customergateway.DhcpOption` object """
params = {'VpcId' : vpc_id, 'CidrBlock' : cidr_block} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateDhcpOption', params, DhcpOptions)
<SYSTEM_TASK:> Retrieve information about your VPN_CONNECTIONs. You can filter results to <END_TASK> <USER_TASK:> Description: def get_all_vpn_connections(self, vpn_connection_ids=None, filters=None): """ Retrieve information about your VPN_CONNECTIONs. You can filter results to return information only about those VPN_CONNECTIONs that match your search parameters. Otherwise, all VPN_CONNECTIONs associated with your account are returned. :type vpn_connection_ids: list :param vpn_connection_ids: A list of strings with the desired VPN_CONNECTION ID's :type filters: list of tuples :param filters: A list of tuples containing filters. Each tuple consists of a filter key and a filter value. Possible filter keys are: - *state*, the state of the VPN_CONNECTION pending,available,deleting,deleted - *type*, the type of connection, currently 'ipsec.1' - *customerGatewayId*, the ID of the customer gateway associated with the VPN - *vpnGatewayId*, the ID of the VPN gateway associated with the VPN connection :rtype: list :return: A list of :class:`boto.vpn_connection.vpnconnection.VpnConnection` """
params = {} if vpn_connection_ids: self.build_list_params(params, vpn_connection_ids, 'Vpn_ConnectionId') if filters: i = 1 for filter in filters: params[('Filter.%d.Name' % i)] = filter[0] params[('Filter.%d.Value.1')] = filter[1] i += 1 return self.get_list('DescribeVpnConnections', params, [('item', VpnConnection)])
<SYSTEM_TASK:> Create a new VPN Connection. <END_TASK> <USER_TASK:> Description: def create_vpn_connection(self, type, customer_gateway_id, vpn_gateway_id): """ Create a new VPN Connection. :type type: str :param type: The type of VPN Connection. Currently only 'ipsec.1' is supported :type customer_gateway_id: str :param customer_gateway_id: The ID of the customer gateway. :type vpn_gateway_id: str :param vpn_gateway_id: The ID of the VPN gateway. :rtype: The newly created VpnConnection :return: A :class:`boto.vpc.vpnconnection.VpnConnection` object """
params = {'Type' : type, 'CustomerGatewayId' : customer_gateway_id, 'VpnGatewayId' : vpn_gateway_id} return self.get_object('CreateVpnConnection', params, VpnConnection)
<SYSTEM_TASK:> Returns size of file, optionally leaving fp positioned at EOF. <END_TASK> <USER_TASK:> Description: def get_cur_file_size(fp, position_to_eof=False): """ Returns size of file, optionally leaving fp positioned at EOF. """
if not position_to_eof: cur_pos = fp.tell() fp.seek(0, os.SEEK_END) cur_file_size = fp.tell() if not position_to_eof: fp.seek(cur_pos, os.SEEK_SET) return cur_file_size
<SYSTEM_TASK:> Attempts a resumable download. <END_TASK> <USER_TASK:> Description: def _attempt_resumable_download(self, key, fp, headers, cb, num_cb, torrent, version_id): """ Attempts a resumable download. Raises ResumableDownloadException if any problems occur. """
cur_file_size = get_cur_file_size(fp, position_to_eof=True) if (cur_file_size and self.etag_value_for_current_download and self.etag_value_for_current_download == key.etag.strip('"\'')): # Try to resume existing transfer. if cur_file_size > key.size: raise ResumableDownloadException( '%s is larger (%d) than %s (%d).\nDeleting tracker file, so ' 'if you re-try this download it will start from scratch' % (fp.name, cur_file_size, str(storage_uri_for_key(key)), key.size), ResumableTransferDisposition.ABORT) elif cur_file_size == key.size: if key.bucket.connection.debug >= 1: print 'Download complete.' return if key.bucket.connection.debug >= 1: print 'Resuming download.' headers = headers.copy() headers['Range'] = 'bytes=%d-%d' % (cur_file_size, key.size - 1) cb = ByteTranslatingCallbackHandler(cb, cur_file_size).call self.download_start_point = cur_file_size else: if key.bucket.connection.debug >= 1: print 'Starting new resumable download.' self._save_tracker_info(key) self.download_start_point = 0 # Truncate the file, in case a new resumable download is being # started atop an existing file. fp.truncate(0) # Disable AWSAuthConnection-level retry behavior, since that would # cause downloads to restart from scratch. key.get_file(fp, headers, cb, num_cb, torrent, version_id, override_num_retries=0) fp.flush()
<SYSTEM_TASK:> Build authentication redirect url. <END_TASK> <USER_TASK:> Description: def get_redirect_url(self, request, callback, parameters=None): """Build authentication redirect url."""
args = self.get_redirect_args(request, callback=callback) additional = parameters or {} args.update(additional) params = urlencode(args) return '{0}?{1}'.format(self.authorization_url, params)
<SYSTEM_TASK:> Fetch the OAuth request token. Only required for OAuth 1.0. <END_TASK> <USER_TASK:> Description: def get_request_token(self, request, callback): """Fetch the OAuth request token. Only required for OAuth 1.0."""
callback = force_text(request.build_absolute_uri(callback)) try: response = self.request('post', self.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch request token: {0}'.format(e)) return None else: return response.text
<SYSTEM_TASK:> Builds a list containing a full French deck of 52 Card instances. The <END_TASK> <USER_TASK:> Description: def build_cards(jokers=False, num_jokers=0): """ Builds a list containing a full French deck of 52 Card instances. The cards are sorted according to ``DEFAULT_RANKS``. .. note: Adding jokers may break some functions & methods at the moment. :arg bool jokers: Whether or not to include jokers in the deck. :arg int num_jokers: The number of jokers to include. :returns: A list containing a full French deck of 52 Card instances. """
new_deck = [] if jokers: new_deck += [Card("Joker", None) for i in xrange(num_jokers)] new_deck += [Card(value, suit) for value in VALUES for suit in SUITS] return new_deck
<SYSTEM_TASK:> Checks whether the given cards are sorted by the given ranks. <END_TASK> <USER_TASK:> Description: def check_sorted(cards, ranks=None): """ Checks whether the given cards are sorted by the given ranks. :arg cards: The cards to check. Can be a ``Stack``, ``Deck``, or ``list`` of ``Card`` isntances. :arg dict ranks: The ranks to check against. Default is DEFAULT_RANKS. :returns: ``True`` or ``False``. """
ranks = ranks or DEFAULT_RANKS sorted_cards = sort_cards(cards, ranks) if cards == sorted_cards or cards[::-1] == sorted_cards: return True else: return False
<SYSTEM_TASK:> Checks a given search term against a given card's full name, suit, <END_TASK> <USER_TASK:> Description: def check_term(card, term): """ Checks a given search term against a given card's full name, suit, value, and abbreviation. :arg Card card: The card to check. :arg str term: The search term to check for. Can be a card full name, suit, value, or abbreviation. :returns: ``True`` or ``False``. """
check_list = [ x.lower() for x in [card.name, card.suit, card.value, card.abbrev, card.suit[0], card.value[0]] ] term = term.lower() for check in check_list: if check == term: return True return False
<SYSTEM_TASK:> Open cards from a txt file. <END_TASK> <USER_TASK:> Description: def open_cards(filename=None): """ Open cards from a txt file. :arg str filename: The filename of the deck file to open. If no filename given, defaults to "cards-YYYYMMDD.txt", where "YYYYMMDD" is the year, month, and day. For example, "cards-20140711.txt". :returns: The opened cards, as a list. """
filename = filename or "cards-%s.txt" % (time.strftime("%Y%m%d")) with open(filename, "r") as deck_file: card_data = [line.rstrip("\n") for line in deck_file.readlines()] cards = [None] * len(card_data) for i, card in enumerate(card_data): card = card.split() cards[i] = Card(card[0], card[1]) return cards
<SYSTEM_TASK:> Returns a random card from the Stack. If ``remove=True``, it will <END_TASK> <USER_TASK:> Description: def random_card(cards, remove=False): """ Returns a random card from the Stack. If ``remove=True``, it will also remove the card from the deck. :arg bool remove: Whether or not to remove the card from the deck. :returns: A random Card object, from the Stack. """
if not remove: return random.choice(cards) else: i = random.randrange(len(cards)) card = cards[i] del cards[i] return card
<SYSTEM_TASK:> Save the given cards, in plain text, to a txt file. <END_TASK> <USER_TASK:> Description: def save_cards(cards, filename=None): """ Save the given cards, in plain text, to a txt file. :arg cards: The cards to save. Can be a ``Stack``, ``Deck``, or ``list``. :arg str filename: The filename to use for the cards file. If no filename given, defaults to "cards-YYYYMMDD.txt", where "YYYYMMDD" is the year, month, and day. For example, "cards-20140711.txt". """
filename = filename or "cards-%s.txt" % (time.strftime("%Y%m%d")) with open(filename, "w") as deck_file: card_reprs = ["%s %s\n" % (card.value, card.suit) for card in cards] card_reprs[-1] = card_reprs[-1].rstrip("\n") for card in card_reprs: deck_file.write(card)
<SYSTEM_TASK:> Sorts the given Deck indices by the given ranks. Must also supply the <END_TASK> <USER_TASK:> Description: def sort_card_indices(cards, indices, ranks=None): """ Sorts the given Deck indices by the given ranks. Must also supply the ``Stack``, ``Deck``, or ``list`` that the indices are from. :arg cards: The cards the indices are from. Can be a ``Stack``, ``Deck``, or ``list`` :arg list indices: The indices to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: The sorted indices. """
ranks = ranks or DEFAULT_RANKS if ranks.get("suits"): indices = sorted( indices, key=lambda x: ranks["suits"][cards[x].suit] if cards[x].suit != None else 0 ) if ranks.get("values"): indices = sorted( indices, key=lambda x: ranks["values"][cards[x].value] ) return indices
<SYSTEM_TASK:> Sorts a given list of cards, either by poker ranks, or big two ranks. <END_TASK> <USER_TASK:> Description: def sort_cards(cards, ranks=None): """ Sorts a given list of cards, either by poker ranks, or big two ranks. :arg cards: The cards to sort. :arg dict ranks: The rank dict to reference for sorting. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: The sorted cards. """
ranks = ranks or DEFAULT_RANKS if ranks.get("suits"): cards = sorted( cards, key=lambda x: ranks["suits"][x.suit] if x.suit != None else 0 ) if ranks.get("values"): cards = sorted( cards, key=lambda x: ranks["values"][x.value] ) return cards
<SYSTEM_TASK:> Decode a single element for a map <END_TASK> <USER_TASK:> Description: def decode_map_element(self, item_type, value): """Decode a single element for a map"""
import urllib key = value if ":" in value: key, value = value.split(':',1) key = urllib.unquote(key) if Model in item_type.mro(): value = item_type(id=value) else: value = self.decode(item_type, value) return (key, value)
<SYSTEM_TASK:> Get the number of results that would <END_TASK> <USER_TASK:> Description: def count(self, cls, filters, quick=True, sort_by=None, select=None): """ Get the number of results that would be returned in this query """
query = "select count(*) from `%s` %s" % (self.domain.name, self._build_filter_part(cls, filters, sort_by, select)) count = 0 for row in self.domain.select(query): count += int(row['Count']) if quick: return count return count
<SYSTEM_TASK:> Get all decendents for a given class <END_TASK> <USER_TASK:> Description: def _get_all_decendents(self, cls): """Get all decendents for a given class"""
decendents = {} for sc in cls.__sub_classes__: decendents[sc.__name__] = sc decendents.update(self._get_all_decendents(sc)) return decendents
<SYSTEM_TASK:> Update the data associated with this snapshot by querying EC2. <END_TASK> <USER_TASK:> Description: def update(self, validate=False): """ Update the data associated with this snapshot by querying EC2. :type validate: bool :param validate: By default, if EC2 returns no data about the snapshot the update method returns quietly. If the validate param is True, however, it will raise a ValueError exception if no data is returned from EC2. """
rs = self.connection.get_all_snapshots([self.id]) if len(rs) > 0: self._update(rs[0]) elif validate: raise ValueError('%s is not a valid Snapshot ID' % self.id) return self.progress
<SYSTEM_TASK:> Compares the card against another card, ``other``, and checks whether <END_TASK> <USER_TASK:> Description: def ne(self, other, ranks=None): """ Compares the card against another card, ``other``, and checks whether the card is not equal to ``other``, based on the given rank dict. :arg Card other: The second Card to compare. :arg dict ranks: The ranks to refer to for comparisons. :returns: ``True`` or ``False``. """
ranks = ranks or DEFAULT_RANKS if isinstance(other, Card): if ranks.get("suits"): return ( ranks["values"][self.value] != ranks["values"][other.value] or ranks["suits"][self.suit] != ranks["suits"][other.suit] ) else: return ranks[self.value] != ranks[other.value] else: return False
<SYSTEM_TASK:> Update the instance's state information by making a call to fetch <END_TASK> <USER_TASK:> Description: def update(self, validate=False): """ Update the instance's state information by making a call to fetch the current instance attributes from the service. :type validate: bool :param validate: By default, if EC2 returns no data about the instance the update method returns quietly. If the validate param is True, however, it will raise a ValueError exception if no data is returned from EC2. """
rs = self.connection.get_all_instances([self.id]) if len(rs) > 0: r = rs[0] for i in r.instances: if i.id == self.id: self._update(i) elif validate: raise ValueError('%s is not a valid Instance ID' % self.id) return self.state
<SYSTEM_TASK:> Terminate the instance <END_TASK> <USER_TASK:> Description: def terminate(self): """ Terminate the instance """
rs = self.connection.terminate_instances([self.id]) if len(rs) > 0: self._update(rs[0])
<SYSTEM_TASK:> Stop the instance <END_TASK> <USER_TASK:> Description: def stop(self, force=False): """ Stop the instance :type force: bool :param force: Forces the instance to stop :rtype: list :return: A list of the instances stopped """
rs = self.connection.stop_instances([self.id], force) if len(rs) > 0: self._update(rs[0])
<SYSTEM_TASK:> Changes an attribute of this instance <END_TASK> <USER_TASK:> Description: def modify_attribute(self, attribute, value): """ Changes an attribute of this instance :type attribute: string :param attribute: The attribute you wish to change. AttributeName - Expected value (default) instanceType - A valid instance type (m1.small) kernel - Kernel ID (None) ramdisk - Ramdisk ID (None) userData - Base64 encoded String (None) disableApiTermination - Boolean (true) instanceInitiatedShutdownBehavior - stop|terminate rootDeviceName - device name (None) :type value: string :param value: The new value for the attribute :rtype: bool :return: Whether the operation succeeded or not """
return self.connection.modify_instance_attribute(self.id, attribute, value)
<SYSTEM_TASK:> Retrieve all load balancers associated with your account. <END_TASK> <USER_TASK:> Description: def get_all_load_balancers(self, load_balancer_names=None): """ Retrieve all load balancers associated with your account. :type load_balancer_names: list :keyword load_balancer_names: An optional list of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` """
params = {} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)])
<SYSTEM_TASK:> Add availability zones to an existing Load Balancer <END_TASK> <USER_TASK:> Description: def enable_availability_zones(self, load_balancer_name, zones_to_add): """ Add availability zones to an existing Load Balancer All zones must be in the same region as the Load Balancer Adding zones that are already registered with the Load Balancer has no effect. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type zones: List of strings :param zones: The name of the zone(s) to add. :rtype: List of strings :return: An updated list of zones for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') return self.get_list('EnableAvailabilityZonesForLoadBalancer', params, None)
<SYSTEM_TASK:> Remove availability zones from an existing Load Balancer. <END_TASK> <USER_TASK:> Description: def disable_availability_zones(self, load_balancer_name, zones_to_remove): """ Remove availability zones from an existing Load Balancer. All zones must be in the same region as the Load Balancer. Removing zones that are not registered with the Load Balancer has no effect. You cannot remove all zones from an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type zones: List of strings :param zones: The name of the zone(s) to remove. :rtype: List of strings :return: An updated list of zones for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') return self.get_list('DisableAvailabilityZonesForLoadBalancer', params, None)
<SYSTEM_TASK:> Add new Instances to an existing Load Balancer. <END_TASK> <USER_TASK:> Description: def register_instances(self, load_balancer_name, instances): """ Add new Instances to an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to add. :rtype: List of strings :return: An updated list of instances for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)])
<SYSTEM_TASK:> Remove Instances from an existing Load Balancer. <END_TASK> <USER_TASK:> Description: def deregister_instances(self, load_balancer_name, instances): """ Remove Instances from an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to remove. :rtype: List of strings :return: An updated list of instances for this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)])
<SYSTEM_TASK:> Get current state of all Instances registered to an Load Balancer. <END_TASK> <USER_TASK:> Description: def describe_instance_health(self, load_balancer_name, instances=None): """ Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to return status for. If not provided, the state of all instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances in this Load Balancer. """
params = {'LoadBalancerName' : load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)])
<SYSTEM_TASK:> Define a health check for the EndPoints. <END_TASK> <USER_TASK:> Description: def configure_health_check(self, name, health_check): """ Define a health check for the EndPoints. :type name: string :param name: The mnemonic name associated with the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object populated with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` """
params = {'LoadBalancerName' : name, 'HealthCheck.Timeout' : health_check.timeout, 'HealthCheck.Target' : health_check.target, 'HealthCheck.Interval' : health_check.interval, 'HealthCheck.UnhealthyThreshold' : health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold' : health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck)
<SYSTEM_TASK:> Sets the certificate that terminates the specified listener's SSL <END_TASK> <USER_TASK:> Description: def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): """ Sets the certificate that terminates the specified listener's SSL connections. The specified certificate replaces any prior certificate that was used on the same LoadBalancer and port. """
params = { 'LoadBalancerName' : lb_name, 'LoadBalancerPort' : lb_port, 'SSLCertificateId' : ssl_certificate_id, } return self.get_status('SetLoadBalancerListenerSSLCertificate', params)
<SYSTEM_TASK:> Generates a stickiness policy with sticky session lifetimes that follow <END_TASK> <USER_TASK:> Description: def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): """ Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can only be associated with HTTP listeners. This policy is similar to the policy created by CreateLBCookieStickinessPolicy, except that the lifetime of the special Elastic Load Balancing cookie follows the lifetime of the application-generated cookie specified in the policy configuration. The load balancer only inserts a new stickiness cookie when the application response includes a new application cookie. If the application cookie is explicitly removed or expires, the session stops being sticky until a new application cookie is issued. """
params = { 'CookieName' : name, 'LoadBalancerName' : lb_name, 'PolicyName' : policy_name, } return self.get_status('CreateAppCookieStickinessPolicy', params)
<SYSTEM_TASK:> Deletes a policy from the LoadBalancer. The specified policy must not <END_TASK> <USER_TASK:> Description: def delete_lb_policy(self, lb_name, policy_name): """ Deletes a policy from the LoadBalancer. The specified policy must not be enabled for any listeners. """
params = { 'LoadBalancerName' : lb_name, 'PolicyName' : policy_name, } return self.get_status('DeleteLoadBalancerPolicy', params)
<SYSTEM_TASK:> Remove keys from target_dict that are not available in src_dict <END_TASK> <USER_TASK:> Description: def remove_missing_keys(src_dict, target_dict): """ Remove keys from target_dict that are not available in src_dict :param src_dict: source dictionary to search for :param target_dict: target dictionary where keys should be removed """
for key in list(target_dict.keys()): if key not in src_dict: target_dict.pop(key)
<SYSTEM_TASK:> Creates all directories mentioned in the given path. <END_TASK> <USER_TASK:> Description: def create_dirs(path): """ Creates all directories mentioned in the given path. Useful to write a new file with the specified path. It carefully skips the file-name in the given path. :param path: Path of a file or directory """
fname = os.path.basename(path) # if file name exists in path, skip the filename if fname.__contains__('.'): path = os.path.dirname(path) if not os.path.exists(path): os.makedirs(path)
<SYSTEM_TASK:> Method returns results from response of Yahoo YQL API. It should returns always python list. <END_TASK> <USER_TASK:> Description: def fetch_data(self): """Method returns results from response of Yahoo YQL API. It should returns always python list."""
if relativedelta(self.end_date, self.start_date).years <= const.ONE_YEAR: data = self.request.send(self.symbol, self.start_date, self.end_date) else: data = self.fetch_chunk_data() return self.clean(data)
<SYSTEM_TASK:> Register a new HIT Type <END_TASK> <USER_TASK:> Description: def register_hit_type(self, title, description, reward, duration, keywords=None, approval_delay=None, qual_req=None): """ Register a new HIT Type title, description are strings reward is a Price object duration can be a timedelta, or an object castable to an int """
params = dict( Title=title, Description=description, AssignmentDurationInSeconds= self.duration_as_seconds(duration), ) params.update(MTurkConnection.get_price_as_price(reward).get_as_params('Reward')) if keywords: params['Keywords'] = self.get_keywords_as_string(keywords) if approval_delay is not None: d = self.duration_as_seconds(approval_delay) params['AutoApprovalDelayInSeconds'] = d if qual_req is not None: params.update(qual_req.get_as_params()) return self._process_request('RegisterHITType', params)
<SYSTEM_TASK:> Performs a SetHITTypeNotification operation to set email <END_TASK> <USER_TASK:> Description: def set_email_notification(self, hit_type, email, event_types=None): """ Performs a SetHITTypeNotification operation to set email notification for a specified HIT type """
return self._set_notification(hit_type, 'Email', email, event_types)
<SYSTEM_TASK:> Performs a SetHITTypeNotification operation to set REST notification <END_TASK> <USER_TASK:> Description: def set_rest_notification(self, hit_type, url, event_types=None): """ Performs a SetHITTypeNotification operation to set REST notification for a specified HIT type """
return self._set_notification(hit_type, 'REST', url, event_types)
<SYSTEM_TASK:> Common SetHITTypeNotification operation to set notification for a <END_TASK> <USER_TASK:> Description: def _set_notification(self, hit_type, transport, destination, event_types=None): """ Common SetHITTypeNotification operation to set notification for a specified HIT type """
assert type(hit_type) is str, "hit_type argument should be a string." params = {'HITTypeId': hit_type} # from the Developer Guide: # The 'Active' parameter is optional. If omitted, the active status of # the HIT type's notification specification is unchanged. All HIT types # begin with their notification specifications in the "inactive" status. notification_params = {'Destination': destination, 'Transport': transport, 'Version': boto.mturk.notification.NotificationMessage.NOTIFICATION_VERSION, 'Active': True, } # add specific event types if required if event_types: self.build_list_params(notification_params, event_types, 'EventType') # Set up dict of 'Notification.1.Transport' etc. values notification_rest_params = {} num = 1 for key in notification_params: notification_rest_params['Notification.%d.%s' % (num, key)] = notification_params[key] # Update main params dict params.update(notification_rest_params) # Execute operation return self._process_request('SetHITTypeNotification', params)
<SYSTEM_TASK:> Retrieve the HITs that have a status of Reviewable, or HITs that <END_TASK> <USER_TASK:> Description: def get_reviewable_hits(self, hit_type=None, status='Reviewable', sort_by='Expiration', sort_direction='Ascending', page_size=10, page_number=1): """ Retrieve the HITs that have a status of Reviewable, or HITs that have a status of Reviewing, and that belong to the Requester calling the operation. """
params = {'Status' : status, 'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number} # Handle optional hit_type argument if hit_type is not None: params.update({'HITTypeId': hit_type}) return self._process_request('GetReviewableHITs', params, [('HIT', HIT),])
<SYSTEM_TASK:> Return all of a Requester's HITs <END_TASK> <USER_TASK:> Description: def get_all_hits(self): """ Return all of a Requester's HITs Despite what search_hits says, it does not return all hits, but instead returns a page of hits. This method will pull the hits from the server 100 at a time, but will yield the results iteratively, so subsequent requests are made on demand. """
page_size = 100 search_rs = self.search_hits(page_size=page_size) total_records = int(search_rs.TotalNumResults) get_page_hits = lambda(page): self.search_hits(page_size=page_size, page_number=page) page_nums = self._get_pages(page_size, total_records) hit_sets = itertools.imap(get_page_hits, page_nums) return itertools.chain.from_iterable(hit_sets)
<SYSTEM_TASK:> Retrieves completed assignments for a HIT. <END_TASK> <USER_TASK:> Description: def get_assignments(self, hit_id, status=None, sort_by='SubmitTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None): """ Retrieves completed assignments for a HIT. Use this operation to retrieve the results for a HIT. The returned ResultSet will have the following attributes: NumResults The number of assignments on the page in the filtered results list, equivalent to the number of assignments being returned by this call. A non-negative integer PageNumber The number of the page in the filtered results list being returned. A positive integer TotalNumResults The total number of HITs in the filtered results list based on this call. A non-negative integer The ResultSet will contain zero or more Assignment objects """
params = {'HITId' : hit_id, 'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number} if status is not None: params['AssignmentStatus'] = status # Handle optional response groups argument if response_groups: self.build_list_params(params, response_groups, 'ResponseGroup') return self._process_request('GetAssignmentsForHIT', params, [('Assignment', Assignment),])
<SYSTEM_TASK:> Update a HIT with a status of Reviewable to have a status of Reviewing, <END_TASK> <USER_TASK:> Description: def set_reviewing(self, hit_id, revert=None): """ Update a HIT with a status of Reviewable to have a status of Reviewing, or reverts a Reviewing HIT back to the Reviewable status. Only HITs with a status of Reviewable can be updated with a status of Reviewing. Similarly, only Reviewing HITs can be reverted back to a status of Reviewable. """
params = {'HITId' : hit_id,} if revert: params['Revert'] = revert return self._process_request('SetHITAsReviewing', params)
<SYSTEM_TASK:> Remove a HIT from the Mechanical Turk marketplace, approves all <END_TASK> <USER_TASK:> Description: def disable_hit(self, hit_id, response_groups=None): """ Remove a HIT from the Mechanical Turk marketplace, approves all submitted assignments that have not already been approved or rejected, and disposes of the HIT and all assignment data. Assignments for the HIT that have already been submitted, but not yet approved or rejected, will be automatically approved. Assignments in progress at the time of the call to DisableHIT will be approved once the assignments are submitted. You will be charged for approval of these assignments. DisableHIT completely disposes of the HIT and all submitted assignment data. Assignment results data cannot be retrieved for a HIT that has been disposed. It is not possible to re-enable a HIT once it has been disabled. To make the work from a disabled HIT available again, create a new HIT. """
params = {'HITId' : hit_id,} # Handle optional response groups argument if response_groups: self.build_list_params(params, response_groups, 'ResponseGroup') return self._process_request('DisableHIT', params)
<SYSTEM_TASK:> Return information about the Mechanical Turk Service <END_TASK> <USER_TASK:> Description: def get_help(self, about, help_type='Operation'): """ Return information about the Mechanical Turk Service operations and response group NOTE - this is basically useless as it just returns the URL of the documentation help_type: either 'Operation' or 'ResponseGroup' """
params = {'About': about, 'HelpType': help_type,} return self._process_request('Help', params)
<SYSTEM_TASK:> Issues a payment of money from your account to a Worker. To <END_TASK> <USER_TASK:> Description: def grant_bonus(self, worker_id, assignment_id, bonus_price, reason): """ Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or rejected. This payment happens separately from the reward you pay to the Worker when you approve the Worker's assignment. The Bonus must be passed in as an instance of the Price object. """
params = bonus_price.get_as_params('BonusAmount', 1) params['WorkerId'] = worker_id params['AssignmentId'] = assignment_id params['Reason'] = reason return self._process_request('GrantBonus', params)
<SYSTEM_TASK:> Block a worker from working on my tasks. <END_TASK> <USER_TASK:> Description: def block_worker(self, worker_id, reason): """ Block a worker from working on my tasks. """
params = {'WorkerId': worker_id, 'Reason': reason} return self._process_request('BlockWorker', params)
<SYSTEM_TASK:> Unblock a worker from working on my tasks. <END_TASK> <USER_TASK:> Description: def unblock_worker(self, worker_id, reason): """ Unblock a worker from working on my tasks. """
params = {'WorkerId': worker_id, 'Reason': reason} return self._process_request('UnblockWorker', params)
<SYSTEM_TASK:> Send a text message to workers. <END_TASK> <USER_TASK:> Description: def notify_workers(self, worker_ids, subject, message_text): """ Send a text message to workers. """
params = {'Subject' : subject, 'MessageText': message_text} self.build_list_params(params, worker_ids, 'WorkerId') return self._process_request('NotifyWorkers', params)
<SYSTEM_TASK:> Create a new Qualification Type. <END_TASK> <USER_TASK:> Description: def create_qualification_type(self, name, description, status, keywords=None, retry_delay=None, test=None, answer_key=None, answer_key_xml=None, test_duration=None, auto_granted=False, auto_granted_value=1): """ Create a new Qualification Type. name: This will be visible to workers and must be unique for a given requester. description: description shown to workers. Max 2000 characters. status: 'Active' or 'Inactive' keywords: list of keyword strings or comma separated string. Max length of 1000 characters when concatenated with commas. retry_delay: number of seconds after requesting a qualification the worker must wait before they can ask again. If not specified, workers can only request this qualification once. test: a QuestionForm answer_key: an XML string of your answer key, for automatically scored qualification tests. (Consider implementing an AnswerKey class for this to support.) test_duration: the number of seconds a worker has to complete the test. auto_granted: if True, requests for the Qualification are granted immediately. Can't coexist with a test. auto_granted_value: auto_granted qualifications are given this value. """
params = {'Name' : name, 'Description' : description, 'QualificationTypeStatus' : status, } if retry_delay is not None: params['RetryDelayInSeconds'] = retry_delay if test is not None: assert(isinstance(test, QuestionForm)) assert(test_duration is not None) params['Test'] = test.get_as_xml() if test_duration is not None: params['TestDurationInSeconds'] = test_duration if answer_key is not None: if isinstance(answer_key, basestring): params['AnswerKey'] = answer_key # xml else: raise TypeError # Eventually someone will write an AnswerKey class. if auto_granted: assert(test is None) params['AutoGranted'] = True params['AutoGrantedValue'] = auto_granted_value if keywords: params['Keywords'] = self.get_keywords_as_string(keywords) return self._process_request('CreateQualificationType', params, [('QualificationType', QualificationType),])
<SYSTEM_TASK:> Returns a comma+space-separated string of keywords from either <END_TASK> <USER_TASK:> Description: def get_keywords_as_string(keywords): """ Returns a comma+space-separated string of keywords from either a list or a string """
if type(keywords) is list: keywords = ', '.join(keywords) if type(keywords) is str: final_keywords = keywords elif type(keywords) is unicode: final_keywords = keywords.encode('utf-8') elif keywords is None: final_keywords = "" else: raise TypeError("keywords argument must be a string or a list of strings; got a %s" % type(keywords)) return final_keywords
<SYSTEM_TASK:> Returns a Price data structure from either a float or a Price <END_TASK> <USER_TASK:> Description: def get_price_as_price(reward): """ Returns a Price data structure from either a float or a Price """
if isinstance(reward, Price): final_price = reward else: final_price = Price(reward) return final_price
<SYSTEM_TASK:> Has this HIT expired yet? <END_TASK> <USER_TASK:> Description: def _has_expired(self): """ Has this HIT expired yet? """
expired = False if hasattr(self, 'Expiration'): now = datetime.datetime.utcnow() expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ') expired = (now >= expiration) else: raise ValueError("ERROR: Request for expired property, but no Expiration in HIT!") return expired
<SYSTEM_TASK:> A generator function for listing versions in a bucket. <END_TASK> <USER_TASK:> Description: def versioned_bucket_lister(bucket, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None): """ A generator function for listing versions in a bucket. """
more_results = True k = None while more_results: rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker, version_id_marker=version_id_marker, delimiter=delimiter, headers=headers, max_keys=999) for k in rs: yield k key_marker = rs.next_key_marker version_id_marker = rs.next_version_id_marker more_results= rs.is_truncated
<SYSTEM_TASK:> A generator function for listing multipart uploads in a bucket. <END_TASK> <USER_TASK:> Description: def multipart_upload_lister(bucket, key_marker='', upload_id_marker='', headers=None): """ A generator function for listing multipart uploads in a bucket. """
more_results = True k = None while more_results: rs = bucket.get_all_multipart_uploads(key_marker=key_marker, upload_id_marker=upload_id_marker, headers=headers) for k in rs: yield k key_marker = rs.next_key_marker upload_id_marker = rs.next_upload_id_marker more_results= rs.is_truncated
<SYSTEM_TASK:> Store attributes for a given item. <END_TASK> <USER_TASK:> Description: def put_attributes(self, item_name, attributes, replace=True, expected_value=None): """ Store attributes for a given item. :type item_name: string :param item_name: The name of the item whose attributes are being stored. :type attribute_names: dict or dict-like object :param attribute_names: The name/value pairs to store as attributes :type expected_value: list :param expected_value: If supplied, this is a list or tuple consisting of a single attribute name and expected value. The list can be of the form: * ['name', 'value'] In which case the call will first verify that the attribute "name" of this item has a value of "value". If it does, the delete will proceed, otherwise a ConditionalCheckFailed error will be returned. The list can also be of the form: * ['name', True|False] which will simply check for the existence (True) or non-existence (False) of the attribute. :type replace: bool :param replace: Whether the attribute values passed in will replace existing values or will be added as addition values. Defaults to True. :rtype: bool :return: True if successful """
return self.connection.put_attributes(self, item_name, attributes, replace, expected_value)
<SYSTEM_TASK:> Store attributes for multiple items. <END_TASK> <USER_TASK:> Description: def batch_put_attributes(self, items, replace=True): """ Store attributes for multiple items. :type items: dict or dict-like object :param items: A dictionary-like object. The keys of the dictionary are the item names and the values are themselves dictionaries of attribute names/values, exactly the same as the attribute_names parameter of the scalar put_attributes call. :type replace: bool :param replace: Whether the attribute values passed in will replace existing values or will be added as addition values. Defaults to True. :rtype: bool :return: True if successful """
return self.connection.batch_put_attributes(self, items, replace)
<SYSTEM_TASK:> Retrieve attributes for a given item. <END_TASK> <USER_TASK:> Description: def get_attributes(self, item_name, attribute_name=None, consistent_read=False, item=None): """ Retrieve attributes for a given item. :type item_name: string :param item_name: The name of the item whose attributes are being retrieved. :type attribute_names: string or list of strings :param attribute_names: An attribute name or list of attribute names. This parameter is optional. If not supplied, all attributes will be retrieved for the item. :rtype: :class:`boto.sdb.item.Item` :return: An Item mapping type containing the requested attribute name/values """
return self.connection.get_attributes(self, item_name, attribute_name, consistent_read, item)