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 update(self, id, body): """Modifies a connection. Args: id: Id of the connection. body (dict): Specifies which fields are to be modified, and to what values. See: https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id Returns: The modified connection object. """
return self.client.patch(self._url(id), data=body)
<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(self, body): """Creates a new connection. Args: body (dict): Attributes used to create the connection. Mandatory attributes are: 'name' and 'strategy'. See: https://auth0.com/docs/api/management/v2#!/Connections/post_connections """
return self.client.post(self._url(), data=body)
<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_user_by_email(self, id, email): """Deletes a specified connection user by its email. Args: id (str): The id of the connection (must be a database connection). email (str): The email of the user to delete. See: https://auth0.com/docs/api/management/v2#!/Connections/delete_users_by_email Returns: An empty dict. """
return self.client.delete(self._url(id) + '/users', params={'email': email})
<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, user_id, client_id, type, fields=None, include_fields=True): """List device credentials. Args: user_id (str): The user_id of the devices to retrieve. client_id (str): The client_id of the devices to retrieve. type (str): The type of credentials (public_key, refresh_token). fields (list, optional): A list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve all fields include_fields (bool, optional): True if the fields specified are to be included in the result, False otherwise (defaults to true) See: https://auth0.com/docs/api/management/v2#!/Device_Credentials/get_device_credentials """
params = { 'fields': fields and ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'user_id': user_id, 'client_id': client_id, 'type': type, } return self.client.get(self._url(), 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 get(self, id): """Retrieves custom domain. See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/get_custom_domains_by_id """
url = self._url('%s' % (id)) return self.client.get(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 delete(self, id): """Deletes a grant. Args: id (str): The id of the custom domain to delete See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/delete_custom_domains_by_id """
url = self._url('%s' % (id)) return self.client.delete(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 create_new(self, body): """Configure a new custom domain Args: body (str): The domain, tye and verification method in json See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/post_custom_domains """
return self.client.post(self._url(), data=body)
<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(self, id): """Verify a custom domain Args: id (str): The id of the custom domain to delete See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/post_verify """
url = self._url('%s/verify' % (id)) return self.client.post(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 saml_metadata(self, client_id): """Get SAML2.0 Metadata. Args: client_id (str): Client Id of the application to get the SAML metadata for. """
return self.get(url='https://{}/samlp/metadata/{}'.format(self.domain, client_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wsfed_metadata(self): """Returns the WS-Federation Metadata. """
url = 'https://{}/wsfed/FederationMetadata' \ '/2007-06/FederationMetadata.xml' return self.get(url=url.format(self.domain))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self, fields=None, include_fields=True, page=None, per_page=None, extra_params=None): """Retrieves a list of all the applications. Important: The client_secret and encryption_key attributes can only be retrieved with the read:client_keys scope. Args: fields (list of str, optional): A list of fields to include or exclude from the result (depending on include_fields). Empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be included in the result, False otherwise. page (int): The result's page number (zero based). per_page (int, optional): The amount of entries per page. extra_params (dictionary, optional): The extra parameters to add to the request. The fields, include_fields, page and per_page values specified as parameters take precedence over the ones defined here. See: https://auth0.com/docs/api/management/v2#!/Clients/get_clients """
params = extra_params or {} params['fields'] = fields and ','.join(fields) or None params['include_fields'] = str(include_fields).lower() params['page'] = page params['per_page'] = per_page return self.client.get(self._url(), 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 rotate_secret(self, id): """Rotate a client secret. The generated secret is NOT base64 encoded. Args: id (str): Client ID of the application. body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Clients/post_rotate_secret """
params = {'id': id } url = self._url('%s/rotate-secret' % id) return self.client.get(url, 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 email(self, client_id, email, send='link', auth_params=None): """Start flow sending an email. Given the user email address, it will send an email with: - A link (default, send:"link"). You can then authenticate with this user opening the link and he will be automatically logged in to the application. Optionally, you can append/override parameters to the link (like scope, redirect_uri, protocol, response_type, etc.) using auth_params dict. - A verification code (send:"code"). You can then authenticate with this user using email as username and code as password. Args: client_id (str): Client Id of the application. email (str): Email address. send (str, optional): Can be: 'link' or 'code'. Defaults to 'link'. auth_params (dict, optional): Parameters to append or override. """
return self.post( 'https://{}/passwordless/start'.format(self.domain), data={ 'client_id': client_id, 'connection': 'email', 'email': email, 'send': send, 'authParams': auth_params }, headers={'Content-Type': 'application/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 sms(self, client_id, phone_number): """Start flow sending a SMS message. """
return self.post( 'https://{}/passwordless/start'.format(self.domain), data={ 'client_id': client_id, 'connection': 'sms', 'phone_number': phone_number, }, headers={'Content-Type': 'application/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 get_all(self, page=None, per_page=None, include_totals=False): """Retrieves all resource servers Args: page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. include_totals (bool, optional): True if the query summary is to be included in the result, False otherwise. See: https://auth0.com/docs/api/management/v2#!/Resource_Servers/get_resource_servers """
params = { 'page': page, 'per_page': per_page, 'include_totals': str(include_totals).lower() } return self.client.get(self._url(), 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 get_by_identifier(self, identifier): """Gets blocks by identifier Args: identifier (str): Should be any of: username, phone_number, email. See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks """
params = {'identifier': identifier} return self.client.get(self._url(), 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 unblock_by_identifier(self, identifier): """Unblocks by identifier Args: identifier (str): Should be any of: username, phone_number, email. See: https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks """
params = {'identifier': identifier} return self.client.delete(self._url(), 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 get_token(self, client_id, target, api_type, grant_type, id_token=None, refresh_token=None, scope='openid'): """Obtain a delegation token. """
if id_token and refresh_token: raise ValueError('Only one of id_token or refresh_token ' 'can be None') data = { 'client_id': client_id, 'grant_type': grant_type, 'target': target, 'scope': scope, 'api_type': api_type, } if id_token: data.update({'id_token': id_token}) elif refresh_token: data.update({'refresh_token': refresh_token}) else: raise ValueError('Either id_token or refresh_token must ' 'have a value') return self.post( 'https://{}/delegation'.format(self.domain), headers={'Content-Type': 'application/json'}, data=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 update_templates(self, body): """Update enrollment and verification SMS templates. Useful to send custom messages on sms enrollment and verification Args: body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guardian/put_templates """
return self.client.put(self._url('factors/sms/templates'), data=body)
<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_enrollment(self, id): """Retrieves an enrollment. Useful to check its type and related metadata. Args: id (str): The id of the device account to update See: https://auth0.com/docs/api/management/v2#!/Guardian/get_enrollments_by_id """
url = self._url('enrollments/{}'.format(id)) return self.client.get(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 delete_enrollment(self, id): """Deletes an enrollment. Useful when you want to force re-enroll. Args: id (str): The id of the device account to update See: https://auth0.com/docs/api/management/v2#!/Guardian/delete_enrollments_by_id """
url = self._url('enrollments/{}'.format(id)) return self.client.delete(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 create_enrollment_ticket(self, body): """Creates an enrollment ticket for user_id A useful way to send an email to a user, with a link that lead to start the enrollment process Args: body (dict): Details of the user to send the ticket to. See: https://auth0.com/docs/api/management/v2#!/Guardian/post_ticket """
return self.client.post(self._url('enrollments/ticket'), data=body)
<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_factor_providers(self, factor_name, name): """Get Guardian SNS or SMS factor providers. Returns provider configuration Args: factor_name (str): Either push-notification or sms name (str): Name of the provider See: https://auth0.com/docs/api/management/v2#!/Guardian/get_sns https://auth0.com/docs/api/management/v2#!/Guardian/get_twilio """
url = self._url('factors/{}/providers/{}'.format(factor_name, name)) return self.client.get(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 update_factor_providers(self, factor_name, name, body): """Get Guardian factor providers. Returns provider configuration Args: factor_name (str): Either push-notification or sms name (str): Name of the provider body (dict): See: https://auth0.com/docs/api/management/v2#!/Guardian/put_twilio """
url = self._url('factors/{}/providers/{}'.format(factor_name, name)) return self.client.put(url, data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revoke_refresh_token(self, client_id, token, client_secret=None): """Revokes a Refresh Token if it has been compromised Each revocation request invalidates not only the specific token, but all other tokens based on the same authorization grant. This means that all Refresh Tokens that have been issued for the same user, application, and audience will be revoked. Args: client_id (str): The Client ID for your Application token (str): The Refresh Token you want to revoke client_secret (str, optional): The Client Secret for your Application. Required for confidential applications. See: https://auth0.com/docs/applications/application-types#confidential-applications See: https://auth0.com/docs/api/authentication#refresh-token """
body = { 'client_id': client_id, 'token': token, 'client_secret': client_secret } return self.post( 'https://{}/oauth/revoke'.format(self.domain), data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unset(self, key): """Removes the rules config for a given key. Args: key (str): rules config key to remove See: https://auth0.com/docs/api/management/v2#!/Rules_Configs/delete_rules_configs_by_key """
params = { 'key': key } return self.client.delete(self._url(), 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 set(self, key, value): """Sets the rules config for a given key. Args: key (str): rules config key to set value (str): value to set for the rules config key See: https://auth0.com/docs/api/management/v2#!/Rules_Configs/put_rules_configs_by_key """
url = self._url('{}'.format(key)) body = {'value': value} return self.client.put(url, data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def daily_stats(self, from_date=None, to_date=None): """Gets the daily stats for a particular period. Args: from_date (str): The first day of the period (inclusive) in YYYYMMDD format. to_date (str): The last day of the period (inclusive) in YYYYMMDD format. See: https://auth0.com/docs/api/management/v2#!/Stats/get_daily """
return self.client.get(self._url('daily'), params={'from': from_date, 'to': to_date})
<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_email_verification(self, body): """Create an email verification ticket. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Tickets/post_email_verification """
return self.client.post(self._url('email-verification'), data=body)
<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_pswd_change(self, body): """Create password change ticket. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Tickets/post_password_change """
return self.client.post(self._url('password-change'), data=body)
<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, page=0, per_page=50, sort=None, q=None, include_totals=True, fields=None, from_param=None, take=None, include_fields=True): """Search log events. Args: page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. sort (str, optional): The field to use for sorting. 1 == ascending and -1 == descending. (e.g: date:1) q (str, optional): Query in Lucene query string syntax. fields (list of str, optional): A list of fields to include or exclude from the result (depending on include_fields). Empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be included in the result, False otherwise. include_totals (bool, optional): True if the query summary is to be included in the result, False otherwise. from_param (str, optional): Log Event Id to start retrieving logs. You can limit the amount of logs using the take parameter take (int, optional): The total amount of entries to retrieve when using the from parameter. https://auth0.com/docs/api/management/v2#!/Logs/get_logs """
params = { 'per_page': per_page, 'page': page, 'include_totals': str(include_totals).lower(), 'sort': sort, 'fields': fields and ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'q': q, 'from': from_param, 'take': take } return self.client.get(self._url(), 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 all(self, audience=None, page=None, per_page=None, include_totals=False, client_id=None): """Retrieves all client grants. Args: audience (str, optional): URL encoded audience of a Resource Server to filter page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. include_totals (bool, optional): True if the query summary is to be included in the result, False otherwise. client_id (string, optional): The id of a client to filter See: https://auth0.com/docs/api/management/v2#!/Client_Grants/get_client_grants """
params = { 'audience': audience, 'page': page, 'per_page': per_page, 'include_totals': str(include_totals).lower(), 'client_id': client_id, } return self.client.get(self._url(), 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 login(self, client_id, access_token, connection, scope='openid'): """Login using a social provider's access token Given the social provider's access_token and the connection specified, it will do the authentication on the provider and return a dict with the access_token and id_token. Currently, this endpoint only works for Facebook, Google, Twitter and Weibo. Args: client_id (str): application's client id. access_token (str): social provider's access_token. connection (str): connection type (e.g: 'facebook') Returns: A dict with 'access_token' and 'id_token' keys. """
return self.post( 'https://{}/oauth/access_token'.format(self.domain), data={ 'client_id': client_id, 'access_token': access_token, 'connection': connection, 'scope': scope, }, headers={'Content-Type': 'application/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 get(self, aud=None): """Retrieves the jti and aud of all tokens in the blacklist. Args: aud (str, optional): The JWT's aud claim. The client_id of the application for which it was issued. See: https://auth0.com/docs/api/management/v2#!/Blacklists/get_tokens """
params = { 'aud': aud } return self.client.get(self.url, 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(self, jti, aud=''): """Adds a token to the blacklist. Args: jti (str): the jti of the JWT to blacklist. aud (str, optional): The JWT's aud claim. The client_id of the application for which it was issued. body (dict): See: https://auth0.com/docs/api/management/v2#!/Blacklists/post_tokens """
return self.client.post(self.url, data={'jti': jti, 'aud': aud})
<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, page=0, per_page=25, sort=None, connection=None, q=None, search_engine=None, include_totals=True, fields=None, include_fields=True): """List or search users. Args: page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. sort (str, optional): The field to use for sorting. 1 == ascending and -1 == descending. (e.g: email:1) connection (str, optional): Connection filter. q (str, optional): Query in Lucene query string syntax. Only fields in app_metadata, user_metadata or the normalized user profile are searchable. search_engine (str, optional): The version of the search_engine to use when querying for users. Will default to the latest version available. See: https://auth0.com/docs/users/search fields (list of str, optional): A list of fields to include or exclude from the result (depending on include_fields). Empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be include in the result, False otherwise. See: https://auth0.com/docs/api/management/v2#!/Users/get_users """
params = { 'per_page': per_page, 'page': page, 'include_totals': str(include_totals).lower(), 'sort': sort, 'connection': connection, 'fields': fields and ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'q': q, 'search_engine': search_engine } return self.client.get(self._url(), 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_multifactor(self, id, provider): """Delete a user's multifactor provider. Args: id (str): The user's id. provider (str): The multifactor provider. Supported values 'duo' or 'google-authenticator' See: https://auth0.com/docs/api/management/v2#!/Users/delete_multifactor_by_provider """
url = self._url('{}/multifactor/{}'.format(id, provider)) return self.client.delete(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 unlink_user_account(self, id, provider, user_id): """Unlink a user account Args: id (str): The user_id of the user identity. provider (str): The type of identity provider (e.g: facebook). user_id (str): The unique identifier for the user for the identity. See: https://auth0.com/docs/api/management/v2#!/Users/delete_user_identity_by_user_id """
url = self._url('{}/identities/{}/{}'.format(id, provider, user_id)) return self.client.delete(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 link_user_account(self, user_id, body): """Link user accounts. Links the account specified in the body (secondary account) to the account specified by the id param of the URL (primary account). Args: id (str): The user_id of the primary identity where you are linking the secondary account to. body (dict): Please see: https://auth0.com/docs/api/v2#!/Users/post_identities """
url = self._url('{}/identities'.format(user_id)) return self.client.post(url, data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regenerate_recovery_code(self, user_id): """Removes the current recovery token, generates and returns a new one Args: user_id (str): The user_id of the user identity. See: https://auth0.com/docs/api/management/v2#!/Users/post_recovery_code_regeneration """
url = self._url('{}/recovery-code-regeneration'.format(user_id)) return self.client.post(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_guardian_enrollments(self, user_id): """Retrieves all Guardian enrollments. Args: user_id (str): The user_id of the user to retrieve See: https://auth0.com/docs/api/management/v2#!/Users/get_enrollments """
url = self._url('{}/enrollments'.format(user_id)) return self.client.get(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_log_events(self, user_id, page=0, per_page=50, sort=None, include_totals=False): """Retrieve every log event for a specific user id Args: user_id (str): The user_id of the logs to retrieve page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. Default: 50. Max value: 100 sort (str, optional): The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1 include_totals (bool, optional): True if the query summary is to be included in the result, False otherwise. See: https://auth0.com/docs/api/management/v2#!/Users/get_logs_by_user """
params = { 'per_page': per_page, 'page': page, 'include_totals': str(include_totals).lower(), 'sort': sort } url = self._url('{}/logs'.format(user_id)) return self.client.get(url, 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 all(self, stage='login_success', enabled=True, fields=None, include_fields=True, page=None, per_page=None, include_totals=False): """Retrieves a list of all rules. Args: stage (str, optional): Retrieves rules that match the execution stage (defaults to login_success). enabled (bool, optional): If provided, retrieves rules that match the value, otherwise all rules are retrieved. fields (list, optional): A list of fields to include or exclude (depending on include_fields) from the result, empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be included in the result, False otherwise (defaults to true). page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. include_totals (bool, optional): True if the query summary is to be included in the result, False otherwise. See: https://auth0.com/docs/api/management/v2#!/Rules/get_rules """
params = { 'stage': stage, 'fields': fields and ','.join(fields) or None, 'include_fields': str(include_fields).lower(), 'page': page, 'per_page': per_page, 'include_totals': str(include_totals).lower() } # since the default is True, this is here to disable the filter if enabled is not None: params['enabled'] = str(enabled).lower() return self.client.get(self._url(), 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 get_failed_job(self, id): """Get failed job error details Args: id (str): The id of the job. See: https://auth0.com/docs/api/management/v2#!/Jobs/get_errors """
url = self._url('{}/errors'.format(id)) return self.client.get(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_results(self, job_id): """Get results of a job Args: job_id (str): The ID of the job. See: https://auth0.com/docs/api/management/v2#!/Jobs/get_results """
url = self._url('%s/results' % job_id) return self.client.get(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 export_users(self, body): """Export all users to a file using a long running job. Check job status with get(). URL pointing to the export file will be included in the status once the job is complete. Args: body (dict): Please see: https://auth0.com/docs/api/management/v2#!/Jobs/post_users_exports """
return self.client.post(self._url('users-exports'), data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_users(self, connection_id, file_obj, upsert=False): """Imports users to a connection from a file. Args: connection_id (str): The connection id of the connection to which users will be inserted. file_obj (file): A file-like object to upload. The format for this file is explained in: https://auth0.com/docs/bulk-import See: https://auth0.com/docs/api/management/v2#!/Jobs/post_users_imports """
return self.client.file_post(self._url('users-imports'), data={'connection_id': connection_id, 'upsert': str(upsert).lower()}, files={'users': file_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 send_verification_email(self, body): """Send verification email. Send an email to the specified user that asks them to click a link to verify their email address. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Jobs/post_verification_email """
return self.client.post(self._url('verification-email'), data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(self, body): """Configure the email provider. Args: body (dict): Please see: https://auth0.com/docs/api/v2#!/Emails/post_provider """
return self.client.post(self._url(), data=body)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. This endpoint will work only if openid was granted as a scope for the access_token. Args: access_token (str): Auth0 access token (obtained during login). Returns: The user profile. """
return self.get( url='https://{}/userinfo'.format(self.domain), headers={'Authorization': 'Bearer {}'.format(access_token)} )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokeninfo(self, jwt): """Returns user profile based on the user's jwt Validates a JSON Web Token (signature and expiration) and returns the user information associated with the user id (sub property) of the token. Args: jwt (str): User's jwt Returns: The user profile. """
warnings.warn("/tokeninfo will be deprecated in future releases", DeprecationWarning) return self.post( url='https://{}/tokeninfo'.format(self.domain), data={'id_token': jwt}, headers={'Content-Type': 'application/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 all(self, page=None, per_page=None, include_totals=False, extra_params=None): """Retrieves all grants. Args: page (int, optional): The result's page number (zero based). per_page (int, optional): The amount of entries per page. include_totals (bool, optional): True if the query summary is to be included in the result, False otherwise. extra_params (dictionary, optional): The extra parameters to add to the request. The page, per_page, and include_totals values specified as parameters take precedence over the ones defined here. See: https://auth0.com/docs/api/management/v2#!/Grants/get_grants """
params = extra_params or {} params.update({ 'page': page, 'per_page': per_page, 'include_totals': str(include_totals).lower() }) return self.client.get(self._url(), 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 change_password(self, client_id, email, connection, password=None): """Asks to change a password for a given user. """
return self.post( 'https://{}/dbconnections/change_password'.format(self.domain), data={ 'client_id': client_id, 'email': email, 'password': password, 'connection': connection, }, headers={'Content-Type': 'application/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 encrypt(self, k, a, m): """ Encrypt according to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authentication Data :param m: Plaintext Returns a dictionary with the computed data. """
hkey = k[:_inbytes(self.keysize)] ekey = k[_inbytes(self.keysize):] # encrypt iv = _randombits(self.blocksize) cipher = Cipher(algorithms.AES(ekey), modes.CBC(iv), backend=self.backend) encryptor = cipher.encryptor() padder = PKCS7(self.blocksize).padder() padded_data = padder.update(m) + padder.finalize() e = encryptor.update(padded_data) + encryptor.finalize() # mac t = self._mac(hkey, a, iv, e) return (iv, e, t)
<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(self, k, a, m): """ Encrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authentication Data :param m: Plaintext Returns a dictionary with the computed data. """
iv = _randombits(96) cipher = Cipher(algorithms.AES(k), modes.GCM(iv), backend=self.backend) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(a) e = encryptor.update(m) + encryptor.finalize() return (iv, e, encryptor.tag)
<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_json(cls, key): """Creates a RFC 7517 JWK from the standard JSON format. :param key: The RFC 7517 representation of a JWK. """
obj = cls() try: jkey = json_decode(key) except Exception as e: # pylint: disable=broad-except raise InvalidJWKValue(e) obj.import_key(**jkey) return 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 export(self, private_key=True): """Exports the key in the standard JSON format. Exports the key regardless of type, if private_key is False and the key is_symmetric an exceptionis raised. :param private_key(bool): Whether to export the private key. Defaults to True. """
if private_key is True: # Use _export_all for backwards compatibility, as this # function allows to export symmetrict keys too return self._export_all() else: return self.export_public()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_public(self): """Whether this JWK has an asymmetric Public key."""
if self.is_symmetric: return False reg = JWKValuesRegistry[self._params['kty']] for value in reg: if reg[value].public and value in self._key: return 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 get_curve(self, arg): """Gets the Elliptic Curve associated with the key. :param arg: an optional curve name :raises InvalidJWKType: the key is not an EC or OKP key. :raises InvalidJWKValue: if the curve names is invalid. """
k = self._key if self._params['kty'] not in ['EC', 'OKP']: raise InvalidJWKType('Not an EC or OKP key') if arg and k['crv'] != arg: raise InvalidJWKValue('Curve requested is "%s", but ' 'key curve is "%s"' % (arg, k['crv'])) return self._get_curve_by_name(k['crv'])
<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_op_key(self, operation=None, arg=None): """Get the key object associated to the requested opration. For example the public RSA key for the 'verify' operation or the private EC key for the 'decrypt' operation. :param operation: The requested operation. The valid set of operations is availble in the :data:`JWKOperationsRegistry` registry. :param arg: an optional, context specific, argument For example a curve name. :raises InvalidJWKOperation: if the operation is unknown or not permitted with this key. :raises InvalidJWKUsage: if the use constraints do not permit the operation. """
validops = self._params.get('key_ops', list(JWKOperationsRegistry.keys())) if validops is not list: validops = [validops] if operation is None: if self._params['kty'] == 'oct': return self._key['k'] raise InvalidJWKOperation(operation, validops) elif operation == 'sign': self._check_constraints('sig', operation) return self._get_private_key(arg) elif operation == 'verify': self._check_constraints('sig', operation) return self._get_public_key(arg) elif operation == 'encrypt' or operation == 'wrapKey': self._check_constraints('enc', operation) return self._get_public_key(arg) elif operation == 'decrypt' or operation == 'unwrapKey': self._check_constraints('enc', operation) return self._get_private_key(arg) else: raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thumbprint(self, hashalg=hashes.SHA256()): """Returns the key thumbprint as specified by RFC 7638. :param hashalg: A hash function (defaults to SHA256) """
t = {'kty': self._params['kty']} for name, val in iteritems(JWKValuesRegistry[t['kty']]): if val.required: t[name] = self._key[name] digest = hashes.Hash(hashalg, backend=default_backend()) digest.update(bytes(json_encode(t).encode('utf8'))) return base64url_encode(digest.finalize())
<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, elem): """Adds a JWK object to the set :param elem: the JWK object to add. :raises TypeError: if the object is not a JWK. """
if not isinstance(elem, JWK): raise TypeError('Only JWK objects are valid elements') set.add(self, elem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self, private_keys=True): """Exports a RFC 7517 keyset using the standard JSON format :param private_key(bool): Whether to export private keys. Defaults to True. """
exp_dict = dict() for k, v in iteritems(self): if k == 'keys': keys = list() for jwk in v: keys.append(json_decode(jwk.export(private_keys))) v = keys exp_dict[k] = v return json_encode(exp_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_keyset(self, keyset): """Imports a RFC 7517 keyset using the standard JSON format. :param keyset: The RFC 7517 representation of a JOSE Keyset. """
try: jwkset = json_decode(keyset) except Exception: # pylint: disable=broad-except raise InvalidJWKValue() if 'keys' not in jwkset: raise InvalidJWKValue() for k, v in iteritems(jwkset): if k == 'keys': for jwk in v: self['keys'].add(JWK(**jwk)) else: self[k] = v
<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_recipient(self, key, header=None): """Encrypt the plaintext with the given key. :param key: A JWK key or password of appropriate type for the 'alg' provided in the JOSE Headers. :param header: A JSON string representing the per-recipient header. :raises ValueError: if the plaintext is missing or not of type bytes. :raises ValueError: if the compression type is unknown. :raises InvalidJWAAlgorithm: if the 'alg' provided in the JOSE headers is missing or unknown, or otherwise not implemented. """
if self.plaintext is None: raise ValueError('Missing plaintext') if not isinstance(self.plaintext, bytes): raise ValueError("Plaintext must be 'bytes'") if isinstance(header, dict): header = json_encode(header) jh = self._get_jose_header(header) alg, enc = self._get_alg_enc_from_headers(jh) rec = dict() if header: rec['header'] = header wrapped = alg.wrap(key, enc.wrap_key_size, self.cek, jh) self.cek = wrapped['cek'] if 'ek' in wrapped: rec['encrypted_key'] = wrapped['ek'] if 'header' in wrapped: h = json_decode(rec.get('header', '{}')) nh = self._merge_headers(h, wrapped['header']) rec['header'] = json_encode(nh) if 'ciphertext' not in self.objects: self._encrypt(alg, enc, jh) if 'recipients' in self.objects: self.objects['recipients'].append(rec) elif 'encrypted_key' in self.objects or 'header' in self.objects: self.objects['recipients'] = list() n = dict() if 'encrypted_key' in self.objects: n['encrypted_key'] = self.objects.pop('encrypted_key') if 'header' in self.objects: n['header'] = self.objects.pop('header') self.objects['recipients'].append(n) self.objects['recipients'].append(rec) else: self.objects.update(rec)
<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(self, compact=False): """Serializes the object into a JWE token. :param compact(boolean): if True generates the compact representation, otherwise generates a standard JSON format. :raises InvalidJWEOperation: if the object cannot serialized with the compact representation and `compact` is True. :raises InvalidJWEOperation: if no recipients have been added to the object. """
if 'ciphertext' not in self.objects: raise InvalidJWEOperation("No available ciphertext") if compact: for invalid in 'aad', 'unprotected': if invalid in self.objects: raise InvalidJWEOperation( "Can't use compact encoding when the '%s' parameter" "is set" % invalid) if 'protected' not in self.objects: raise InvalidJWEOperation( "Can't use compat encoding without protected headers") else: ph = json_decode(self.objects['protected']) for required in 'alg', 'enc': if required not in ph: raise InvalidJWEOperation( "Can't use compat encoding, '%s' must be in the " "protected header" % required) if 'recipients' in self.objects: if len(self.objects['recipients']) != 1: raise InvalidJWEOperation("Invalid number of recipients") rec = self.objects['recipients'][0] else: rec = self.objects if 'header' in rec: # The AESGCMKW algorithm generates data (iv, tag) we put in the # per-recipient unpotected header by default. Move it to the # protected header and re-encrypt the payload, as the protected # header is used as additional authenticated data. h = json_decode(rec['header']) ph = json_decode(self.objects['protected']) nph = self._merge_headers(h, ph) self.objects['protected'] = json_encode(nph) jh = self._get_jose_header() alg, enc = self._get_alg_enc_from_headers(jh) self._encrypt(alg, enc, jh) del rec['header'] return '.'.join([base64url_encode(self.objects['protected']), base64url_encode(rec.get('encrypted_key', '')), base64url_encode(self.objects['iv']), base64url_encode(self.objects['ciphertext']), base64url_encode(self.objects['tag'])]) else: obj = self.objects enc = {'ciphertext': base64url_encode(obj['ciphertext']), 'iv': base64url_encode(obj['iv']), 'tag': base64url_encode(self.objects['tag'])} if 'protected' in obj: enc['protected'] = base64url_encode(obj['protected']) if 'unprotected' in obj: enc['unprotected'] = json_decode(obj['unprotected']) if 'aad' in obj: enc['aad'] = base64url_encode(obj['aad']) if 'recipients' in obj: enc['recipients'] = list() for rec in obj['recipients']: e = dict() if 'encrypted_key' in rec: e['encrypted_key'] = \ base64url_encode(rec['encrypted_key']) if 'header' in rec: e['header'] = json_decode(rec['header']) enc['recipients'].append(e) else: if 'encrypted_key' in obj: enc['encrypted_key'] = \ base64url_encode(obj['encrypted_key']) if 'header' in obj: enc['header'] = json_decode(obj['header']) return json_encode(enc)
<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(self, key): """Decrypt a JWE token. :param key: The (:class:`jwcrypto.jwk.JWK`) decryption key. :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key or a password string (optional). :raises InvalidJWEOperation: if the key is not a JWK object. :raises InvalidJWEData: if the ciphertext can't be decrypted or the object is otherwise malformed. """
if 'ciphertext' not in self.objects: raise InvalidJWEOperation("No available ciphertext") self.decryptlog = list() if 'recipients' in self.objects: for rec in self.objects['recipients']: try: self._decrypt(key, rec) except Exception as e: # pylint: disable=broad-except self.decryptlog.append('Failed: [%s]' % repr(e)) else: try: self._decrypt(key, self.objects) except Exception as e: # pylint: disable=broad-except self.decryptlog.append('Failed: [%s]' % repr(e)) if not self.plaintext: raise InvalidJWEData('No recipient matched the provided ' 'key' + repr(self.decryptlog))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(self, raw_jwe, key=None): """Deserialize a JWE token. NOTE: Destroys any current status and tries to import the raw JWE provided. :param raw_jwe: a 'raw' JWE token (JSON Encoded or Compact notation) string. :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key or a password string (optional). If a key is provided a decryption step will be attempted after the object is successfully deserialized. :raises InvalidJWEData: if the raw object is an invaid JWE token. :raises InvalidJWEOperation: if the decryption fails. """
self.objects = dict() self.plaintext = None self.cek = None o = dict() try: try: djwe = json_decode(raw_jwe) o['iv'] = base64url_decode(djwe['iv']) o['ciphertext'] = base64url_decode(djwe['ciphertext']) o['tag'] = base64url_decode(djwe['tag']) if 'protected' in djwe: p = base64url_decode(djwe['protected']) o['protected'] = p.decode('utf-8') if 'unprotected' in djwe: o['unprotected'] = json_encode(djwe['unprotected']) if 'aad' in djwe: o['aad'] = base64url_decode(djwe['aad']) if 'recipients' in djwe: o['recipients'] = list() for rec in djwe['recipients']: e = dict() if 'encrypted_key' in rec: e['encrypted_key'] = \ base64url_decode(rec['encrypted_key']) if 'header' in rec: e['header'] = json_encode(rec['header']) o['recipients'].append(e) else: if 'encrypted_key' in djwe: o['encrypted_key'] = \ base64url_decode(djwe['encrypted_key']) if 'header' in djwe: o['header'] = json_encode(djwe['header']) except ValueError: c = raw_jwe.split('.') if len(c) != 5: raise InvalidJWEData() p = base64url_decode(c[0]) o['protected'] = p.decode('utf-8') ekey = base64url_decode(c[1]) if ekey != b'': o['encrypted_key'] = base64url_decode(c[1]) o['iv'] = base64url_decode(c[2]) o['ciphertext'] = base64url_decode(c[3]) o['tag'] = base64url_decode(c[4]) self.objects = o except Exception as e: # pylint: disable=broad-except raise InvalidJWEData('Invalid format', repr(e)) if key: self.decrypt(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 sign(self): """Generates a signature"""
payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) signature = self.engine.sign(self.key, sigin) return {'protected': self.protected, 'payload': payload, 'signature': base64url_encode(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 verify(self, signature): """Verifies a signature :raises InvalidJWSSignature: if the verification fails. """
try: payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) self.engine.verify(self.key, sigin, signature) except Exception as e: # pylint: disable=broad-except raise InvalidJWSSignature('Verification failed', repr(e)) return 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 verify(self, key, alg=None): """Verifies a JWS token. :param key: The (:class:`jwcrypto.jwk.JWK`) verification key. :param alg: The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token. :raises InvalidJWSSignature: if the verification fails. """
self.verifylog = list() self.objects['valid'] = False obj = self.objects if 'signature' in obj: try: self._verify(alg, key, obj['payload'], obj['signature'], obj.get('protected', None), obj.get('header', None)) obj['valid'] = True except Exception as e: # pylint: disable=broad-except self.verifylog.append('Failed: [%s]' % repr(e)) elif 'signatures' in obj: for o in obj['signatures']: try: self._verify(alg, key, obj['payload'], o['signature'], o.get('protected', None), o.get('header', None)) # Ok if at least one verifies obj['valid'] = True except Exception as e: # pylint: disable=broad-except self.verifylog.append('Failed: [%s]' % repr(e)) else: raise InvalidJWSSignature('No signatures availble') if not self.is_valid: raise InvalidJWSSignature('Verification failed for all ' 'signatures' + repr(self.verifylog))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(self, raw_jws, key=None, alg=None): """Deserialize a JWS token. NOTE: Destroys any current status and tries to import the raw JWS provided. :param raw_jws: a 'raw' JWS token (JSON Encoded or Compact notation) string. :param key: A (:class:`jwcrypto.jwk.JWK`) verification key (optional). If a key is provided a verification step will be attempted after the object is successfully deserialized. :param alg: The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token. :raises InvalidJWSObject: if the raw object is an invaid JWS token. :raises InvalidJWSSignature: if the verification fails. """
self.objects = dict() o = dict() try: try: djws = json_decode(raw_jws) if 'signatures' in djws: o['signatures'] = list() for s in djws['signatures']: os = self._deserialize_signature(s) o['signatures'].append(os) self._deserialize_b64(o, os.get('protected')) else: o = self._deserialize_signature(djws) self._deserialize_b64(o, o.get('protected')) if 'payload' in djws: if o.get('b64', True): o['payload'] = base64url_decode(str(djws['payload'])) else: o['payload'] = djws['payload'] except ValueError: c = raw_jws.split('.') if len(c) != 3: raise InvalidJWSObject('Unrecognized representation') p = base64url_decode(str(c[0])) if len(p) > 0: o['protected'] = p.decode('utf-8') self._deserialize_b64(o, o['protected']) o['payload'] = base64url_decode(str(c[1])) o['signature'] = base64url_decode(str(c[2])) self.objects = o except Exception as e: # pylint: disable=broad-except raise InvalidJWSObject('Invalid format', repr(e)) if key: self.verify(key, alg)
<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_signature(self, key, alg=None, protected=None, header=None): """Adds a new signature to the object. :param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate for the "alg" provided. :param alg: An optional algorithm name. If already provided as an element of the protected or unprotected header it can be safely omitted. :param potected: The Protected Header (optional) :param header: The Unprotected Header (optional) :raises InvalidJWSObject: if no payload has been set on the object, or invalid headers are provided. :raises ValueError: if the key is not a :class:`JWK` object. :raises ValueError: if the algorithm is missing or is not provided by one of the headers. :raises InvalidJWAAlgorithm: if the algorithm is not valid, is unknown or otherwise not yet implemented. """
if not self.objects.get('payload', None): raise InvalidJWSObject('Missing Payload') b64 = True p = dict() if protected: if isinstance(protected, dict): p = protected protected = json_encode(p) else: p = json_decode(protected) # If b64 is present we must enforce criticality if 'b64' in list(p.keys()): crit = p.get('crit', []) if 'b64' not in crit: raise InvalidJWSObject('b64 header must always be critical') b64 = p['b64'] if 'b64' in self.objects: if b64 != self.objects['b64']: raise InvalidJWSObject('Mixed b64 headers on signatures') h = None if header: if isinstance(header, dict): h = header header = json_encode(header) else: h = json_decode(header) p = self._merge_check_headers(p, h) if 'alg' in p: if alg is None: alg = p['alg'] elif alg != p['alg']: raise ValueError('"alg" value mismatch, specified "alg" ' 'does not match JOSE header value') if alg is None: raise ValueError('"alg" not specified') c = JWSCore(alg, key, protected, self.objects['payload']) sig = c.sign() o = dict() o['signature'] = base64url_decode(sig['signature']) if protected: o['protected'] = protected if header: o['header'] = h o['valid'] = True if 'signatures' in self.objects: self.objects['signatures'].append(o) elif 'signature' in self.objects: self.objects['signatures'] = list() n = dict() n['signature'] = self.objects.pop('signature') if 'protected' in self.objects: n['protected'] = self.objects.pop('protected') if 'header' in self.objects: n['header'] = self.objects.pop('header') if 'valid' in self.objects: n['valid'] = self.objects.pop('valid') self.objects['signatures'].append(n) self.objects['signatures'].append(o) else: self.objects.update(o) self.objects['b64'] = b64
<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(self, compact=False): """Serializes the object into a JWS token. :param compact(boolean): if True generates the compact representation, otherwise generates a standard JSON format. :raises InvalidJWSOperation: if the object cannot serialized with the compact representation and `compat` is True. :raises InvalidJWSSignature: if no signature has been added to the object, or no valid signature can be found. """
if compact: if 'signatures' in self.objects: raise InvalidJWSOperation("Can't use compact encoding with " "multiple signatures") if 'signature' not in self.objects: raise InvalidJWSSignature("No available signature") if not self.objects.get('valid', False): raise InvalidJWSSignature("No valid signature found") if 'protected' in self.objects: protected = base64url_encode(self.objects['protected']) else: protected = '' if self.objects.get('payload', False): if self.objects.get('b64', True): payload = base64url_encode(self.objects['payload']) else: if isinstance(self.objects['payload'], bytes): payload = self.objects['payload'].decode('utf-8') else: payload = self.objects['payload'] if '.' in payload: raise InvalidJWSOperation( "Can't use compact encoding with unencoded " "payload that uses the . character") else: payload = '' return '.'.join([protected, payload, base64url_encode(self.objects['signature'])]) else: obj = self.objects sig = dict() if self.objects.get('payload', False): if self.objects.get('b64', True): sig['payload'] = base64url_encode(self.objects['payload']) else: sig['payload'] = self.objects['payload'] if 'signature' in obj: if not obj.get('valid', False): raise InvalidJWSSignature("No valid signature found") sig['signature'] = base64url_encode(obj['signature']) if 'protected' in obj: sig['protected'] = base64url_encode(obj['protected']) if 'header' in obj: sig['header'] = obj['header'] elif 'signatures' in obj: sig['signatures'] = list() for o in obj['signatures']: if not o.get('valid', False): continue s = {'signature': base64url_encode(o['signature'])} if 'protected' in o: s['protected'] = base64url_encode(o['protected']) if 'header' in o: s['header'] = o['header'] sig['signatures'].append(s) if len(sig['signatures']) == 0: raise InvalidJWSSignature("No valid signature found") else: raise InvalidJWSSignature("No available signature") return json_encode(sig)
<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_signed_token(self, key): """Signs the payload. Creates a JWS token with the header as the JWS protected header and the claims as the payload. See (:class:`jwcrypto.jws.JWS`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk.JWK`) key. """
t = JWS(self.claims) t.add_signature(key, protected=self.header) self.token = t
<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_encrypted_token(self, key): """Encrypts the payload. Creates a JWE token with the header as the JWE protected header and the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk.JWK`) key. """
t = JWE(self.claims, self.header) t.add_recipient(key) self.token = t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(self, jwt, key=None): """Deserialize a JWT token. NOTE: Destroys any current status and tries to import the raw token provided. :param jwt: a 'raw' JWT token. :param key: A (:class:`jwcrypto.jwk.JWK`) verification or decryption key, or a (:class:`jwcrypto.jwk.JWKSet`) that contains a key indexed by the 'kid' header. """
c = jwt.count('.') if c == 2: self.token = JWS() elif c == 4: self.token = JWE() else: raise ValueError("Token format unrecognized") # Apply algs restrictions if any, before performing any operation if self._algs: self.token.allowed_algs = self._algs self.deserializelog = list() # now deserialize and also decrypt/verify (or raise) if we # have a key if key is None: self.token.deserialize(jwt, None) elif isinstance(key, JWK): self.token.deserialize(jwt, key) self.deserializelog.append("Success") elif isinstance(key, JWKSet): self.token.deserialize(jwt, None) if 'kid' in self.token.jose_header: kid_key = key.get_key(self.token.jose_header['kid']) if not kid_key: raise JWTMissingKey('Key ID %s not in key set' % self.token.jose_header['kid']) self.token.deserialize(jwt, kid_key) else: for k in key: try: self.token.deserialize(jwt, k) self.deserializelog.append("Success") break except Exception as e: # pylint: disable=broad-except keyid = k.key_id if keyid is None: keyid = k.thumbprint() self.deserializelog.append('Key [%s] failed: [%s]' % ( keyid, repr(e))) continue if "Success" not in self.deserializelog: raise JWTMissingKey('No working key found in key set') else: raise ValueError("Unrecognized Key Type") if key is not None: self.header = self.token.jose_header self.claims = self.token.payload.decode('utf-8') self._check_provided_claims()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, n_viz=9): """Validate current model using validation dataset. Parameters n_viz: int Number fo visualization. Returns ------- log: dict Log values. """
iter_valid = copy.copy(self.iter_valid) losses, lbl_trues, lbl_preds = [], [], [] vizs = [] dataset = iter_valid.dataset desc = 'valid [iteration=%08d]' % self.iteration for batch in tqdm.tqdm(iter_valid, desc=desc, total=len(dataset), ncols=80, leave=False): img, lbl_true = zip(*batch) batch = map(datasets.transform_lsvrc2012_vgg16, batch) with chainer.no_backprop_mode(), \ chainer.using_config('train', False): in_vars = utils.batch_to_vars(batch, device=self.device) loss = self.model(*in_vars) losses.append(float(loss.data)) score = self.model.score lbl_pred = chainer.functions.argmax(score, axis=1) lbl_pred = chainer.cuda.to_cpu(lbl_pred.data) for im, lt, lp in zip(img, lbl_true, lbl_pred): lbl_trues.append(lt) lbl_preds.append(lp) if len(vizs) < n_viz: viz = utils.visualize_segmentation( lbl_pred=lp, lbl_true=lt, img=im, n_class=self.model.n_class) vizs.append(viz) # save visualization out_viz = osp.join(self.out, 'visualizations_valid', 'iter%08d.jpg' % self.iteration) if not osp.exists(osp.dirname(out_viz)): os.makedirs(osp.dirname(out_viz)) viz = utils.get_tile_image(vizs) skimage.io.imsave(out_viz, viz) # generate log acc = utils.label_accuracy_score( lbl_trues, lbl_preds, self.model.n_class) self._write_log(**{ 'epoch': self.epoch, 'iteration': self.iteration, 'elapsed_time': time.time() - self.stamp_start, 'valid/loss': np.mean(losses), 'valid/acc': acc[0], 'valid/acc_cls': acc[1], 'valid/mean_iu': acc[2], 'valid/fwavacc': acc[3], }) self._save_model()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def train(self): """Train the network using the training dataset. Parameters None Returns ------- None """
self.stamp_start = time.time() for iteration, batch in tqdm.tqdm(enumerate(self.iter_train), desc='train', total=self.max_iter, ncols=80): self.epoch = self.iter_train.epoch self.iteration = iteration ############ # validate # ############ if self.interval_validate and \ self.iteration % self.interval_validate == 0: self.validate() ######### # train # ######### batch = map(datasets.transform_lsvrc2012_vgg16, batch) in_vars = utils.batch_to_vars(batch, device=self.device) self.model.zerograds() loss = self.model(*in_vars) if loss is not None: loss.backward() self.optimizer.update() lbl_true = zip(*batch)[1] lbl_pred = chainer.functions.argmax(self.model.score, axis=1) lbl_pred = chainer.cuda.to_cpu(lbl_pred.data) acc = utils.label_accuracy_score( lbl_true, lbl_pred, self.model.n_class) self._write_log(**{ 'epoch': self.epoch, 'iteration': self.iteration, 'elapsed_time': time.time() - self.stamp_start, 'train/loss': float(loss.data), 'train/acc': acc[0], 'train/acc_cls': acc[1], 'train/mean_iu': acc[2], 'train/fwavacc': acc[3], }) if iteration >= self.max_iter: self._save_model() break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def centerize(src, dst_shape, margin_color=None): """Centerize image for specified image size @param src: image to centerize @param dst_shape: image shape (height, width) or (height, width, channel) """
if src.shape[:2] == dst_shape[:2]: return src centerized = np.zeros(dst_shape, dtype=src.dtype) if margin_color: centerized[:, :] = margin_color pad_vertical, pad_horizontal = 0, 0 h, w = src.shape[:2] dst_h, dst_w = dst_shape[:2] if h < dst_h: pad_vertical = (dst_h - h) // 2 if w < dst_w: pad_horizontal = (dst_w - w) // 2 centerized[pad_vertical:pad_vertical + h, pad_horizontal:pad_horizontal + w] = src return centerized
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tile_images(imgs, tile_shape, concatenated_image): """Concatenate images whose sizes are same. @param imgs: image list which should be concatenated @param tile_shape: shape for which images should be concatenated @param concatenated_image: returned image. if it is None, new image will be created. """
y_num, x_num = tile_shape one_width = imgs[0].shape[1] one_height = imgs[0].shape[0] if concatenated_image is None: if len(imgs[0].shape) == 3: n_channels = imgs[0].shape[2] assert all(im.shape[2] == n_channels for im in imgs) concatenated_image = np.zeros( (one_height * y_num, one_width * x_num, n_channels), dtype=np.uint8, ) else: concatenated_image = np.zeros( (one_height * y_num, one_width * x_num), dtype=np.uint8) for y in six.moves.range(y_num): for x in six.moves.range(x_num): i = x + y * x_num if i >= len(imgs): pass else: concatenated_image[y * one_height:(y + 1) * one_height, x * one_width:(x + 1) * one_width] = imgs[i] return concatenated_image
<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_tile_image(imgs, tile_shape=None, result_img=None, margin_color=None): """Concatenate images whose sizes are different. @param imgs: image list which should be concatenated @param tile_shape: shape for which images should be concatenated @param result_img: numpy array to put result image """
def resize(*args, **kwargs): # anti_aliasing arg cannot be passed to skimage<0.14 # use LooseVersion to allow 0.14dev. if LooseVersion(skimage.__version__) < LooseVersion('0.14'): kwargs.pop('anti_aliasing', None) return skimage.transform.resize(*args, **kwargs) def get_tile_shape(img_num): x_num = 0 y_num = int(math.sqrt(img_num)) while x_num * y_num < img_num: x_num += 1 return y_num, x_num if tile_shape is None: tile_shape = get_tile_shape(len(imgs)) # get max tile size to which each image should be resized max_height, max_width = np.inf, np.inf for img in imgs: max_height = min([max_height, img.shape[0]]) max_width = min([max_width, img.shape[1]]) # resize and concatenate images for i, img in enumerate(imgs): h, w = img.shape[:2] dtype = img.dtype h_scale, w_scale = max_height / h, max_width / w scale = min([h_scale, w_scale]) h, w = int(scale * h), int(scale * w) img = resize( image=img, output_shape=(h, w), mode='reflect', preserve_range=True, anti_aliasing=True, ).astype(dtype) if len(img.shape) == 3: img = centerize(img, (max_height, max_width, 3), margin_color) else: img = centerize(img, (max_height, max_width), margin_color) imgs[i] = img return _tile_images(imgs, tile_shape, result_img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visualize_segmentation(**kwargs): """Visualize segmentation. Parameters img: ndarray Input image to predict label. lbl_true: ndarray Ground truth of the label. lbl_pred: ndarray Label predicted. n_class: int Number of classes. label_names: dict or list Names of each label value. Key or index is label_value and value is its name. Returns ------- img_array: ndarray Visualized image. """
img = kwargs.pop('img', None) lbl_true = kwargs.pop('lbl_true', None) lbl_pred = kwargs.pop('lbl_pred', None) n_class = kwargs.pop('n_class', None) label_names = kwargs.pop('label_names', None) if kwargs: raise RuntimeError( 'Unexpected keys in kwargs: {}'.format(kwargs.keys())) if lbl_true is None and lbl_pred is None: raise ValueError('lbl_true or lbl_pred must be not None.') lbl_true = copy.deepcopy(lbl_true) lbl_pred = copy.deepcopy(lbl_pred) mask_unlabeled = None viz_unlabeled = None if lbl_true is not None: mask_unlabeled = lbl_true == -1 lbl_true[mask_unlabeled] = 0 viz_unlabeled = ( np.random.random((lbl_true.shape[0], lbl_true.shape[1], 3)) * 255 ).astype(np.uint8) if lbl_pred is not None: lbl_pred[mask_unlabeled] = 0 vizs = [] if lbl_true is not None: viz_trues = [ img, label2rgb(lbl_true, label_names=label_names, n_labels=n_class), label2rgb(lbl_true, img, label_names=label_names, n_labels=n_class), ] viz_trues[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled] viz_trues[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled] vizs.append(get_tile_image(viz_trues, (1, 3))) if lbl_pred is not None: viz_preds = [ img, label2rgb(lbl_pred, label_names=label_names, n_labels=n_class), label2rgb(lbl_pred, img, label_names=label_names, n_labels=n_class), ] if mask_unlabeled is not None and viz_unlabeled is not None: viz_preds[1][mask_unlabeled] = viz_unlabeled[mask_unlabeled] viz_preds[2][mask_unlabeled] = viz_unlabeled[mask_unlabeled] vizs.append(get_tile_image(viz_preds, (1, 3))) if len(vizs) == 1: return vizs[0] elif len(vizs) == 2: return get_tile_image(vizs, (2, 1)) else: raise RuntimeError
<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(self, output_path, dry_run=False, output_format=None, compresslevel=None): """ Create the archive at output_file_path. Type of the archive is determined either by extension of output_file_path or by output_format. Supported formats are: gz, zip, bz2, xz, tar, tgz, txz @param output_path: Output file path. @type output_path: str @param dry_run: Determines whether create should do nothing but print what it would archive. @type dry_run: bool @param output_format: Determines format of the output archive. If None, format is determined from extension of output_file_path. @type output_format: str """
if output_format is None: file_name, file_ext = path.splitext(output_path) output_format = file_ext[len(extsep):].lower() self.LOG.debug("Output format is not explicitly set, determined format is {0}.".format(output_format)) if not dry_run: if output_format in self.ZIPFILE_FORMATS: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED if compresslevel is not None: if sys.version_info > (3, 7): archive = ZipFile(path.abspath(output_path), 'w', compresslevel=compresslevel) else: raise ValueError("Compression level for zip archives requires Python 3.7+") else: archive = ZipFile(path.abspath(output_path), 'w') def add_file(file_path, arcname): if not path.islink(file_path): archive.write(file_path, arcname, ZIP_DEFLATED) else: i = ZipInfo(arcname) i.create_system = 3 i.external_attr = 0xA1ED0000 archive.writestr(i, readlink(file_path)) elif output_format in self.TARFILE_FORMATS: import tarfile mode = self.TARFILE_FORMATS[output_format] if compresslevel is not None: try: archive = tarfile.open(path.abspath(output_path), mode, compresslevel=compresslevel) except TypeError: raise ValueError("{0} cannot be compressed".format(output_format)) else: archive = tarfile.open(path.abspath(output_path), mode) def add_file(file_path, arcname): archive.add(file_path, arcname) else: raise ValueError("unknown format: {0}".format(output_format)) def archiver(file_path, arcname): self.LOG.debug("{0} => {1}".format(file_path, arcname)) add_file(file_path, arcname) else: archive = None def archiver(file_path, arcname): self.LOG.info("{0} => {1}".format(file_path, arcname)) self.archive_all_files(archiver) if archive is not None: archive.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 is_file_excluded(self, repo_abspath, repo_file_path): """ Checks whether file at a given path is excluded. @param repo_abspath: Absolute path to the git repository. @type repo_abspath: str @param repo_file_path: Path to a file relative to repo_abspath. @type repo_file_path: str @return: True if file should be excluded. Otherwise False. @rtype: bool """
next(self._check_attr_gens[repo_abspath]) attrs = self._check_attr_gens[repo_abspath].send(repo_file_path) return attrs['export-ignore'] == 'set'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def archive_all_files(self, archiver): """ Archive all files using archiver. @param archiver: Callable that accepts 2 arguments: abspath to file on the system and relative path within archive. @type archiver: Callable """
for file_path in self.extra: archiver(path.abspath(file_path), path.join(self.prefix, file_path)) for file_path in self.walk_git_files(): archiver(path.join(self.main_repo_abspath, file_path), path.join(self.prefix, file_path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk_git_files(self, repo_path=''): """ An iterator method that yields a file path relative to main_repo_abspath for each file that should be included in the archive. Skips those that match the exclusion patterns found in any discovered .gitattributes files along the way. Recurs into submodules as well. @param repo_path: Path to the git submodule repository relative to main_repo_abspath. @type repo_path: str @return: Iterator to traverse files under git control relative to main_repo_abspath. @rtype: Iterable """
repo_abspath = path.join(self.main_repo_abspath, repo_path) assert repo_abspath not in self._check_attr_gens self._check_attr_gens[repo_abspath] = self.check_attr(repo_abspath, ['export-ignore']) try: repo_file_paths = self.run_git_shell( 'git ls-files -z --cached --full-name --no-empty-directory', repo_abspath ).split('\0')[:-1] for repo_file_path in repo_file_paths: repo_file_abspath = path.join(repo_abspath, repo_file_path) # absolute file path main_repo_file_path = path.join(repo_path, repo_file_path) # relative to main_repo_abspath # Only list symlinks and files. if not path.islink(repo_file_abspath) and path.isdir(repo_file_abspath): continue if self.is_file_excluded(repo_abspath, repo_file_path): continue yield main_repo_file_path if self.force_sub: self.run_git_shell('git submodule init', repo_abspath) self.run_git_shell('git submodule update', repo_abspath) try: repo_gitmodules_abspath = path.join(repo_abspath, ".gitmodules") with open(repo_gitmodules_abspath) as f: lines = f.readlines() for l in lines: m = re.match("^\\s*path\\s*=\\s*(.*)\\s*$", l) if m: repo_submodule_path = m.group(1) # relative to repo_path main_repo_submodule_path = path.join(repo_path, repo_submodule_path) # relative to main_repo_abspath if self.is_file_excluded(repo_abspath, repo_submodule_path): continue for main_repo_submodule_file_path in self.walk_git_files(main_repo_submodule_path): repo_submodule_file_path = path.relpath(main_repo_submodule_file_path, repo_path) # relative to repo_path if self.is_file_excluded(repo_abspath, repo_submodule_file_path): continue yield main_repo_submodule_file_path except IOError: pass finally: self._check_attr_gens[repo_abspath].close() del self._check_attr_gens[repo_abspath]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_attr(self, repo_abspath, attrs): """ Generator that returns attributes for given paths relative to repo_abspath. @param repo_abspath: Absolute path to a git repository. @type repo_abspath: str @param attrs: Attributes to check. @type attrs: [str] @rtype: generator """
def make_process(): env = dict(environ, GIT_FLUSH='1') cmd = 'git check-attr --stdin -z {0}'.format(' '.join(attrs)) return Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, cwd=repo_abspath, env=env) def read_attrs(process, repo_file_path): process.stdin.write(repo_file_path.encode('utf-8') + b'\0') process.stdin.flush() # For every attribute check-attr will output: <path> NUL <attribute> NUL <info> NUL path, attr, info = b'', b'', b'' nuls_count = 0 nuls_expected = 3 * len(attrs) while nuls_count != nuls_expected: b = process.stdout.read(1) if b == b'' and process.poll() is not None: raise RuntimeError("check-attr exited prematurely") elif b == b'\0': nuls_count += 1 if nuls_count % 3 == 0: yield map(self.decode_git_output, (path, attr, info)) path, attr, info = b'', b'', b'' elif nuls_count % 3 == 0: path += b elif nuls_count % 3 == 1: attr += b elif nuls_count % 3 == 2: info += b def read_attrs_old(process, repo_file_path): """ Compatibility with versions 1.8.5 and below that do not recognize -z for output. """ process.stdin.write(repo_file_path.encode('utf-8') + b'\0') process.stdin.flush() # For every attribute check-attr will output: <path>: <attribute>: <info>\n # where <path> is c-quoted path, attr, info = b'', b'', b'' lines_count = 0 lines_expected = len(attrs) while lines_count != lines_expected: line = process.stdout.readline() info_start = line.rfind(b': ') if info_start == -1: raise RuntimeError("unexpected output of check-attr: {0}".format(line)) attr_start = line.rfind(b': ', 0, info_start) if attr_start == -1: raise RuntimeError("unexpected output of check-attr: {0}".format(line)) info = line[info_start + 2:len(line) - 1] # trim leading ": " and trailing \n attr = line[attr_start + 2:info_start] # trim leading ": " path = line[:attr_start] yield map(self.decode_git_output, (path, attr, info)) lines_count += 1 if not attrs: return process = make_process() try: while True: repo_file_path = yield repo_file_attrs = {} if self.git_version is None or self.git_version > (1, 8, 5): reader = read_attrs else: reader = read_attrs_old for path, attr, value in reader(process, repo_file_path): repo_file_attrs[attr] = value yield repo_file_attrs finally: process.stdin.close() process.wait()
<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_git_shell(cls, cmd, cwd=None): """ Runs git shell command, reads output and decodes it into unicode string. @param cmd: Command to be executed. @type cmd: str @type cwd: str @param cwd: Working directory. @rtype: str @return: Output of the command. @raise CalledProcessError: Raises exception if return code of the command is non-zero. """
p = Popen(cmd, shell=True, stdout=PIPE, cwd=cwd) output, _ = p.communicate() output = cls.decode_git_output(output) if p.returncode: if sys.version_info > (2, 6): raise CalledProcessError(returncode=p.returncode, cmd=cmd, output=output) else: raise CalledProcessError(returncode=p.returncode, cmd=cmd) return output
<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_git_version(cls): """ Return version of git current shell points to. If version cannot be parsed None is returned. @rtype: tuple or None """
try: output = cls.run_git_shell('git version') except CalledProcessError: cls.LOG.warning("Unable to get Git version.") return None try: version = output.split()[2] except IndexError: cls.LOG.warning("Unable to parse Git version \"%s\".", output) return None try: return tuple(int(v) for v in version.split('.')) except ValueError: cls.LOG.warning("Unable to parse Git version \"%s\".", version) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def request(method, uri, **kwargs): '''Base function for one time http requests. Args: method (str): The http method to use. For example 'GET' uri (str): The url of the resource. Example: 'https://example.com/stuff' kwargs: Any number of arguments supported, found here: http://asks.rtfd.io/en/latest/overview-of-funcs-and-args.html Returns: Response (asks.Response): The Response object. ''' c_interact = kwargs.pop('persist_cookies', None) ssl_context = kwargs.pop('ssl_context', None) async with Session(persist_cookies=c_interact, ssl_context=ssl_context) as s: r = await s.request(method, url=uri, **kwargs) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def make_request(self, redirect=False): ''' Acts as the central hub for preparing requests to be sent, and returning them upon completion. Generally just pokes through self's attribs and makes decisions about what to do. Returns: sock: The socket to be returned to the calling session's pool. Response: The response object, after any redirects. If there were redirects, the redirect responses will be stored in the final response object's `.history`. ''' h11_connection = h11.Connection(our_role=h11.CLIENT) (self.scheme, self.host, self.path, self.uri_parameters, self.query, _) = urlparse(self.uri) if not redirect: self.initial_scheme = self.scheme self.initial_netloc = self.host # leave default the host on 80 / 443 # otherwise use the base host with :port appended. host = (self.host if (self.port == '80' or self.port == '443') else self.host.split(':')[0] + ':' + self.port) # default header construction asks_headers = c_i_dict([('Host', host), ('Connection', 'keep-alive'), ('Accept-Encoding', 'gzip, deflate'), ('Accept', '*/*'), ('Content-Length', '0'), ('User-Agent', 'python-asks/2.2.2') ]) # check for a CookieTracker object, and if it's there inject # the relevant cookies in to the (next) request. # What the fuck is this shit. if self.persist_cookies is not None: self.cookies.update( self.persist_cookies.get_additional_cookies( self.host, self.path)) # formulate path / query and intended extra querys for use in uri self._build_path() # handle building the request body, if any body = '' if any((self.data, self.files, self.json is not None)): content_type, content_len, body = await self._formulate_body() asks_headers['Content-Type'] = content_type asks_headers['Content-Length'] = content_len # add custom headers, if any # note that custom headers take precedence if self.headers is not None: asks_headers.update(self.headers) # add auth if self.auth is not None: asks_headers.update(await self._auth_handler_pre()) asks_headers.update(await self._auth_handler_post_get_auth()) # add cookies if self.cookies: cookie_str = '' for k, v in self.cookies.items(): cookie_str += '{}={}; '.format(k, v) asks_headers['Cookie'] = cookie_str[:-1] # Construct h11 body object, if any body. if body: if not isinstance(body, bytes): body = bytes(body, self.encoding) asks_headers['Content-Length'] = str(len(body)) req_body = h11.Data(data=body) else: req_body = None # Construct h11 request object. req = h11.Request(method=self.method, target=self.path, headers=asks_headers.items()) # call i/o handling func response_obj = await self._request_io(req, req_body, h11_connection) # check to see if the final socket object is suitable to be returned # to the calling session's connection pool. # We don't want to return sockets that are of a difference schema or # different top level domain, as they are less likely to be useful. if redirect: if not (self.scheme == self.initial_scheme and self.host == self.initial_netloc): self.sock._active = False if self.streaming: return None, response_obj return self.sock, response_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 _build_path(self): ''' Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server. ''' if not self.path: self.path = '/' if self.uri_parameters: self.path = self.path + ';' + requote_uri(self.uri_parameters) if self.query: self.path = (self.path + '?' + self.query) if self.params: try: if self.query: self.path = self.path + self._dict_to_query( self.params, base_query=True) else: self.path = self.path + self._dict_to_query(self.params) except AttributeError: self.path = self.path + '?' + self.params self.path = requote_uri(self.path) self.req_url = urlunparse( (self.scheme, self.host, (self.path or ''), '', '', ''))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def _catch_response(self, h11_connection): ''' Instantiates the parser which manages incoming data, first getting the headers, storing cookies, and then parsing the response's body, if any. This function also instances the Response class in which the response status line, headers, cookies, and body is stored. It should be noted that in order to remain preformant, if the user wishes to do any file IO it should use async files or risk long wait times and risk connection issues server-side when using callbacks. If a callback is used, the response's body will be None. Returns: The most recent response object. ''' response = await self._recv_event(h11_connection) resp_data = {'encoding': self.encoding, 'method': self.method, 'status_code': response.status_code, 'reason_phrase': str(response.reason, 'utf-8'), 'http_version': str(response.http_version, 'utf-8'), 'headers': c_i_dict( [(str(name, 'utf-8'), str(value, 'utf-8')) for name, value in response.headers]), 'body': b'', 'url': self.req_url } for header in response.headers: if header[0] == b'set-cookie': try: resp_data['headers']['set-cookie'].append(str(header[1], 'utf-8')) except (KeyError, AttributeError): resp_data['headers']['set-cookie'] = [str(header[1], 'utf-8')] # check whether we should receive body according to RFC 7230 # https://tools.ietf.org/html/rfc7230#section-3.3.3 get_body = False try: if int(resp_data['headers']['content-length']) > 0: get_body = True except KeyError: try: if 'chunked' in resp_data['headers']['transfer-encoding'].lower(): get_body = True except KeyError: if resp_data['headers'].get('connection', '').lower() == 'close': get_body = True if get_body: if self.callback is not None: endof = await self._body_callback(h11_connection) elif self.stream: if not ((self.scheme == self.initial_scheme and self.host == self.initial_netloc) or resp_data['headers']['connection'].lower() == 'close'): self.sock._active = False resp_data['body'] = StreamBody( h11_connection, self.sock, resp_data['headers'].get('content-encoding', None), resp_data['encoding']) self.streaming = True else: while True: data = await self._recv_event(h11_connection) if isinstance(data, h11.Data): resp_data['body'] += data.data elif isinstance(data, h11.EndOfMessage): break else: endof = await self._recv_event(h11_connection) assert isinstance(endof, h11.EndOfMessage) if self.streaming: return StreamResponse(**resp_data) return Response(**resp_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def _send(self, request_bytes, body_bytes, h11_connection): ''' Takes a package and body, combines then, then shoots 'em off in to the ether. Args: package (list of str): The header package. body (str): The str representation of the body. ''' await self.sock.send_all(h11_connection.send(request_bytes)) if body_bytes is not None: await self.sock.send_all(h11_connection.send(body_bytes)) await self.sock.send_all(h11_connection.send(h11.EndOfMessage()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def _location_auth_protect(self, location): ''' Checks to see if the new location is 1. The same top level domain 2. As or more secure than the current connection type Returns: True (bool): If the current top level domain is the same and the connection type is equally or more secure. False otherwise. ''' netloc_sans_port = self.host.split(':')[0] netloc_sans_port = netloc_sans_port.replace( (re.match(_WWX_MATCH, netloc_sans_port)[0]), '') base_domain = '.'.join(netloc_sans_port.split('.')[-2:]) l_scheme, l_netloc, _, _, _, _ = urlparse(location) location_sans_port = l_netloc.split(':')[0] location_sans_port = location_sans_port.replace( (re.match(_WWX_MATCH, location_sans_port)[0]), '') location_domain = '.'.join(location_sans_port.split('.')[-2:]) if base_domain == location_domain: if l_scheme < self.scheme: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def _body_callback(self, h11_connection): ''' A callback func to be supplied if the user wants to do something directly with the response body's stream. ''' # pylint: disable=not-callable while True: next_event = await self._recv_event(h11_connection) if isinstance(next_event, h11.Data): await self.callback(next_event.data) else: return next_event
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def _connect(self, host_loc): ''' Simple enough stuff to figure out where we should connect, and creates the appropriate connection. ''' scheme, host, path, parameters, query, fragment = urlparse( host_loc) if parameters or query or fragment: raise ValueError('Supplied info beyond scheme, host.' + ' Host should be top level only: ', path) host, port = get_netloc_port(scheme, host) if scheme == 'http': return await self._open_connection_http( (host, int(port))), port else: return await self._open_connection_https( (host, int(port))), port
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def request(self, method, url=None, *, path='', retries=1, connection_timeout=60, **kwargs): ''' This is the template for all of the `http method` methods for the Session. Args: method (str): A http method, such as 'GET' or 'POST'. url (str): The url the request should be made to. path (str): An optional kw-arg for use in Session method calls, for specifying a particular path. Usually to be used in conjunction with the base_location/endpoint paradigm. kwargs: Any number of the following: data (dict or str): Info to be processed as a body-bound query. params (dict or str): Info to be processed as a url-bound query. headers (dict): User HTTP headers to be used in the request. encoding (str): The str representation of the codec to process the request under. json (dict): A dict to be formatted as json and sent in the request body. files (dict): A dict of `filename:filepath`s to be sent as multipart. cookies (dict): A dict of `name:value` cookies to be passed in request. callback (func): A callback function to be called on each bytechunk of of the response body. timeout (int or float): A numeric representation of the longest time to wait on a complete response once a request has been sent. retries (int): The number of attempts to try against connection errors. max_redirects (int): The maximum number of redirects allowed. persist_cookies (True or None): Passing True instantiates a CookieTracker object to manage the return of cookies to the server under the relevant domains. auth (child of AuthBase): An object for handling auth construction. When you call something like Session.get() or asks.post(), you're really calling a partial method that has the 'method' argument pre-completed. ''' timeout = kwargs.get('timeout', None) req_headers = kwargs.pop('headers', None) if self.headers is not None: headers = copy(self.headers) if req_headers is not None: headers.update(req_headers) req_headers = headers async with self.sema: if url is None: url = self._make_url() + path retry = False sock = None try: sock = await timeout_manager( connection_timeout, self._grab_connection, url) port = sock.port req_obj = RequestProcessor( self, method, url, port, headers=req_headers, encoding=self.encoding, sock=sock, persist_cookies=self._cookie_tracker, **kwargs ) try: if timeout is None: sock, r = await req_obj.make_request() else: sock, r = await timeout_manager(timeout, req_obj.make_request) except BadHttpResponse: if timeout is None: sock, r = await req_obj.make_request() else: sock, r = await timeout_manager(timeout, req_obj.make_request) if sock is not None: try: if r.headers['connection'].lower() == 'close': sock._active = False await sock.close() except KeyError: pass await self.return_to_pool(sock) # ConnectionErrors are special. They are the only kind of exception # we ever want to suppress. All other exceptions are re-raised or # raised through another exception. except ConnectionError as e: if retries > 0: retry = True retries -= 1 else: raise e except Exception as e: if sock: await self._handle_exception(e, sock) raise # any BaseException is considered unlawful murder, and # Session.cleanup should be called to tidy up sockets. except BaseException as e: if sock: await sock.close() raise e if retry: return (await self.request(method, url, path=path, retries=retries, headers=headers, **kwargs)) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _handle_exception(self, e, sock): """ Given an exception, we want to handle it appropriately. Some exceptions we prefer to shadow with an asks exception, and some we want to raise directly. In all cases we clean up the underlying socket. """
if isinstance(e, (RemoteProtocolError, AssertionError)): await sock.close() raise BadHttpResponse('Invalid HTTP response from server.') from e if isinstance(e, Exception): await sock.close() raise e