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/messagin...
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...
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 bes...
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 =...
<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-ap...
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 ...
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...
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 prefi...
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('s...
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_e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 el...
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_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 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: ...
<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', 'h...
<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): ...
<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 ".ti...
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 v...
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)...
<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/...
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-...
<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 ke...
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": c...
<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: ei...
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 = 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 _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...
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...
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 delet...
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 ...
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, pagin...
<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(reque...
<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 v...
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, paylo...
<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 o...
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(ser...
<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) ...
<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_statu...
<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: ...
<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(respo...
<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 t...
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 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 add(self, *blocks, indentation=0) -> "CodeBlock": """ Adds sub-blocks at the specified indentation level, which defaults to 0. Nones are skipped. Returns the ...
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.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 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 wo...
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...
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 valu...
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...
<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...
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...
<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 befor...
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 ...
<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 ] ...
<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 ...
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.CommandLineT...
<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. Avaiabl...
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_byte...
<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: Bas...
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...
<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...
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 ...
<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...
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...
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.g...
<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.c...
<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...
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() ...
<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(c...
<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...
<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 wr...
# 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, ...
<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 co...
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")), ...
<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_requ...
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_requ...
<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, versio...
<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/{...
<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 ...
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, 'c...
<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/', '...
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=conf...
<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 thresho...
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 != 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 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', (',', ': ')) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 al...
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:l...
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 o...
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 o...
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.ar...
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: 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 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 ...
<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...
<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...
<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_...
<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 refere...
# 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....
<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...
<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) i...
<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