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 message(self, phone_number, message, message_type, **params): """ Send a message to the target phone_number. See https://developer.telesign.com/docs/messaging-api for detailed API documentation. """
return self.post(MESSAGING_RESOURCE, phone_number=phone_number, message=message, message_type=message_type, **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 status(self, reference_id, **params): """ Retrieves the current status of the message. See https://developer.telesign.com/docs/messaging-api for detailed API documentation. """
return self.get(MESSAGING_STATUS_RESOURCE.format(reference_id=reference_id), **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 phoneid(self, phone_number, **params): """ The PhoneID API provides a cleansed phone number, phone type, and telecom carrier information to determine the best communication method - SMS or voice. See https://developer.telesign.com/docs/phoneid-api for detailed API documentation. """
return self.post(PHONEID_RESOURCE.format(phone_number=phone_number), **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 copy(self): """Returns a new instance which identical to this instance."""
if self._pre_computed_hash is None: temp = ssdeep(buf="") else: temp = ssdeep(hash=hash) libssdeep_wrapper.fuzzy_free(temp._state) temp._state = libssdeep_wrapper.fuzzy_clone(self._state) temp._updatable = self._updatable temp._pre_computed_hash = self._pre_computed_hash return temp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, phone_number, message, message_type, **params): """ Send a voice call to the target phone_number. See https://developer.telesign.com/docs/voice-api for detailed API documentation. """
return self.post(VOICE_RESOURCE, phone_number=phone_number, message=message, message_type=message_type, **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 status(self, reference_id, **params): """ Retrieves the current status of the voice call. See https://developer.telesign.com/docs/voice-api for detailed API documentation. """
return self.get(VOICE_STATUS_RESOURCE.format(reference_id=reference_id), **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 status(self, external_id, **params): """ Retrieves the verification result for an App Verify transaction by external_id. To ensure a secure verification flow you must check the status using TeleSign's servers on your backend. Do not rely on the SDK alone to indicate a successful verification. See https://developer.telesign.com/docs/app-verify-android-sdk-self#section-get-status-service or https://developer.telesign.com/docs/app-verify-ios-sdk-self#section-get-status-service for detailed API documentation. """
return self.get(APPVERIFY_STATUS_RESOURCE.format(external_id=external_id), **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_asset_location(element, attr): """ Get Asset Location. Remove leading slash e.g '/static/images.jpg' ==> static/images.jpg Also, if the url is also prefixed with static, it would be removed. e.g static/image.jpg ==> image.jpg """
asset_location = re.match(r'^/?(static)?/?(.*)', element[attr], re.IGNORECASE) # replace relative links i.e (../../static) asset_location = asset_location.group(2).replace('../', '') return asset_location
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(matches, framework, namespace, static_endpoint): """ The actual transformation occurs here. flask example: images/staticfy.jpg', ==> "{{ url_for('static', filename='images/staticfy.jpg') }}" """
transformed = [] namespace = namespace + '/' if namespace else '' for attribute, elements in matches: for element in elements: asset_location = get_asset_location(element, attribute) # string substitution sub_dict = { 'static_endpoint': static_endpoint, 'namespace': namespace, 'asset_location': asset_location } transformed_string = frameworks[framework] % sub_dict res = (attribute, element[attribute], transformed_string) transformed.append(res) return transformed
<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_elements(html_file, tags): """ Extract all the elements we're interested in. Returns a list of tuples with the attribute as first item and the list of elements as the second item. """
with open(html_file) as f: document = BeautifulSoup(f, 'html.parser') def condition(tag, attr): # Don't include external links return lambda x: x.name == tag \ and not x.get(attr, 'http').startswith(('http', '//')) all_tags = [(attr, document.find_all(condition(tag, attr))) for tag, attr in tags] return all_tags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_lines(html_file, transformed): """Replace lines in the old file with the transformed lines."""
result = [] with codecs.open(html_file, 'r', 'utf-8') as input_file: for line in input_file: # replace all single quotes with double quotes line = re.sub(r'\'', '"', line) for attr, value, new_link in transformed: if attr in line and value in line: # replace old link with new staticfied link new_line = line.replace(value, new_link) result.append(new_line) break else: result.append(line) return ''.join(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def staticfy(html_file, args=argparse.ArgumentParser()): """ Staticfy method. Loop through each line of the file and replaces the old links """
# unpack arguments static_endpoint = args.static_endpoint or 'static' framework = args.framework or os.getenv('STATICFY_FRAMEWORK', 'flask') add_tags = args.add_tags or {} exc_tags = args.exc_tags or {} namespace = args.namespace or {} # default tags tags = {('img', 'src'), ('link', 'href'), ('script', 'src')} # generate additional_tags add_tags = {(tag, attr) for tag, attr in add_tags.items()} tags.update(add_tags) # remove tags if any was specified exc_tags = {(tag, attr) for tag, attr in exc_tags.items()} tags = tags - exc_tags # get elements we're interested in matches = get_elements(html_file, tags) # transform old links to new links transformed = transform(matches, framework, namespace, static_endpoint) return replace_lines(html_file, transformed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_ops(staticfied, args): """Write to stdout or a file"""
destination = args.o or args.output if destination: with open(destination, 'w') as file: file.write(staticfied) else: print(staticfied)
<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_keys(args): """Get keys specified in arguments returns list of keys or None """
key = args['--key'] if key: return [key] keyfile = args['--apikeys'] if keyfile: return read_keyfile(keyfile) envkey = os.environ.get('TINYPNG_API_KEY', None) if envkey: return [envkey] local_keys = join(abspath("."), "tinypng.keys") if isfile(local_keys): return read_keyfile(local_keys) home_keys = join(expanduser("~/.tinypng.keys")) if isfile(home_keys): return read_keyfile(home_keys) 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 get_shrunk_data(shrink_info): """Read shrunk file from tinypng.org api."""
out_url = shrink_info['output']['url'] try: return requests.get(out_url).content except HTTPError as err: if err.code != 404: raise exc = ValueError("Unable to read png file \"{0}\"".format(out_url)) exc.__cause__ = err raise exc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shrink_file(in_filepath, api_key=None, out_filepath=None): """Shrink png file and write it back to a new file The default file path replaces ".png" with ".tiny.png". returns api_info (including info['ouput']['filepath']) """
info = get_shrink_file_info(in_filepath, api_key, out_filepath) write_shrunk_file(info) return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_telesign_callback_signature(api_key, signature, json_str): """ Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature. :param api_key: the TeleSign API api_key associated with your account. :param signature: the TeleSign Authorization header value supplied in the callback, as a string. :param json_str: the POST body text, that is, the JSON string sent by TeleSign describing the transaction status. """
your_signature = b64encode(HMAC(b64decode(api_key), json_str.encode("utf-8"), sha256).digest()).decode("utf-8") if len(signature) != len(your_signature): return False # avoid timing attack with constant time equality check signatures_equal = True for x, y in zip(signature, your_signature): if not x == y: signatures_equal = False return signatures_equal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setposition(self, position): """ The move format is in long algebraic notation. Takes list of stirngs = ['e2e4', 'd7d5'] OR FEN = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1' """
try: if isinstance(position, list): self.send('position startpos moves {}'.format( self.__listtostring(position))) self.isready() elif re.match('\s*^(((?:[rnbqkpRNBQKP1-8]+\/){7})[rnbqkpRNBQKP1-8]+)\s([b|w])\s([K|Q|k|q|-]{1,4})\s(-|[a-h][1-8])\s(\d+\s\d+)$', position): regexList = re.match('\s*^(((?:[rnbqkpRNBQKP1-8]+\/){7})[rnbqkpRNBQKP1-8]+)\s([b|w])\s([K|Q|k|q|-]{1,4})\s(-|[a-h][1-8])\s(\d+\s\d+)$', position).groups() fen = regexList[0].split("/") if len(fen) != 8: raise ValueError("expected 8 rows in position part of fen: {0}".format(repr(fen))) for fenPart in fen: field_sum = 0 previous_was_digit, previous_was_piece = False, False for c in fenPart: if c in ["1", "2", "3", "4", "5", "6", "7", "8"]: if previous_was_digit: raise ValueError("two subsequent digits in position part of fen: {0}".format(repr(fen))) field_sum += int(c) previous_was_digit = True previous_was_piece = False elif c == "~": if not previous_was_piece: raise ValueError("~ not after piece in position part of fen: {0}".format(repr(fen))) previous_was_digit, previous_was_piece = False, False elif c.lower() in ["p", "n", "b", "r", "q", "k"]: field_sum += 1 previous_was_digit = False previous_was_piece = True else: raise ValueError("invalid character in position part of fen: {0}".format(repr(fen))) if field_sum != 8: raise ValueError("expected 8 columns per row in position part of fen: {0}".format(repr(fen))) self.send('position fen {}'.format(position)) self.isready() else: raise ValueError("fen doesn`t match follow this example: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 ") except ValueError as e: print('\nCheck position correctness\n') sys.exit(e.message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_item(self, host, key, value, clock=None, state=0): """ Add a single item into DataContainer :host: hostname to which item will be linked to :key: item key as defined in Zabbix :value: item value :clock: timestemp as integer. If not provided self.clock()) will be used """
if clock is None: clock = self.clock if self._config.data_type == "items": item = {"host": host, "key": key, "value": value, "clock": clock, "state": state} elif self._config.data_type == "lld": item = {"host": host, "key": key, "clock": clock, "state": state, "value": json.dumps({"data": value})} else: if self.logger: # pragma: no cover self.logger.error("Setup data_type before adding data") raise ValueError('Setup data_type before adding data') self._items_list.append(item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, data): """ Add a list of item into the container :data: dict of items & value per hostname """
for host in data: for key in data[host]: if not data[host][key] == []: self.add_item(host, key, data[host][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 _send_common(self, item): """ Common part of sending operations Calls SenderProtocol._send_to_zabbix Returns result as provided by _handle_response :item: either a list or a single item depending on debug_level """
total = len(item) processed = failed = time = 0 if self._config.dryrun is True: total = len(item) processed = failed = time = 0 response = 'dryrun' else: self._send_to_zabbix(item) response, processed, failed, total, time = self._read_from_zabbix() output_key = '(bulk)' output_item = '(bulk)' if self.debug_level >= 4: output_key = item[0]['key'] output_item = item[0]['value'] if self.logger: # pragma: no cover self.logger.info( "" + ZBX_DBG_SEND_RESULT % ( processed, failed, total, output_key, output_item, response ) ) return response, processed, failed, total, time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset(self): """ Reset main DataContainer properties """
# Reset DataContainer to default values # So that it can be reused if self.logger: # pragma: no cover self.logger.info("Reset DataContainer") self._items_list = [] self._config.data_type = 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 logger(self, value): """ Set logger instance for the class """
if isinstance(value, logging.Logger): self._logger = value else: if self._logger: # pragma: no cover self._logger.error("logger requires a logging instance") raise ValueError('logger requires a logging instance')
<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_issue(self, issue_id, params=None): """Returns a full representation of the issue for the given issue key. The issue JSON consists of the issue key and a collection of fields. Additional information like links to workflow transition sub-resources, or HTML rendered values of the fields supporting HTML rendering can be retrieved with expand request parameter specified. The fields request parameter accepts a comma-separated list of fields to include in the response. It can be used to retrieve a subset of fields. By default all fields are returned in the response. A particular field can be excluded from the response if prefixed with a "-" (minus) sign. Parameter can be provided multiple times on a single request. By default, all fields are returned in the response. Note: this is different from a JQL search - only navigable fields are returned by default (*navigable). Args: issue_id: params: Returns: """
return self._get(self.API_URL + 'issue/{}'.format(issue_id), params=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_issue(self, data, params=None): """Creates an issue or a sub-task from a JSON representation. You can provide two parameters in request's body: update or fields. The fields, that can be set on an issue create operation, can be determined using the /rest/api/2/issue/createmeta resource. If a particular field is not configured to appear on the issue's Create screen, then it will not be returned in the createmeta response. A field validation error will occur if such field is submitted in request. Creating a sub-task is similar to creating an issue with the following differences: issueType field must be set to a sub-task issue type (use /issue/createmeta to find sub-task issue types), and You must provide a parent field with the ID or key of the parent issue. Args: data: params: Returns: """
return self._post(self.API_URL + 'issue', data=data, params=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_issue(self, issue_id, params=None): """Deletes an individual issue. If the issue has sub-tasks you must set the deleteSubtasks=true parameter to delete the issue. You cannot delete an issue without deleting its sub-tasks. Args: issue_id: params: Returns: """
return self._delete(self.API_URL + 'issue/{}'.format(issue_id), params=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 list(self, pagination=True, page_size=None, page=None, **queryparams): """ Retrieves a list of objects. By default uses local cache and remote pagination If pagination is used and no page is requested (the default), all the remote objects are retrieved and appended in a single list. If pagination is disabled, all the objects are fetched from the endpoint and returned. This may trigger some parsing error if the result set is very large. :param pagination: Use pagination (default: `True`) :param page_size: Size of the pagination page (default: `100`). Any non numeric value will be casted to the default value :param page: Page number to retrieve (default: `None`). Ignored if `pagination` is `False` :param queryparams: Additional filter parameters as accepted by the remote API :return: <SearchableList> """
if page_size and pagination: try: page_size = int(page_size) except (ValueError, TypeError): page_size = 100 queryparams['page_size'] = page_size result = self.requester.get( self.instance.endpoint, query=queryparams, paginate=pagination ) objects = SearchableList() objects.extend(self.parse_list(result.json())) if result.headers.get('X-Pagination-Next', False) and not page: next_page = 2 else: next_page = None while next_page: pageparams = queryparams.copy() pageparams['page'] = next_page result = self.requester.get( self.instance.endpoint, query=pageparams, ) objects.extend(self.parse_list(result.json())) if result.headers.get('X-Pagination-Next', False): next_page += 1 else: next_page = None return objects
<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(cls, requester, entry): """ Turns a JSON object into a model instance. """
if not type(entry) is dict: return entry for key_to_parse, cls_to_parse in six.iteritems(cls.parser): if key_to_parse in entry: entry[key_to_parse] = cls_to_parse.parse( requester, entry[key_to_parse] ) return cls(requester, **entry)
<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_attribute(self, id, value, version=1): """ Set attribute to a specific value :param id: id of the attribute :param value: value of the attribute :param version: version of the attribute (default = 1) """
attributes = self._get_attributes(cache=True) formatted_id = '{0}'.format(id) attributes['attributes_values'][formatted_id] = value response = self.requester.patch( '/{endpoint}/custom-attributes-values/{id}', endpoint=self.endpoint, id=self.id, payload={ 'attributes_values': attributes['attributes_values'], 'version': version } ) cache_key = self.requester.get_full_url( '/{endpoint}/custom-attributes-values/{id}', endpoint=self.endpoint, id=self.id ) self.requester.cache.put(cache_key, response) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issues_stats(self): """ Get stats for issues of the project """
response = self.requester.get( '/{endpoint}/{id}/issues_stats', endpoint=self.endpoint, id=self.id ) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def like(self): """ Like the project """
self.requester.post( '/{endpoint}/{id}/like', endpoint=self.endpoint, id=self.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 unlike(self): """ Unlike the project """
self.requester.post( '/{endpoint}/{id}/unlike', endpoint=self.endpoint, id=self.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 star(self): """ Stars the project .. deprecated:: 0.8.5 Update Taiga and use like instead """
warnings.warn( "Deprecated! Update Taiga and use .like() instead", DeprecationWarning ) self.requester.post( '/{endpoint}/{id}/star', endpoint=self.endpoint, id=self.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 get(self, resource_id): """ Get a history element """
response = self.requester.get( '/{endpoint}/{entity}/{id}', endpoint=self.endpoint, entity=self.entity, id=resource_id, paginate=False ) return response.json()
<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(cls, value): """Takes a class and a dict and try to build an instance of the class :param cls: The class to parse :param value: either a dict, a list or a scalar value """
if is_list_annotation(cls): if not isinstance(value, list): raise TypeError('Could not parse {} because value is not a list'.format(cls)) return [parse(cls.__args__[0], o) for o in value] else: return GenericParser(cls, ModelProviderImpl()).parse(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 convert_ensembl_to_entrez(self, ensembl): """Convert Ensembl Id to Entrez Gene Id"""
if 'ENST' in ensembl: pass else: raise (IndexError) # Submit resquest to NCBI eutils/Gene database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format( ensembl) r = requests.get(server, headers={"Content-Type": "text/xml"}) if not r.ok: r.raise_for_status() sys.exit() # Process Request response = r.text info = xmltodict.parse(response) try: geneId = info['eSearchResult']['IdList']['Id'] except TypeError: raise (TypeError) return geneId
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_entrez_to_uniprot(self, entrez): """Convert Entrez Id to Uniprot Id"""
server = "http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml".format(entrez) r = requests.get(server, headers={"Content-Type": "text/xml"}) if not r.ok: r.raise_for_status() sys.exit() response = r.text info = xmltodict.parse(response) try: data = info['uniprot']['entry']['accession'][0] return data except TypeError: data = info['uniprot']['entry'][0]['accession'][0] return 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 convert_uniprot_to_entrez(self, uniprot): """Convert Uniprot Id to Entrez Id"""
# Submit request to NCBI eutils/Gene Database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format( uniprot) r = requests.get(server, headers={"Content-Type": "text/xml"}) if not r.ok: r.raise_for_status() sys.exit() # Process Request response = r.text info = xmltodict.parse(response) geneId = info['eSearchResult']['IdList']['Id'] # check to see if more than one result is returned # if you have more than more result then check which Entrez Id returns the same uniprot Id entered. if len(geneId) > 1: for x in geneId: c = self.convert_entrez_to_uniprot(x) c = c.lower() u = uniprot.lower() if c == u: return x else: return geneId
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_accession_to_taxid(self, accessionid): """Convert Accession Id to Tax Id """
# Submit request to NCBI eutils/Taxonomy Database server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" + self.options + "&db=nuccore&id={0}&retmode=xml".format( accessionid) r = requests.get(server, headers={"Content-Type": "text/xml"}) if not r.ok: r.raise_for_status() sys.exit() # Process Request response = r.text records = xmltodict.parse(response) try: for i in records['GBSet']['GBSeq']['GBSeq_feature-table']['GBFeature']['GBFeature_quals']['GBQualifier']: for key, value in i.items(): if value == 'db_xref': taxid = i['GBQualifier_value'] taxid = taxid.split(':')[1] return taxid except: for i in records['GBSet']['GBSeq']['GBSeq_feature-table']['GBFeature'][0]['GBFeature_quals']['GBQualifier']: for key, value in i.items(): if value == 'db_xref': taxid = i['GBQualifier_value'] taxid = taxid.split(':')[1] return taxid 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 convert_symbol_to_entrezid(self, symbol): """Convert Symbol to Entrez Gene Id"""
entrezdict = {} server = "http://rest.genenames.org/fetch/symbol/{0}".format(symbol) r = requests.get(server, headers={"Content-Type": "application/json"}) if not r.ok: r.raise_for_status() sys.exit() response = r.text info = xmltodict.parse(response) for data in info['response']['result']['doc']['str']: if data['@name'] == 'entrez_id': entrezdict[data['@name']] = data['#text'] if data['@name'] == 'symbol': entrezdict[data['@name']] = data['#text'] return entrezdict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_local_message(message_format, *args): """ Log a request so that it matches our local log format. """
prefix = '{} {}'.format(color('INFO', fg=248), color('request', fg=5)) message = message_format % args sys.stderr.write('{} {}\n'.format(prefix, message))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(obj): """Takes a object and produces a dict-like representation :param obj: the object to serialize """
if isinstance(obj, list): return [serialize(o) for o in obj] return GenericSerializer(ModelProviderImpl()).serialize(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def of(self, *indented_blocks) -> "CodeBlock": """ By default, marks the block as expecting an indented "body" blocks of which are then supplied as arguments to this method. Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones, this will generate a "pass" statement as the body. If there is a "closed_by" specified, then that will be used on the same indentation level as the opening of the block. After all the arguments have been handled, this block is marked as finalised and no more blocks can be appended to it. None blocks are skipped. Returns the block itself. """
if self.closed_by is None: self.expects_body_or_pass = True for block in indented_blocks: if block is not None: self._blocks.append((1, block)) # Finalise it so that we cannot add more sub-blocks to this block. self.finalise() 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 add(self, *blocks, indentation=0) -> "CodeBlock": """ Adds sub-blocks at the specified indentation level, which defaults to 0. Nones are skipped. Returns the parent block itself, useful for chaining. """
for block in blocks: if block is not None: self._blocks.append((indentation, block)) 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 to_code(self, context: Context =None): """ Generate the code and return it as a string. """
# Do not override this method! context = context or Context() for imp in self.imports: if imp not in context.imports: context.imports.append(imp) counter = Counter() lines = list(self.to_lines(context=context, counter=counter)) if counter.num_indented_non_doc_blocks == 0: if self.expects_body_or_pass: lines.append(" pass") elif self.closed_by: lines[-1] += self.closed_by else: if self.closed_by: lines.append(self.closed_by) return join_lines(*lines) + self._suffix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exec(self, globals=None, locals=None): """ Execute simple code blocks. Do not attempt this on modules or other blocks where you have imports as they won't work. Instead write the code to a file and use runpy.run_path() """
if locals is None: locals = {} builtins.exec(self.to_code(), globals, locals) return locals
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block(self, *blocks, **kwargs) -> "CodeBlock": """ Build a basic code block. Positional arguments should be instances of CodeBlock or strings. All code blocks passed as positional arguments are added at indentation level 0. None blocks are skipped. """
assert "name" not in kwargs kwargs.setdefault("code", self) code = CodeBlock(**kwargs) for block in blocks: if block is not None: code._blocks.append((0, block)) return 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 dict_from_locals(self, name, params: List[Parameter], not_specified_literal=Constants.VALUE_NOT_SET): """ Generate code for a dictionary of locals whose value is not the specified literal. """
code = self.block(f"{name} = {{}}") for p in params: code.add( self.block(f"if {p.name} is not {not_specified_literal}:").of( f"{name}[{p.name!r}] = {p.name}" ), ) return 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 search(self, project, text=''): """ Search in your Taiga.io instance :param project: the project id :param text: the query of your search """
result = self.raw_request.get( 'search', query={'project': project, 'text': text} ) result = result.json() search_result = SearchResult() search_result.tasks = self.tasks.parse_list(result['tasks']) search_result.issues = self.issues.parse_list(result['issues']) search_result.user_stories = self.user_stories.parse_list( result['userstories'] ) search_result.wikipages = self.wikipages.parse_list( result['wikipages'] ) return search_result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_app(self, app_id, app_secret, auth_code, state=''): """ Authenticate an app :param app_id: the app id :param app_secret: the app secret :param auth_code: the app auth code """
headers = { 'Content-type': 'application/json' } payload = { 'application': app_id, 'auth_code': auth_code, 'state': state } try: full_url = utils.urljoin( self.host, '/api/v1/application-tokens/validate' ) response = requests.post( full_url, data=json.dumps(payload), headers=headers, verify=self.tls_verify ) except RequestException: raise exceptions.TaigaRestException( full_url, 400, 'NETWORK ERROR', 'POST' ) if response.status_code != 200: raise exceptions.TaigaRestException( full_url, response.status_code, response.text, 'POST' ) cyphered_token = response.json().get('cyphered_token', '') if cyphered_token: from jwkest.jwk import SYMKey from jwkest.jwe import JWE sym_key = SYMKey(key=app_secret, alg='A128KW') data, success = JWE().decrypt(cyphered_token, keys=[sym_key]), True if isinstance(data, tuple): data, success = data try: self.token = json.loads(data.decode('utf-8')).get('token', None) except ValueError: # pragma: no cover self.token = None if not success: self.token = None else: self.token = None if self.token is None: raise exceptions.TaigaRestException( full_url, 400, 'INVALID TOKEN', 'POST' ) self.raw_request = RequestMaker('/api/v1', self.host, self.token, 'Application', self.tls_verify) self._init_resources()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sorted_members(self): """ Iterate over sorted members of shape in the same order in which the members are declared except yielding the required members before any optional members. """
members = collections.OrderedDict() required_names = self.metadata.get("required", ()) for name, shape in self.members.items(): members[name] = AbShapeMember(name=name, shape=shape, is_required=name in required_names) if self.is_output_shape: # ResponseMetadata is the first member for all output shapes. yield AbShapeMember( name="ResponseMetadata", shape=self._shape_resolver.get_shape_by_name("ResponseMetadata"), is_required=True, ) yield from sorted(members.values(), key=lambda m: not m.is_required)
<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): """ Fetch and parse stats """
self.frontends = [] self.backends = [] self.listeners = [] csv = [ l for l in self._fetch().strip(' #').split('\n') if l ] if self.failed: return #read fields header to create keys self.fields = [ f for f in csv.pop(0).split(',') if f ] #add frontends and backends first for line in csv: service = HAProxyService(self.fields, line.split(','), self.name) if service.svname == 'FRONTEND': self.frontends.append(service) elif service.svname == 'BACKEND': service.listeners = [] self.backends.append(service) else: self.listeners.append(service) #now add listener names to corresponding backends for listener in self.listeners: for backend in self.backends: if backend.iid == listener.iid: backend.listeners.append(listener) self.last_update = datetime.utcnow()
<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(value): """ decode byte strings and convert to int where needed """
if value.isdigit(): return int(value) if isinstance(value, bytes): return value.decode('utf-8') else: 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 caseinsensitive(cls): """Annotation function to set an Enum to be case insensitive on parsing"""
if not issubclass(cls, Enum): raise TypeError('caseinsensitive decorator can only be applied to subclasses of enum.Enum') enum_options = getattr(cls, PYCKSON_ENUM_OPTIONS, {}) enum_options[ENUM_CASE_INSENSITIVE] = True setattr(cls, PYCKSON_ENUM_OPTIONS, enum_options) return cls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def win32_utf8_argv(): """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of UTF-8 strings. Versions 2.5 and older of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. Returns None on failure. Example usage: """
try: from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) if argc.value > 0: # Remove Python executable if present if argc.value - len(sys.argv) == 1: start = 1 else: start = 0 return [argv[i].encode('utf-8') for i in range(start, argc.value)] except Exception: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encrypt_ascii(self, data, key=None, v=None, extra_bytes=0, digest="hex"): """ Encrypt data and return as ascii string. Hexadecimal digest as default. Avaiable digests: hex: Hexadecimal base64: Base 64 hqx: hexbin4 """
digests = {"hex": binascii.b2a_hex, "base64": binascii.b2a_base64, "hqx": binascii.b2a_hqx} digestor = digests.get(digest) if not digestor: TripleSecError(u"Digestor not supported.") binary_result = self.encrypt(data, key, v, extra_bytes) result = digestor(binary_result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrypt_ascii(self, ascii_string, key=None, digest="hex"): """ Receive ascii string and return decrypted data. Avaiable digests: hex: Hexadecimal base64: Base 64 hqx: hexbin4 """
digests = {"hex": binascii.a2b_hex, "base64": binascii.a2b_base64, "hqx": binascii.a2b_hqx} digestor = digests.get(digest) if not digestor: TripleSecError(u"Digestor not supported.") binary_string = digestor(ascii_string) result = self.decrypt(binary_string, key) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_heroes(): """ Load hero details from JSON file into memoy """
filename = os.path.join(os.path.dirname(__file__), "data", "heroes.json") with open(filename) as f: heroes = json.loads(f.read())["result"]["heroes"] for hero in heroes: HEROES_CACHE[hero["id"]] = hero
<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_items(): """ Load item details fom JSON file into memory """
filename = os.path.join(os.path.dirname(__file__), "data", "items.json") with open(filename) as f: items = json.loads(f.read())["result"]["items"] for item in items: ITEMS_CACHE[item["id"]] = item
<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_cmd_tree(self, cmd_cls, cmd_name=None): """ Build a tree of commands. :param cmd_cls: The Command class or object to start with. :param cmd_name: Hard-coded name of the command (can be None for auto-detection) :returns: A tree structure represented as tuple ``(cmd_obj, cmd_name, children)`` Where ``cmd_obj`` is a Command instance, cmd_name is its name, if any (it might be None) and ``children`` is a tuple of identical tuples. Note that command name auto-detection relies on :meth:`guacamole.recipes.cmd.Command.get_cmd_name()`. Let's look at a simple git-like example:: (None, '<git>', ( ('log', <git_log>, ()), ('stash', <git_stash>, ( ('list', <git_stash_list>, ()),),),),) """
if isinstance(cmd_cls, type): cmd_obj = cmd_cls() else: cmd_obj = cmd_cls if cmd_name is None: cmd_name = cmd_obj.get_cmd_name() return cmd_tree_node(cmd_name, cmd_obj, tuple([ self._build_cmd_tree(subcmd_cls, subcmd_name) for subcmd_name, subcmd_cls in cmd_obj.get_sub_commands()]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug_dump(message, file_prefix="dump"): """ Utility while developing to dump message data to play with in the interpreter """
global index index += 1 with open("%s_%s.dump" % (file_prefix, index), 'w') as f: f.write(message.SerializeToString()) f.close()
<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_side_attr(attr, invert, player): """ Get a player attribute that depends on which side the player is on. A creep kill for a radiant hero is a badguy_kill, while a creep kill for a dire hero is a goodguy_kill. """
t = player.team if invert: t = not player.team return getattr(player, "%s_%s" % ("goodguy" if t else "badguy", attr))
<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_dota_um(self, event): """ The chat messages that arrive when certain events occur. The most useful ones are CHAT_MESSAGE_RUNE_PICKUP, CHAT_MESSAGE_RUNE_BOTTLE, CHAT_MESSAGE_GLYPH_USED, CHAT_MESSAGE_TOWER_KILL """
if event.type == dota_usermessages_pb2.CHAT_MESSAGE_AEGIS: self.aegis.append((self.tick, event.playerid_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 parse_player_info(self, player): """ Parse a PlayerInfo struct. This arrives before a FileInfo message """
if not player.ishltv: self.player_info[player.name] = { "user_id": player.userID, "guid": player.guid, "bot": player.fakeplayer, }
<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_file_info(self, file_info): """ The CDemoFileInfo contains our winners as well as the length of the demo """
self.info["playback_time"] = file_info.playback_time self.info["match_id"] = file_info.game_info.dota.match_id self.info["game_mode"] = file_info.game_info.dota.game_mode self.info["game_winner"] = file_info.game_info.dota.game_winner for index, player in enumerate(file_info.game_info.dota.player_info): p = self.heroes[player.hero_name] p.name = player.player_name p.index = index p.team = 0 if index < 5 else 1 self.indexed_players[index] = p self.info["players"][player.player_name] = p
<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_game_event(self, ge): """ Game events contain the combat log as well as 'chase_hero' events which could be interesting """
if ge.name == "dota_combatlog": if ge.keys["type"] == 4: #Something died try: source = self.dp.combat_log_names.get(ge.keys["sourcename"], "unknown") target = self.dp.combat_log_names.get(ge.keys["targetname"], "unknown") target_illusion = ge.keys["targetillusion"] timestamp = ge.keys["timestamp"] if (target.startswith("npc_dota_hero") and not target_illusion): self.kills.append({ "target": target, "source": source, "timestamp": timestamp, "tick": self.tick, }) elif source.startswith("npc_dota_hero"): self.heroes[source].creep_kill(target, timestamp) except KeyError: """ Sometimes we get combat logs for things we dont have in combat_log_names. My theory is that the server sends us incremental updates to the string table using CSVCMsg_UpdateStringTable but I'm not sure how to parse that """ pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_file(file_name, line_ranges, options=None, in_place=False, diff=False, verbose=0, cwd=None): """Calls fix_code on the source code from the passed in file over the given line_ranges. - If diff then this returns the udiff for the changes, otherwise returns the fixed code. - If in_place the changes are written to the file. """
import codecs from os import getcwd from pep8radius.diff import get_diff from pep8radius.shell import from_dir if cwd is None: cwd = getcwd() with from_dir(cwd): try: with codecs.open(file_name, 'r', encoding='utf-8') as f: original = f.read() except IOError: # Most likely the file has been removed. # Note: it would be nice if we could raise here, specifically # for the case of passing in a diff when in the wrong directory. return '' fixed = fix_code(original, line_ranges, options, verbose=verbose) if in_place: with from_dir(cwd): with codecs.open(file_name, 'w', encoding='utf-8') as f: f.write(fixed) return get_diff(original, fixed, file_name) if diff else fixed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fix_code(source_code, line_ranges, options=None, verbose=0): '''Apply autopep8 over the line_ranges, returns the corrected code. Note: though this is not checked for line_ranges should not overlap. Example ------- >>> code = "def f( x ):\\n if True:\\n return 2*x" >>> print(fix_code(code, [(1, 1), (3, 3)])) def f(x): if True: return 2 * x ''' if options is None: from pep8radius.main import parse_args options = parse_args() if getattr(options, "yapf", False): from yapf.yapflib.yapf_api import FormatCode result = FormatCode(source_code, style_config=options.style, lines=line_ranges) # yapf<0.3 returns diff as str, >=0.3 returns a tuple of (diff, changed) return result[0] if isinstance(result, tuple) else result line_ranges = reversed(line_ranges) # Apply line fixes "up" the file (i.e. in reverse) so that # fixes do not affect changes we're yet to make. partial = source_code for start, end in line_ranges: partial = fix_line_range(partial, start, end, options) _maybe_print('.', end='', max_=1, verbose=verbose) _maybe_print('', max_=1, verbose=verbose) fixed = partial return fixed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0): """Print if verbose is within min_ and max_."""
if min_ <= verbose <= max_: import sys print(something_to_print, end=end) sys.stdout.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_diff(diff, options=None, cwd=None): """Create a Radius object from a diff rather than a reposistory. """
return RadiusFromDiff(diff=diff, options=options, cwd=cwd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix(self): """Runs fix_file on each modified file. - Prints progress and diff depending on options. - Returns True if there were any changes """
from pep8radius.diff import print_diff, udiff_lines_fixed n = len(self.filenames_diff) _maybe_print('Applying autopep8 to touched lines in %s file(s).' % n) any_changes = False total_lines_changed = 0 pep8_diffs = [] for i, file_name in enumerate(self.filenames_diff, start=1): _maybe_print('%s/%s: %s: ' % (i, n, file_name), end='') _maybe_print('', min_=2) p_diff = self.fix_file(file_name) lines_changed = udiff_lines_fixed(p_diff) if p_diff else 0 total_lines_changed += lines_changed if p_diff: any_changes = True if self.diff: pep8_diffs.append(p_diff) if self.in_place: _maybe_print('pep8radius fixed %s lines in %s files.' % (total_lines_changed, n), verbose=self.verbose) else: _maybe_print('pep8radius would fix %s lines in %s files.' % (total_lines_changed, n), verbose=self.verbose) if self.diff: for diff in pep8_diffs: print_diff(diff, color=self.color) return any_changes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_file(self, file_name): """Apply autopep8 to the diff lines of a file. - Returns the diff between original and fixed file. - If self.in_place then this writes the the fixed code the file_name. - Prints dots to show progress depending on options. """
# We hope that a CalledProcessError would have already raised # during the init if it were going to raise here. modified_lines = self.modified_lines(file_name) return fix_file(file_name, modified_lines, self.options, in_place=self.in_place, diff=True, verbose=self.verbose, cwd=self.cwd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_map(base, params): """ Return a URL with get parameters based on the params passed in This is more forgiving than urllib.urlencode and will attempt to coerce non-string objects into strings and automatically UTF-8 encode strings. @param params: HTTP GET parameters """
url = base if not params: url.rstrip("?&") elif '?' not in url: url += "?" entries = [] for key, value in params.items(): if value is not None: value = str(value) entries.append("%s=%s" % (quote_plus(key.encode("utf-8")), quote_plus(value.encode("utf-8")))) url += "&".join(entries) return str(url)
<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(name, params=None, version="V001", key=None, api_type="web", fetcher=get_page, base=None, language="en_us"): """ Make an API request """
params = params or {} params["key"] = key or API_KEY params["language"] = language if not params["key"]: raise ValueError("API key not set, please set DOTA2_API_KEY") url = url_map("%s%s/%s/" % (base or BASE_URL, name, version), params) return fetcher(url)
<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_match_history(start_at_match_id=None, player_name=None, hero_id=None, skill=0, date_min=None, date_max=None, account_id=None, league_id=None, matches_requested=None, game_mode=None, min_players=None, tournament_games_only=None, **kwargs): """ List of most recent 25 matches before start_at_match_id """
params = { "start_at_match_id": start_at_match_id, "player_name": player_name, "hero_id": hero_id, "skill": skill, "date_min": date_min, "date_max": date_max, "account_id": account_id, "league_id": league_id, "matches_requested": matches_requested, "game_mode": game_mode, "min_players": min_players, "tournament_games_only": tournament_games_only } return make_request("GetMatchHistory", params, **kwargs)
<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_match_history_by_sequence_num(start_at_match_seq_num, matches_requested=None, **kwargs): """ Most recent matches ordered by sequence number """
params = { "start_at_match_seq_num": start_at_match_seq_num, "matches_requested": matches_requested } return make_request("GetMatchHistoryBySequenceNum", params, **kwargs)
<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_player_summaries(players, **kwargs): """ Get players steam profile from their steam ids """
if (isinstance(players, list)): params = {'steamids': ','.join(str(p) for p in players)} elif (isinstance(players, int)): params = {'steamids': players} else: raise ValueError("The players input needs to be a list or int") return make_request("GetPlayerSummaries", params, version="v0002", base="http://api.steampowered.com/ISteamUser/", **kwargs)
<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_hero_image_url(hero_name, image_size="lg"): """ Get a hero image based on name and image size """
if hero_name.startswith("npc_dota_hero_"): hero_name = hero_name[len("npc_dota_hero_"):] valid_sizes = ['eg', 'sb', 'lg', 'full', 'vert'] if image_size not in valid_sizes: raise ValueError("Not a valid hero image size") return "http://media.steampowered.com/apps/dota2/images/heroes/{}_{}.png".format( hero_name, image_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 generate_proxy( prefix, base_url='', verify_ssl=True, middleware=None, append_middleware=None, cert=None, timeout=None): """Generate a ProxyClass based view that uses the passed base_url."""
middleware = list(middleware or HttpProxy.proxy_middleware) middleware += list(append_middleware or []) return type('ProxyClass', (HttpProxy,), { 'base_url': base_url, 'reverse_urls': [(prefix, base_url)], 'verify_ssl': verify_ssl, 'proxy_middleware': middleware, 'cert': cert, 'timeout': 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 generate_routes(config): """Generate a list of urls that map to generated proxy views. generate_routes({ 'test_proxy': { 'base_url': 'https://google.com/', 'prefix': '/test_prefix/', 'verify_ssl': False, 'csrf_exempt: False', 'middleware': ['djproxy.proxy_middleware.AddXFF'], 'append_middleware': ['djproxy.proxy_middleware.AddXFF'], 'timeout': 3.0, 'cert': None } }) Required configuration keys: * `base_url` * `prefix` Optional configuration keys: * `verify_ssl`: defaults to `True`. * `csrf_exempt`: defaults to `True`. * `cert`: defaults to `None`. * `timeout`: defaults to `None`. * `middleware`: Defaults to `None`. Specifying `None` causes djproxy to use the default middleware set. If a list is passed, the default middleware list specified by the HttpProxy definition will be replaced with the provided list. * `append_middleware`: Defaults to `None`. `None` results in no changes to the default middleware set. If a list is specified, the list will be appended to the default middleware list specified in the HttpProxy definition or, if provided, the middleware key specificed in the config dict. Returns: [ url(r'^test_prefix/', GeneratedProxy.as_view(), name='test_proxy')), ] """
routes = [] for name, config in iteritems(config): pattern = r'^%s(?P<url>.*)$' % re.escape(config['prefix'].lstrip('/')) proxy = generate_proxy( prefix=config['prefix'], base_url=config['base_url'], verify_ssl=config.get('verify_ssl', True), middleware=config.get('middleware'), append_middleware=config.get('append_middleware'), cert=config.get('cert'), timeout=config.get('timeout')) proxy_view_function = proxy.as_view() proxy_view_function.csrf_exempt = config.get('csrf_exempt', True) routes.append(url(pattern, proxy_view_function, name=name)) return routes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def threshold_brier_score(observations, forecasts, threshold, issorted=False, axis=-1): """ Calculate the Brier scores of an ensemble for exceeding given thresholds. According to the threshold decomposition of CRPS, the resulting Brier scores can thus be summed along the last axis to calculate CRPS, as .. math:: CRPS(F, x) = \int_z BS(F(z), H(z - x)) dz where $F(x) = \int_{z \leq x} p(z) dz$ is the cumulative distribution function (CDF) of the forecast distribution $F$, $x$ is a point estimate of the true observation (observational error is neglected), $BS$ denotes the Brier score and $H(x)$ denotes the Heaviside step function, which we define here as equal to 1 for x >= 0 and 0 otherwise. It is more efficient to calculate CRPS directly, but this threshold decomposition itself provides a useful summary of model quality as a function of measurement values. The Numba accelerated version of this function is much faster for calculating many thresholds simultaneously: it runs in time O(N * (E * log(E) + T)), where N is the number of observations, E is the ensemble size and T is the number of thresholds. The non-Numba accelerated version requires time and space O(N * E * T). Parameters observations : float or array_like Observations float or array. Missing values (NaN) are given scores of NaN. forecasts : float or array_like Array of forecasts ensemble members, of the same shape as observations except for the extra axis corresponding to the ensemble. If forecasts has the same shape as observations, the forecasts are treated as deterministic. Missing values (NaN) are ignored. threshold : scalar or 1d array_like Threshold value(s) at which to calculate exceedence Brier scores. issorted : bool, optional Optimization flag to indicate that the elements of `ensemble` are already sorted along `axis`. axis : int, optional Axis in forecasts which corresponds to different ensemble members, along which to calculate the threshold decomposition. Returns ------- out : np.ndarray Brier scores at each thresold for each ensemble forecast against the observations. If ``threshold`` is a scalar, the result will have the same shape as observations. Otherwise, it will have an additional final dimension corresponding to the threshold levels. References Gneiting, T. and Ranjan, R. Comparing density forecasts using threshold- and quantile-weighted scoring rules. J. Bus. Econ. Stat. 29, 411-422 (2011). http://www.stat.washington.edu/research/reports/2008/tr533.pdf See also -------- crps_ensemble, brier_score """
observations = np.asarray(observations) threshold = np.asarray(threshold) forecasts = np.asarray(forecasts) if axis != -1: forecasts = move_axis_to_end(forecasts, axis) if forecasts.shape == observations.shape: forecasts = forecasts[..., np.newaxis] if observations.shape != forecasts.shape[:-1]: raise ValueError('observations and forecasts must have matching ' 'shapes or matching shapes except along `axis=%s`' % axis) scalar_threshold = threshold.ndim == 0 if threshold.ndim > 1: raise ValueError('threshold must be scalar or 1-dimensional') if threshold.ndim == 1 and not (np.sort(threshold) == threshold).all(): raise ValueError('1D thresholds must be sorted') threshold = threshold.reshape((1,) * observations.ndim + (-1,)) if not issorted: forecasts = np.sort(forecasts, axis=-1) result = _threshold_brier_score_core(observations, forecasts, threshold) if scalar_threshold: result = result.squeeze(axis=-1) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dumps(*args, **kwargs): """ Wrapper for json.dumps that uses the JSONArgonautsEncoder. """
import json from django.conf import settings from argonauts.serializers import JSONArgonautsEncoder kwargs.setdefault('cls', JSONArgonautsEncoder) # pretty print in DEBUG mode. if settings.DEBUG: kwargs.setdefault('indent', 4) kwargs.setdefault('separators', (',', ': ')) else: kwargs.setdefault('separators', (',', ':')) return json.dumps(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, record): """Overridden method that applies SGR codes to log messages."""
# XXX: idea, colorize message arguments s = super(ANSIFormatter, self).format(record) if hasattr(self.context, 'ansi'): s = self.context.ansi(s, **self.get_sgr(record)) return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def added(self, context): """ Configure generic application logging. This method just calls ``:meth:`configure_logging()`` which sets up everything else. This allows other components to use logging without triggering implicit configuration. """
self._expose_argparse = context.bowl.has_spice("log:arguments") self.configure_logging(context)
<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_logging(self, context): """ Configure logging for the application. :param context: The guacamole context object. This method attaches a :py:class:logging.StreamHandler` with a subclass of :py:class:`logging.Formatter` to the root logger. The specific subclass is :class:`ANSIFormatter` and it adds basic ANSI formatting (colors and some styles) to logging messages so that they stand out from normal output. """
fmt = "%(name)-12s: %(levelname)-8s %(message)s" formatter = ANSIFormatter(context, fmt) handler = logging.StreamHandler() handler.setFormatter(formatter) logging.root.addHandler(handler)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_logging(self, context): """ Adjust logging configuration. :param context: The guacamole context object. This method uses the context and the results of early argument parsing to adjust the configuration of the logging subsystem. In practice the values passed to ``--log-level`` and ``--trace`` are applied. """
if context.early_args.log_level: log_level = context.early_args.log_level logging.getLogger("").setLevel(log_level) for name in context.early_args.trace: logging.getLogger(name).setLevel(logging.DEBUG) _logger.info("Enabled tracing on logger %r", name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json(a): """ Output the json encoding of its argument. This will escape all the HTML/XML special characters with their unicode escapes, so it is safe to be output anywhere except for inside a tag attribute. If the output needs to be put in an attribute, entitize the output of this filter. """
json_str = json_dumps(a) # Escape all the XML/HTML special characters. escapes = ['<', '>', '&'] for c in escapes: json_str = json_str.replace(c, r'\u%04x' % ord(c)) # now it's safe to use mark_safe return mark_safe(json_str)
<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(self, argv=None, exit=True): """ Shortcut to prepare a bowl of guacamole and eat it. :param argv: Command line arguments or None. None means that sys.argv is used :param exit: Raise SystemExit after finishing execution :returns: Whatever is returned by the eating the guacamole. :raises: Whatever is raised by eating the guacamole. .. note:: This method always either raises and exception or returns an object. The way it behaves depends on the value of the `exit` argument. This method can be used to quickly take a recipe, prepare the guacamole and eat it. It is named main as it is applicable as the main method of an application. The `exit` argument controls if main returns normally or raises SystemExit. By default it will raise SystemExit (it will either wrap the return value with SystemExit or re-raise the SystemExit exception again). If SystemExit is raised but `exit` is False the argument to SystemExit is unwrapped and returned instead. """
bowl = self.prepare() try: retval = bowl.eat(argv) except SystemExit as exc: if exit: raise else: return exc.args[0] else: if retval is None: retval = 0 if exit: raise SystemExit(retval) else: return retval
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch_failed(self, context): """Print the unhandled exception and exit the application."""
traceback.print_exception( context.exc_type, context.exc_value, context.traceback) raise SystemExit(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 variables(template): '''Returns the set of keywords in a uri template''' vars = set() for varlist in TEMPLATE.findall(template): if varlist[0] in OPERATOR: varlist = varlist[1:] varspecs = varlist.split(',') for var in varspecs: # handle prefix values var = var.split(':')[0] # handle composite values if var.endswith('*'): var = var[:-1] vars.add(var) return vars
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(template, variables): """ Expand template as a URI Template using variables. """
def _sub(match): expression = match.group(1) operator = "" if expression[0] in OPERATOR: operator = expression[0] varlist = expression[1:] else: varlist = expression safe = "" if operator in ["+", "#"]: safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: default = None explode = False prefix = None if "=" in varspec: varname, default = tuple(varspec.split("=", 1)) else: varname = varspec if varname[-1] == "*": explode = True varname = varname[:-1] elif ":" in varname: try: prefix = int(varname[varname.index(":")+1:]) except ValueError: raise ValueError("non-integer prefix '{0}'".format( varname[varname.index(":")+1:])) varname = varname[:varname.index(":")] if default: defaults[varname] = default varnames.append((varname, explode, prefix)) retval = [] joiner = operator start = operator if operator == "+": start = "" joiner = "," if operator == "#": joiner = "," if operator == "?": joiner = "&" if operator == "&": start = "&" if operator == "": joiner = "," for varname, explode, prefix in varnames: if varname in variables: value = variables[varname] if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue expanded = TOSTRING[operator]( varname, value, explode, prefix, operator, safe=safe) if expanded is not None: retval.append(expanded) if len(retval) > 0: return start + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template)
<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): '''Clear history of samples and other internal variables to free memory. .. note:: The proposal is untouched. ''' self.samples.clear() self.weights.clear() if self.target_values is not None: self.target_values.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, N=1, trace_sort=False): '''Run the sampler, store the history of visited points into the member variable ``self.samples`` and the importance weights into ``self.weights``. .. seealso:: :py:class:`pypmc.tools.History` :param N: Integer; the number of samples to be drawn. :param trace_sort: Bool; if True, return an array containing the responsible component of ``self.proposal`` for each sample generated during this run. .. note:: This option only works for proposals of type :py:class:`pypmc.density.mixture.MixtureDensity` .. note:: If True, the samples will be ordered by the components. ''' if N == 0: return 0 if trace_sort: this_samples, origin = self._get_samples(N, trace_sort=True) self._calculate_weights(this_samples, N) return origin else: this_samples = self._get_samples(N, trace_sort=False) self._calculate_weights(this_samples, 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 _calculate_weights(self, this_samples, N): """Calculate and save the weights of a run."""
this_weights = self.weights.append(N)[:,0] if self.target_values is None: for i in range(N): tmp = self.target(this_samples[i]) - self.proposal.evaluate(this_samples[i]) this_weights[i] = _exp(tmp) else: this_target_values = self.target_values.append(N) for i in range(N): this_target_values[i] = self.target(this_samples[i]) tmp = this_target_values[i] - self.proposal.evaluate(this_samples[i]) this_weights[i] = _exp(tmp)
<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_samples(self, N, trace_sort): """Save N samples from ``self.proposal`` to ``self.samples`` This function does NOT calculate the weights. Return a reference to this run's samples in ``self.samples``. If ``trace_sort`` is True, additionally return an array indicating the responsible component. (MixtureDensity only) """
# allocate an empty numpy array to store the run and append accept count # (importance sampling accepts all points) this_run = self.samples.append(N) # store the proposed points (weights are still to be calculated) if trace_sort: this_run[:], origin = self.proposal.propose(N, self.rng, trace=True, shuffle=False) return this_run, origin else: this_run[:] = self.proposal.propose(N, self.rng) return this_run
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def x_forwarded_for(self): """X-Forwarded-For header value. This is the amended header so that it contains the previous IP address in the forwarding change. """
ip = self._request.META.get('REMOTE_ADDR') current_xff = self.headers.get('X-Forwarded-For') return '%s, %s' % (current_xff, ip) if current_xff else ip
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _add_to_docstring(string): '''Private wrapper function. Appends ``string`` to the docstring of the wrapped function. ''' def wrapper(method): if method.__doc__ is not None: method.__doc__ += string else: method.__doc__ = string return method return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_django_header_name(header): """Unmunge header names modified by Django."""
# Remove HTTP_ prefix. new_header = header.rpartition('HTTP_')[2] # Camel case and replace _ with - new_header = '-'.join( x.capitalize() for x in new_header.split('_')) return new_header
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_request(cls, request): """Generate a HeaderDict based on django request object meta data."""
request_headers = HeaderDict() other_headers = ['CONTENT_TYPE', 'CONTENT_LENGTH'] for header, value in iteritems(request.META): is_header = header.startswith('HTTP_') or header in other_headers normalized_header = cls._normalize_django_header_name(header) if is_header and value: request_headers[normalized_header] = value return request_headers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, exclude): """Return a HeaderSet excluding the headers in the exclude list."""
filtered_headers = HeaderDict() lowercased_ignore_list = [x.lower() for x in exclude] for header, value in iteritems(self): if header.lower() not in lowercased_ignore_list: filtered_headers[header] = value return filtered_headers