output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def lowstrip(term): """Convert to lowercase and strip spaces""" term = re.sub('\s+', ' ', term) term = term.lower() return term
Write a Python 3 script for converting to lowercase and strip spaces
You are a Python code generator, capable of creating scripts from specifications.
Perform the similarity join
Can you tell what is the following Python 3 function doing def main(left_path, left_column, right_path, right_column, outfile, titles, join, minscore, count, warp): """Perform the similarity join""" right_file = csv.reader(open(right_path, 'r')) if titles: right_header = next(right_file) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def console_main(): """Process command-line arguments.""" from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument('-t', '--titles', action='store_true', help='input files have column titles') parser.add_argument( '-j', '--j...
Can you write a function in Python 3 where it commands - line arguments.
As a python code expert, you are capable of creating scripts from specifications.
def copy(self, items=None): """Return a new NGram object with the same settings, and referencing the same items. Copy is shallow in that each item is not recursively copied. Optionally specify alternate items to populate the copy. >>> from ngram import NGram >>> from ...
Can you write a function in Python 3 where it returns a shallow copy of this NGram object with the same settings and and referencing the same items.
You are a Python code architect, reviewing and designing scalable and efficient code
def _split(self, string): """Iterates over the ngrams of a string (no padding). >>> from ngram import NGram >>> n = NGram() >>> list(n._split("hamegg")) ['ham', 'ame', 'meg', 'egg'] """ for i in range(len(string) - self.N + 1): yield string[i:i + self...
Can you implement a function in Python 3 that splits a string into ngrams.
You are a Python code analyst, evaluating scripts for potential improvements.
def add(self, item): """Add an item to the N-gram index (if it has not already been added). >>> from ngram import NGram >>> n = NGram() >>> n.add("ham") >>> list(n) ['ham'] >>> n.add("spam") >>> sorted(list(n)) ['ham', 'spam'] """ ...
Implement a function in Python 3 to add an item to the N - gram index.
As a Python code translator, you convert algorithms and pseudocode into Python.
Retrieve the subset of items that share n - grams with this string.
Can you generate the documentation for the following Python 3 function def items_sharing_ngrams(self, query): # From matched string to number of N-grams shared with query string shared = {} # Dictionary mapping n-gram to string to number of occurrences of that # ngram in the string that ...
You are a Python code analyst, evaluating scripts for potential improvements.
def searchitem(self, item, threshold=None): """Search the index for items whose key exceeds the threshold similarity to the key of the given item. :return: list of pairs of (item, similarity) by decreasing similarity. >>> from ngram import NGram >>> n = NGram([(0, "SPAM"), (1, ...
Create a Python 3 function to search the index for items whose key exceeds the threshold similarity to the key of the given item.
You are a Python code architect, reviewing and designing scalable and efficient code
Search the index for items whose key exceeds threshold \ similarity to the query string.
Make a summary of the following Python 3 code def search(self, query, threshold=None): threshold = threshold if threshold is not None else self.threshold results = [] # Identify possible results for match, samegrams in self.items_sharing_ngrams(query).items(): allgrams = (len...
You are a Python code generator, capable of creating scripts from specifications.
Return the most similar item to the provided one or None if nothing exceeds the threshold.
Given the following Python 3 function, write the documentation def finditem(self, item, threshold=None): results = self.searchitem(item, threshold) if results: return results[0][0] else: return None
As a Python code composer, you craft elegant and concise scripts.
Simply return the best match to the query None on no match.
Can you generate a brief explanation for the following Python 3 code def find(self, query, threshold=None): results = self.search(query, threshold) if results: return results[0][0] else: return None
As a Python code composer, you craft elegant and concise scripts.
Compares two strings and returns their similarity between 0. 0 and 1. 0.
Explain what the following Python 3 code does def compare(s1, s2, **kwargs): if s1 is None or s2 is None: if s1 == s2: return 1.0 return 0.0 try: return NGram([s1], **kwargs).search(s2)[0][1] except IndexError: return 0.0
You are a Python code architect, reviewing and designing scalable and efficient code
def clear(self): """Remove all elements from this set. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> sorted(list(n)) ['eggs', 'spam'] >>> n.clear() >>> list(n) [] """ super(NGram, self).clear() self._grams = {} ...
Write a Python 3 function that can remove all elements from this set.
You are a Python code generator, capable of creating scripts from specifications.
def union(self, *others): """Return the union of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.union(b))) ['eggs', 'ham', 'spam'] """ return self.copy(super(NGra...
Implement a function in Python 3 to return the union of two or more sets as a new set.
You are a Python code analyst, evaluating scripts for potential improvements.
def difference(self, *others): """Return the difference of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.difference(b)) ['eggs'] """ return self.copy(super(NGram, self)...
Can you create a Python 3 function that returns the difference of two sets as a new set.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the intersection of two sets as a new set.
Can you tell what is the following Python 3 function doing def intersection(self, *others): return self.copy(super(NGram, self).intersection(*others))
You are a Python code generator, capable of creating scripts from specifications.
Update the set with the intersection of itself and other sets.
Can you generate the documentation for the following Python 3 function def intersection_update(self, *others): self.difference_update(super(NGram, self).difference(*others))
As a Python code translator, you convert algorithms and pseudocode into Python.
def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> sorted(list(a.symmetric_difference(b))) ['eggs', 'ham'] """ ...
Implement a function in Python 3 to return the symmetric difference of two sets as a new set.
As a python code expert, you are capable of creating scripts from specifications.
def symmetric_difference_update(self, other): """Update the set with the symmetric difference of itself and `other`. >>> from ngram import NGram >>> n = NGram(['spam', 'eggs']) >>> other = set(['spam', 'ham']) >>> n.symmetric_difference_update(other) >>> sorted(list(n)) ...
Can you write a function in Python 3 where it updates the set with the symmetric difference of itself and other.
You are a Python code architect, reviewing and designing scalable and efficient code
def sub(value, arg): """Subtract the arg from the value.""" try: nvalue, narg = handle_float_decimal_combinations( valid_numeric(value), valid_numeric(arg), '-') return nvalue - narg except (ValueError, TypeError): try: return value - arg except Except...
How would you code a function in Python 3 to subtract the arg from the value.
As a Python code analyst, you investigate and solve complex coding mysteries
def absolute(value): """Return the absolute value.""" try: return abs(valid_numeric(value)) except (ValueError, TypeError): try: return abs(value) except Exception: return ''
Write a Python 3 script to return the absolute value.
As a Python code composer, you craft elegant and concise scripts.
def cli(config, server, api_key, all, credentials, project): """Create the cli command line.""" # Check first for the pybossa.rc file to configure server and api-key home = expanduser("~") if os.path.isfile(os.path.join(home, '.pybossa.cfg')): config.parser.read(os.path.join(home, '.pybossa.cfg'...
Can you write a function in Python 3 where it creates the cli command line.
You are a Python code analyst, evaluating scripts for potential improvements.
Update project templates and information.
Make a summary of the following Python 3 code def update_project(config, task_presenter, results, long_description, tutorial, watch): # pragma: no cover """Update project templates and information.""" if watch: res = _update_project_watch(config, task_presenter, results, ...
As a Python code composer, you craft elegant and concise scripts.
def add_tasks(config, tasks_file, tasks_type, priority, redundancy): """Add tasks to a project.""" res = _add_tasks(config, tasks_file, tasks_type, priority, redundancy) click.echo(res)
Write a Python 3 script for adding tasks to a project.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_helpingmaterials(config, helping_materials_file, helping_type): """Add helping materials to a project.""" res = _add_helpingmaterials(config, helping_materials_file, helping_type) click.echo(res)
Can you create a Python 3 function that adds helping materials to a project.
As a Python code analyst, you investigate and solve complex coding mysteries
Delete tasks from a project.
Explain what the following Python 3 code does def delete_tasks(config, task_id): if task_id is None: msg = ("Are you sure you want to delete all the tasks and associated task runs?") if click.confirm(msg): res = _delete_tasks(config, task_id) click.echo(res) else: ...
As a Python code composer, you craft elegant and concise scripts.
Update task redudancy for a project.
Can you generate a brief explanation for the following Python 3 code def update_task_redundancy(config, task_id, redundancy): if task_id is None: msg = ("Are you sure you want to update all the tasks redundancy?") if click.confirm(msg): res = _update_tasks_redundancy(config, task_id, red...
As a python code expert, you are capable of creating scripts from specifications.
Create a project in a PyBossa server.
Explain what the following Python 3 code does def _create_project(config): try: response = config.pbclient.create_project(config.project['name'], config.project['short_name'], config.project['description']) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Update a project in a loop.
Can you generate a brief explanation for the following Python 3 code def _update_project_watch(config, task_presenter, results, long_description, tutorial): # pragma: no cover """Update a project in a loop.""" logging.basicConfig(level=logging.INFO, format='%(a...
You are a Python code generator, capable of creating scripts from specifications.
Append to template a distribution bundle js.
Given the following Python 3 function, write the documentation def _update_task_presenter_bundle_js(project): if os.path.isfile ('bundle.min.js'): with open('bundle.min.js') as f: js = f.read() project.info['task_presenter'] += "<script>\n%s\n</script>" % js return if os.pat...
As a Python code composer, you craft elegant and concise scripts.
Load data from CSV XLSM XLTM PO or PROPERTIES type.
Given the following Python 3 function, write the documentation def _load_data(data_file, data_type): raw_data = data_file.read() if data_type is None: data_type = data_file.name.split('.')[-1] # Data list to process data = [] # JSON type if data_type == 'json': data = json.loads(...
As a Python code analyst, you investigate and solve complex coding mysteries
def _add_tasks(config, tasks_file, tasks_type, priority, redundancy): """Add tasks to a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) data ...
Create a Python 3 function for adding tasks to a project.
You are a Python code analyst, evaluating scripts for potential improvements.
def _add_helpingmaterials(config, helping_file, helping_type): """Add helping materials to a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) ...
Implement a Python 3 function for adding helping materials to a project.
As a Python code analyst, you investigate and solve complex coding mysteries
def _delete_tasks(config, task_id, limit=100, offset=0): """Delete tasks from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) if task_id: ...
Implement a Python 3 function for deleting tasks from a project.
You are a Python code architect, reviewing and designing scalable and efficient code
def _update_tasks_redundancy(config, task_id, redundancy, limit=300, offset=0): """Update tasks redundancy from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, ...
Create a Python 3 function for updating tasks redundancy from a project.
As a Python code analyst, you investigate and solve complex coding mysteries
def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name.""" try: response = pbclient.find_project(short_name=short_name, all=all) check_api_error(response) if (len(response) == 0): msg = '%s not found! You can use the all=1 argument to ...
How would you code a function in Python 3 to return project by short_name.
As a Python code analyst, you investigate and solve complex coding mysteries
Check if returned API response contains an error.
Make a summary of the following Python 3 code def check_api_error(api_response): print(api_response) """Check if returned API response contains an error.""" if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200: print("Server response code: %s" % api_response['...
You are a Python code analyst, evaluating scripts for potential improvements.
def format_error(module, error): """Format the error for the given module.""" logging.error(module) # Beautify JSON error print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': ')) exit(1)
Can you implement a function in Python 3 that formats the error for the given module.
As a python code expert, you are capable of creating scripts from specifications.
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.read(code) if code_data is None: raise AuthCodeNotFound ...
Write a Python 3 function that can fetch an authorization code from redis.
As a python code expert, you are capable of creating scripts from specifications.
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`. """ self.write(authorization_code.code, {"client_id": authorization_code.client_id, "c...
How would you implement a function in Python 3 that saves the data belonging to an authorization code token in redis.
As a Python code translator, you convert algorithms and pseudocode into Python.
def save_token(self, access_token): """ Stores the access token and additional data in redis. See :class:`oauth2.store.AccessTokenStore`. """ self.write(access_token.token, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, ...
Write a Python 3 script to save the access token in redis.
You are a Python code architect, reviewing and designing scalable and efficient code
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.delete(access_token.token)
Create a Python 3 function to delete a refresh token after use
You are a Python code architect, reviewing and designing scalable and efficient code
Add a client app to the cache.
Can you generate the documentation for the following Python 3 function def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param c...
As a python code expert, you are capable of creating scripts from specifications.
def create_access_token_data(self, grant_type): """ Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` ...
Write a Python 3 script for creating data needed by an access token.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a new token for the current locale.
Here you have a function in Python 3, explain what it does def generate(self): random_data = os.urandom(100) hash_gen = hashlib.new("sha512") hash_gen.update(random_data) return hash_gen.hexdigest()[:self.token_length]
You are a Python code analyst, evaluating scripts for potential improvements.
Display token information or redirect to login prompt if none is available.
Can you tell what is the following Python 3 function doing def _display_token(self): if self.token is None: return "301 Moved", "", {"Location": "/login"} return ("200 OK", self.TOKEN_TEMPLATE.format( access_token=self.token["access_token"]), ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _request_token(self, env): """ Retrieves a new access token from the OAuth2 server. """ params = {} content = env['wsgi.input'].read(int(env['CONTENT_LENGTH'])) post_params = parse_qs(content) # Convert to dict for easier access for param, value in po...
Implement a function in Python 3 to request an access token from the OAuth2 server.
As a Python code composer, you craft elegant and concise scripts.
Add a client app to the list of available clients.
Here you have a function in Python 3, explain what it does def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret...
As a Python code translator, you convert algorithms and pseudocode into Python.
Retrieve a client by its identifier.
Explain what the following Python 3 code does def fetch_by_client_id(self, client_id): if client_id not in self.clients: raise ClientNotFoundError return self.clients[client_id]
As a Python code translator, you convert algorithms and pseudocode into Python.
def fetch_by_code(self, code): """ Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code. ""...
How would you code a function in Python 3 to return an instance of AuthorizationCode.
You are a Python code generator, capable of creating scripts from specifications.
def save_token(self, access_token): """ Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """ self.access_tokens[access_token.token] = access_token unique_token_key = self._unique_token_key(ac...
Can you create a Python 3 function that stores an access token and additional data in memory.
As a Python code composer, you craft elegant and concise scripts.
def fetch_by_refresh_token(self, refresh_token): """ Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oaut...
Create a Python 3 function for returning an access token by its refresh token.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_grant(self, grant): """ Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandlerFactory` :type grant: oauth2.grant.GrantHandlerFactory """ if hasattr(grant, "expires_i...
Write a Python 3 function for adding a Grant that the provider should support.
You are a Python code generator, capable of creating scripts from specifications.
Checks which Grant supports the current request and dispatches to it.
Can you generate the documentation for the following Python 3 function def dispatch(self, request, environ): try: grant_type = self._determine_grant_type(request) response = self.response_class() grant_type.read_validate_params(request) return grant_type.proces...
As a Python code translator, you convert algorithms and pseudocode into Python.
Enable the use of unique access tokens on all grant types that support this option.
Can you generate a brief explanation for the following Python 3 code def enable_unique_tokens(self): for grant_type in self.grant_types: if hasattr(grant_type, "unique_token"): grant_type.unique_token = True
You are a Python code analyst, evaluating scripts for potential improvements.
def header(self, name, default=None): """ Returns the value of the HTTP header identified by `name`. """ wsgi_header = "HTTP_{0}".format(name.upper()) try: return self.env_raw[wsgi_header] except KeyError: return default
Write a Python 3 function that can return the value of the HTTP header identified by name.
As a Python code analyst, you investigate and solve complex coding mysteries
def request_body(request): """ Extracts the credentials of a client from the *application/x-www-form-urlencoded* body of a request. Expects the client_id to be the value of the ``client_id`` parameter and the client_secret to be the value of the ``client_secret`` parameter. :param request: The...
Create a Python 3 function to extract the client id and client secret from the request body.
As a python code expert, you are capable of creating scripts from specifications.
Extracts the client credentials from an HTTP Basic Auth header.
Explain what the following Python 3 code does def http_basic_auth(request): auth_header = request.header("authorization") if auth_header is None: raise OAuthInvalidError(error="invalid_request", explanation="Authorization header is missing") auth_parts = auth_header...
You are a Python code analyst, evaluating scripts for potential improvements.
Authenticates a client by its identifier.
Here you have a function in Python 3, explain what it does def by_identifier(self, request): client_id = request.get_param("client_id") if client_id is None: raise OAuthInvalidNoRedirectError(error="missing_client_id") try: client = self.client_store.fetch_by_client_id(...
As a Python code translator, you convert algorithms and pseudocode into Python.
Authenticates a client by its identifier and secret.
Given the following Python 3 function, write the documentation def by_identifier_secret(self, request): client_id, client_secret = self.source(request=request) try: client = self.client_store.fetch_by_client_id(client_id) except ClientNotFoundError: raise OAuthInvalidErr...
As a Python code composer, you craft elegant and concise scripts.
Returns the time until the token expires in seconds or 0 if the token has expired.
Can you generate the documentation for the following Python 3 function def expires_in(self): time_left = self.expires_at - int(time.time()) if time_left > 0: return time_left return 0
You are a Python code analyst, evaluating scripts for potential improvements.
Executes a query and returns the identifier of the last altered row.
Make a summary of the following Python 3 code def execute(self, query, *params): cursor = self.connection.cursor() try: cursor.execute(query, params) self.connection.commit() return cursor.lastrowid finally: cursor.close()
As a Python code analyst, you investigate and solve complex coding mysteries
def fetchone(self, query, *args): """ Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row wit...
Create a Python 3 function to execute a query and returns the first result of the given query.
You are a Python code architect, reviewing and designing scalable and efficient code
def fetchall(self, query, *args): """ Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `list` of `tuple`s with ...
How would you code a function in Python 3 to execute a query and returns all the results of the given query.
As a python code expert, you are capable of creating scripts from specifications.
def fetch_by_refresh_token(self, refresh_token): """ Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNo...
Implement a Python 3 function for retrieving an access token by its refresh token.
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieves an existing access token for a specific client and user for a specific grant.
Can you generate the documentation for the following Python 3 function def fetch_existing_token_of_user(self, client_id, grant_type, user_id): token_data = self.fetchone(self.fetch_existing_token_of_user_query, client_id, grant_type, user_id) if token_data is None: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a new entry for an access token in the database.
How would you explain what the following Python 3 function does def save_token(self, access_token): access_token_id = self.execute(self.create_access_token_query, access_token.client_id, access_token.grant_type, ...
As a python code expert, you are capable of creating scripts from specifications.
Retrieves an authorization code by its code.
How would you explain what the following Python 3 function does def fetch_by_code(self, code): auth_code_data = self.fetchone(self.fetch_code_query, code) if auth_code_data is None: raise AuthCodeNotFound data = dict() data_result = self.fetchall(self.fetch_data_query, auth...
As a python code expert, you are capable of creating scripts from specifications.
def save_code(self, authorization_code): """ Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine. """ auth_c...
Write a Python 3 script to create a new entry of an auth code in the database.
As a Python code analyst, you investigate and solve complex coding mysteries
Retrieves a client by its identifier.
Here you have a function in Python 3, explain what it does def fetch_by_client_id(self, client_id): grants = None redirect_uris = None response_types = None client_data = self.fetchone(self.fetch_client_query, client_id) if client_data is None: raise ClientNotFoundE...
As a Python code composer, you craft elegant and concise scripts.
Fetch data belonging to an authorization code from memcache.
How would you explain what the following Python 3 function does def fetch_by_code(self, code): code_data = self.mc.get(self._generate_cache_key(code)) if code_data is None: raise AuthCodeNotFound return AuthorizationCode(**code_data)
As a Python code translator, you convert algorithms and pseudocode into Python.
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """ key = self._generate_cache_key(authorization_code.code) self.mc.set(key, {"client_id": authorization_code.cli...
Write a Python 3 function for storing the data belonging to an authorization code token in memcache.
You are a Python code architect, reviewing and designing scalable and efficient code
Stores the access token and additional data in memcache.
Given the following Python 3 function, write the documentation def save_token(self, access_token): key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, ...
As a python code expert, you are capable of creating scripts from specifications.
Delete a refresh token after use
Given the following Python 3 function, write the documentation def delete_refresh_token(self, refresh_token): access_token = self.fetch_by_refresh_token(refresh_token) self.mc.delete(self._generate_cache_key(access_token.token)) self.mc.delete(self._generate_cache_key(refresh_token))
You are a Python code generator, capable of creating scripts from specifications.
Encodes a list of scopes into a string.
Here you have a function in Python 3, explain what it does def encode_scopes(scopes, use_quote=False): scopes_as_string = Scope.separator.join(scopes) if use_quote: return quote(scopes_as_string) return scopes_as_string
As a python code expert, you are capable of creating scripts from specifications.
Formats an error as a response containing a JSON body.
Explain what the following Python 3 code does def json_error_response(error, response, status_code=400): msg = {"error": error.error, "error_description": error.explanation} response.status_code = status_code response.add_header("Content-Type", "application/json") response.body = json.dumps(msg) r...
As a Python code analyst, you investigate and solve complex coding mysteries
def json_success_response(data, response): """ Formats the response of a successful token request as JSON. Also adds default headers and status code. """ response.body = json.dumps(data) response.status_code = 200 response.add_header("Content-Type", "application/json") response.add_hea...
Implement a Python 3 function for formatting the response of a successful token request as JSON.
You are a Python code generator, capable of creating scripts from specifications.
Compare the scopes read from request with previously issued scopes.
Make a summary of the following Python 3 code def compare(self, previous_scopes): for scope in self.scopes: if scope not in previous_scopes: raise OAuthInvalidError( error="invalid_scope", explanation="Invalid scope parameter in request") ...
You are a Python code architect, reviewing and designing scalable and efficient code
Parses the scope value in the given request.
Can you generate a brief explanation for the following Python 3 code def parse(self, request, source): if source == "body": req_scope = request.post_param("scope") elif source == "query": req_scope = request.get_param("scope") else: raise ValueError("Unknown s...
As a Python code analyst, you investigate and solve complex coding mysteries
Reads and validates data in an incoming request as required by the client authentication and the Implicit Grant.
Given the following Python 3 function, write the documentation def read_validate_params(self, request): self.client = self.client_authenticator.by_identifier(request) response_type = request.get_param("response_type") if self.client.response_type_supported(response_type) is False: ...
As a Python code composer, you craft elegant and concise scripts.
def authorize(self, request, response, environ, scopes): """ Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually ...
Write a Python 3 function for controlling all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually :param environ: The environment variables of this request :param scopes: The scopes requested ...
You are a Python code analyst, evaluating scripts for potential improvements.
def process(self, request, response, environ): """ Generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`. """ data = self.authorize(request, response, environ, ...
Can you create a Python 3 function that generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`.
As a python code expert, you are capable of creating scripts from specifications.
def handle_error(self, error, response): """ Redirects the client in case an error in the auth process occurred. """ query_params = {"error": error.error} query = urlencode(query_params) location = "%s?%s" % (self.client.redirect_uri, query) response.status_cod...
Write a Python 3 function for redirecting the client in case an error occurs.
As a python code expert, you are capable of creating scripts from specifications.
Generates a new access token and returns it.
Make a summary of the following Python 3 code def process(self, request, response, environ): token_data = self.create_token( client_id=self.client.identifier, data=self.data, grant_type=AuthorizationCodeGrant.grant_type, scopes=self.scopes, user_id=sel...
As a python code expert, you are capable of creating scripts from specifications.
def process(self, request, response, environ): """ Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is returned to the client on successful validation. """ try: data = self.site_adapter.authenticate(re...
How would you implement a function in Python 3 that takes the incoming request checks if the concrete SiteAdapter is valid and issues a new token that is returned to the client on successful validation.
As a Python code analyst, you investigate and solve complex coding mysteries
Checks if all incoming parameters meet the expected values.
Can you generate the documentation for the following Python 3 function def read_validate_params(self, request): self.client = self.client_authenticator.by_identifier_secret(request) self.password = request.post_param("password") self.username = request.post_param("username") self.scope...
As a Python code translator, you convert algorithms and pseudocode into Python.
def process(self, request, response, environ): """ Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` cont...
Write a Python 3 script for creating a new access token and store it in the access token store.
You are a Python code analyst, evaluating scripts for potential improvements.
Validate the incoming request.
Can you tell what is the following Python 3 function doing def read_validate_params(self, request): self.refresh_token = request.post_param("refresh_token") if self.refresh_token is None: raise OAuthInvalidError( error="invalid_request", explanation="Missing ...
As a Python code composer, you craft elegant and concise scripts.
Get value from walking key path with start object obj.
Given the following Python 3 function, write the documentation def value_for_keypath(obj, path): val = obj for part in path.split('.'): match = re.match(list_index_re, part) if match is not None: val = _extract(val, match.group(1)) if not isinstance(val, list) and not isi...
You are a Python code architect, reviewing and designing scalable and efficient code
Set attribute value new_value at key path of object obj.
Can you tell what is the following Python 3 function doing def set_value_for_keypath(obj, path, new_value, preserve_child = False): parts = path.split('.') last_part = len(parts) - 1 dst = obj for i, part in enumerate(parts): match = re.match(list_index_re, part) if match is not None: ...
As a python code expert, you are capable of creating scripts from specifications.
def view_for_image_named(image_name): """Create an ImageView for the given image.""" image = resource.get_image(image_name) if not image: return None return ImageView(pygame.Rect(0, 0, 0, 0), image)
Write a Python 3 function that can create an ImageView for the given image name.
As a Python code analyst, you investigate and solve complex coding mysteries
def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball, _build_install_args(argv))
Write a Python 3 script to install or upgrade setuptools and EasyInstall
As a python code expert, you are capable of creating scripts from specifications.
Fill a surface with a linear gradient pattern.
Given the following Python 3 function, write the documentation def fill_gradient(surface, color, gradient, rect=None, vertical=True, forward=True): """Fill a surface with a linear gradient pattern. color starting color gradient final color rect area to fi...
As a Python code analyst, you investigate and solve complex coding mysteries
This method is called to have the view layout itself.
How would you explain what the following Python 3 function does def layout(self): if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_size, self.frame.h + shadow_size) self.surface = pygame....
You are a Python code architect, reviewing and designing scalable and efficient code
Apply theme style attributes to this instance and its children.
Make a summary of the following Python 3 code def stylize(self): # do children first in case parent needs to override their style for child in self.children: child.stylize() style = theme.current.get_dict(self) preserve_child = False try: preserve_child = ...
As a Python code analyst, you investigate and solve complex coding mysteries
def draw(self): """Do not call directly.""" if self.hidden: return False if self.background_color is not None: render.fillrect(self.surface, self.background_color, rect=pygame.Rect((0, 0), self.frame.size)) for child in self.children...
Create a Python 3 function to do not call directly.
You are a Python code generator, capable of creating scripts from specifications.
def get_border_widths(self): """Return border width for each side top, left, bottom, right.""" if type(self.border_widths) is int: # uniform size return [self.border_widths] * 4 return self.border_widths
Write a Python 3 script for returning border width for each side top left bottom right.
As a Python code composer, you craft elegant and concise scripts.
def hit(self, pt): """Find the view (self, child, or None) under the point `pt`.""" if self.hidden or not self._enabled: return None if not self.frame.collidepoint(pt): return None local_pt = (pt[0] - self.frame.topleft[0], pt[1] - self.fram...
How would you code a function in Python 3 to find the view under the point pt.
As a python code expert, you are capable of creating scripts from specifications.
def bring_to_front(self): """TODO: explain depth sorting""" if self.parent is not None: ch = self.parent.children index = ch.index(self) ch[-1], ch[index] = ch[index], ch[-1]
Write a Python 3 script to bring the class to the front of the tree
As a Python code composer, you craft elegant and concise scripts.
Make the given theme current.
How would you explain what the following Python 3 function does def use_theme(theme): global current current = theme import scene if scene.current is not None: scene.current.stylize()
As a Python code translator, you convert algorithms and pseudocode into Python.