text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_bucket(self, bucket_name, headers=None, location=Location.DEFAULT, policy=None): """ Creates a new located bucket. By default it's in the USA. You can...
check_lowercase_bucketname(bucket_name) if policy: if headers: headers[self.provider.acl_header] = policy else: headers = {self.provider.acl_header : policy} if location == Location.DEFAULT: data = '' else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gen_decode(iterable): "A generator for de-unsynchronizing a byte iterable." sync = False for b in iterable: if sync and b & 0xE0: warn("Invalid unsynched data", Warning) if not (sync and b == 0x00): yield b sync = (b == 0xFF...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gen_encode(data): "A generator for unsynchronizing a byte iterable." sync = False for b in data: if sync and (b == 0x00 or b & 0xE0): yield 0x00 # Insert sync char yield b sync = (b == 0xFF) if sync: yield 0x00
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decode(data): "Decodes a syncsafe integer" value = 0 for b in data: if b > 127: # iTunes bug raise ValueError("Invalid syncsafe integer") value <<= 7 value += b return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(i, *, width=-1): """Encodes a nonnegative integer into syncsafe format When width > 0, then len(result) == width When width < 0, then len(result) >= a...
if i < 0: raise ValueError("value is negative") assert width != 0 data = bytearray() while i: data.append(i & 127) i >>= 7 if width > 0 and len(data) > width: raise ValueError("Integer too large") if len(data) < abs(width):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_message(self, body=''): """ Create new message of appropriate class. :type body: message body :param body: The body of the newly created message (optiona...
m = self.message_class(self, body) m.queue = self return m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, page_size=10, vtimeout=10): """Utility function to remove all messages from a queue"""
n = 0 l = self.get_messages(page_size, vtimeout) while l: for m in l: self.delete_message(m) n += 1 l = self.get_messages(page_size, vtimeout) return n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_to_file(self, fp, sep='\n'): """ Read all messages from the queue and persist them to file-like object. Messages are written to the file and the 'sep' s...
n = 0 m = self.read() while m: n += 1 fp.write(m.get_body()) if sep: fp.write(sep) self.delete_message(m) m = self.read() return n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 's...
fp = open(file_name, 'wb') n = self.save_to_file(fp, sep) fp.close() return n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 conta...
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(transport, query): """Query the Riemann server"""
with CommandLineClient(transport) as client: echo_event(client.query(query))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 :re...
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, sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_attributes(self, attrs): """ Delete just these attributes, not the whole object. :param attrs: Attributes to save, as a list of string names :type att...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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.unhealth...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 tem...
def _replace(match): upload, options = parse_match(match) return render_upload(upload, template_path, **options) return oembed_replace(substitute_uploads(content, _replace))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_meta(meta): """ Parse metadata of API Args: meta: metadata of API Returns: tuple(url_prefix, auth_header, resources) """
resources = {} for name in meta: if name.startswith("$"): continue resources[name] = resource = {} for action in meta[name]: if action.startswith("$"): continue url, httpmethod = res_to_url(name, action) resource[action] = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_core(url_prefix, auth_header, resources): """Generate res.core.js"""
code = '' code += "function(root, init) {\n" code += " var q = init('%(auth_header)s', '%(url_prefix)s');\n" %\ {'url_prefix': url_prefix, 'auth_header': auth_header} code += " var r = null;\n" for key in resources: code += " r = root.%(key)s = {};\n" % {'key': key} for a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_code(meta, prefix=None, node=False, min=False): """ Generate res.js Args: meta: tuple(url_prefix, auth_header, resources) or metadata of API Returns...
if isinstance(meta, dict): url_prefix, auth_header, resources = parse_meta(meta) else: url_prefix, auth_header, resources = meta if prefix is not None: url_prefix = prefix core = render_core(url_prefix, auth_header, resources) if min: filename = 'res.web.min.js' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resjs(url, dest='./res.js', prefix=None, node=False, min=False): """Generate res.js and save it"""
meta = requests.get(url, headers={'Accept': 'application/json'}).json() code = generate_code(meta, prefix, node, min) save_file(dest, code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_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 locati...
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('loadima...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_image(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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def md5sum(content): '''Calculate and returns an MD5 checksum for the specified content. :param content: text content :returns: hex-digest formatted MD5 checksum as a string ''' md5 = hashlib.md5() md5.update(force_bytes(content)) return md5.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_list_params(self, params, items, label): """Add an AWS API-compatible parameter list to a dictionary. :type params: dict :param params: The parameter ...
if isinstance(items, basestring): items = [items] for i in range(1, len(items) + 1): params['%s.%d' % (label, i)] = items[i - 1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 ...
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('u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_error(self, response, body): """ Handle raising the correct exception, depending on the error. Many errors share the same HTTP response code, meaning...
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, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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=...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 SendRawEma...
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_r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_domain(self, domain_name): """ Create a SimpleDB domain. :type domain_name: string :param domain_name: The name of the new domain :rtype: :class:`boto...
params = {'DomainName':domain_name} d = self.get_object('CreateDomain', params, Domain) d.name = domain_name return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_domain(self, domain_or_name): """ Delete a SimpleDB domain. .. caution:: This will delete the domain and all items within the domain. :type domain_or_...
domain, domain_name = self.get_domain_and_name(domain_or_name) params = {'DomainName':domain_name} return self.get_status('DeleteDomain', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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. :p...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_attributes(self, domain_or_name, item_name, attr_names=None, expected_value=None): """ Delete attributes from a given item in a domain. :type domain_o...
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_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_vpcs(self, vpc_ids=None, filters=None): """ Retrieve information about your VPCs. You can filter results to return information only about those VPCs ...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_route_tables(self, route_table_ids=None, filters=None): """ Retrieve information about your routing tables. You can filter results to return informat...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:...
params = { 'RouteTableId': route_table_id, 'SubnetId': subnet_id } result = self.get_object('AssociateRouteTable', params, ResultSet) return result.associationId
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_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 r...
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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_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...
params = { 'RouteTableId': route_table_id, 'DestinationCidrBlock': destination_cidr_block } return self.get_status('DeleteRoute', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_internet_gateways(self, internet_gateway_ids=None, filters=None): """ Get a list of internet gateways. You can filter results to return information a...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_...
params = { 'InternetGatewayId': internet_gateway_id, 'VpcId': vpc_id } return self.get_status('AttachInternetGateway', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 interne...
params = { 'InternetGatewayId': internet_gateway_id, 'VpcId': vpc_id } return self.get_status('DetachInternetGateway', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_customer_gateways(self, customer_gateway_ids=None, filters=None): """ Retrieve information about your CustomerGateways. You can filter results to ret...
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')] = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_customer_gateway(self, type, ip_address, bgp_asn): """ Create a new Customer Gateway :type type: str :param type: Type of VPN Connection. Only valid v...
params = {'Type' : type, 'IpAddress' : ip_address, 'BgpAsn' : bgp_asn} return self.get_object('CreateCustomerGateway', params, CustomerGateway)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_vpn_gateways(self, vpn_gateway_ids=None, filters=None): """ Retrieve information about your VpnGateways. You can filter results to return information...
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] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_vpn_gateway(self, type, availability_zone=None): """ Create a new Vpn Gateway :type type: str :param type: Type of VPN Connection. Only valid valid cu...
params = {'Type' : type} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateVpnGateway', params, VpnGateway)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_gat...
params = {'VpnGatewayId': vpn_gateway_id, 'VpcId' : vpc_id} return self.get_object('AttachVpnGateway', params, Attachment)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_subnets(self, subnet_ids=None, filters=None): """ Retrieve information about your Subnets. You can filter results to return information only about th...
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] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_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...
params = {'VpcId' : vpc_id, 'CidrBlock' : cidr_block} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateSubnet', params, Subnet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_dhcp_options(self, dhcp_options_ids=None): """ Retrieve information about your DhcpOptions. :type dhcp_options_ids: list :param dhcp_options_ids: A l...
params = {} if dhcp_options_ids: self.build_list_params(params, dhcp_options_ids, 'DhcpOptionsId') return self.get_list('DescribeDhcpOptions', params, [('item', DhcpOptions)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_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 y...
params = {'VpcId' : vpc_id, 'CidrBlock' : cidr_block} if availability_zone: params['AvailabilityZone'] = availability_zone return self.get_object('CreateDhcpOption', params, DhcpOptions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def associate_dhcp_options(self, dhcp_options_id, vpc_id): """ Associate a set of Dhcp Options with a VPC. :type dhcp_options_id: str :param dhcp_options_id: The...
params = {'DhcpOptionsId': dhcp_options_id, 'VpcId' : vpc_id} return self.get_status('AssociateDhcpOptions', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_vpn_connections(self, vpn_connection_ids=None, filters=None): """ Retrieve information about your VPN_CONNECTIONs. You can filter results to return i...
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')] = filte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_vpn_connection(self, type, customer_gateway_id, vpn_gateway_id): """ Create a new VPN Connection. :type type: str :param type: The type of VPN Connect...
params = {'Type' : type, 'CustomerGatewayId' : customer_gateway_id, 'VpnGatewayId' : vpn_gateway_id} return self.get_object('CreateVpnConnection', params, VpnConnection)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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}'.forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_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_RA...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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. :a...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:...
if not remove: return random.choice(cards) else: i = random.randrange(len(cards)) card = cards[i] del cards[i] return card
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ``l...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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`` tha...
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=lamb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
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] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_string(self, value): """Convert ASCII, Latin-1 or UTF-8 to pure Unicode"""
if not isinstance(value, str): return value try: return unicode(value, 'utf-8') except: # really, this should throw an exception. # in the interest of not breaking current # systems, however: arr = [] for ch in value: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ret...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def index_config(request): '''This view returns the index configuration of the current application as JSON. Currently, this consists of a Solr index url and the Fedora content models that this application expects to index. .. Note:: By default, Fedora system content models (such as ``fe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _permission_denied_check(request): '''Internal function to verify that access to this webservice is allowed. Currently, based on the value of EUL_INDEXER_ALLOWED_IPS in settings.py. :param request: HttpRequest ''' allowed_ips = settings.EUL_INDEXER_ALLOWED_IPS if allowed_ips != "ANY" and n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, validate=False): """ Update the instance's state information by making a call to fetch the current instance attributes from the service. :type v...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 stop...
rs = self.connection.stop_instances([self.id], force) if len(rs) > 0: self._update(rs[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify_attribute(self, attribute, value): """ Changes an attribute of this instance :type attribute: string :param attribute: The attribute you wish to chang...
return self.connection.modify_instance_attribute(self.id, attribute, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_load_balancers(self, load_balancer_names=None): """ Retrieve all load balancers associated with your account. :type load_balancer_names: list :keywor...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 regi...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_bal...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_balance...
params = {'LoadBalancerName' : load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceSta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 w...
params = {'LoadBalancerName' : name, 'HealthCheck.Timeout' : health_check.timeout, 'HealthCheck.Target' : health_check.target, 'HealthCheck.Interval' : health_check.interval, 'HealthCheck.UnhealthyThreshold' : health_check.unhealthy_thresh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): """ Sets the certificate that terminates the specified listener's SSL connection...
params = { 'LoadBalancerName' : lb_name, 'LoadBalancerPort' : lb_port, 'SSLCertificateId' : ssl_certificate_id, } return self.get_status('SetLoadBalancerListenerSSLCertificate', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): """ Generates a stickiness policy with sticky session lifetimes that follow that of an...
params = { 'CookieName' : name, 'LoadBalancerName' : lb_name, 'PolicyName' : policy_name, } return self.get_status('CreateAppCookieStickinessPolicy', params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 key in list(target_dict.keys()): if key not in src_dict: target_dict.pop(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_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-n...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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, descript...
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: par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_email_notification(self, hit_type, email, event_types=None): """ Performs a SetHITTypeNotification operation to set email notification for a specified HI...
return self._set_notification(hit_type, 'Email', email, event_types)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_rest_notification(self, hit_type, url, event_types=None): """ Performs a SetHITTypeNotification operation to set REST notification for a specified HIT ty...
return self._set_notification(hit_type, 'REST', url, event_types)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_notification(self, hit_type, transport, destination, event_types=None): """ Common SetHITTypeNotification operation to set notification for a specified ...
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. A...