id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
17,400
uber/rides-python-sdk
example/authorize_driver.py
authorization_code_grant_flow
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials. """ auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login as a driver and grant access by going to:\n\n{}\n' login_message = login_message.format(auth_url) response_print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here:\n\n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState) as error: fail_print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'redirect_url': credential.redirect_url, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(storage_filename, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return UberRidesClient(session, sandbox_mode=True)
python
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials. """ auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login as a driver and grant access by going to:\n\n{}\n' login_message = login_message.format(auth_url) response_print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here:\n\n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, UberIllegalState) as error: fail_print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'redirect_url': credential.redirect_url, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(storage_filename, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return UberRidesClient(session, sandbox_mode=True)
[ "def", "authorization_code_grant_flow", "(", "credentials", ",", "storage_filename", ")", ":", "auth_flow", "=", "AuthorizationCodeGrant", "(", "credentials", ".", "get", "(", "'client_id'", ")", ",", "credentials", ".", "get", "(", "'scopes'", ")", ",", "credentials", ".", "get", "(", "'client_secret'", ")", ",", "credentials", ".", "get", "(", "'redirect_url'", ")", ",", ")", "auth_url", "=", "auth_flow", ".", "get_authorization_url", "(", ")", "login_message", "=", "'Login as a driver and grant access by going to:\\n\\n{}\\n'", "login_message", "=", "login_message", ".", "format", "(", "auth_url", ")", "response_print", "(", "login_message", ")", "redirect_url", "=", "'Copy the URL you are redirected to and paste here:\\n\\n'", "result", "=", "input", "(", "redirect_url", ")", ".", "strip", "(", ")", "try", ":", "session", "=", "auth_flow", ".", "get_session", "(", "result", ")", "except", "(", "ClientError", ",", "UberIllegalState", ")", "as", "error", ":", "fail_print", "(", "error", ")", "return", "credential", "=", "session", ".", "oauth2credential", "credential_data", "=", "{", "'client_id'", ":", "credential", ".", "client_id", ",", "'redirect_url'", ":", "credential", ".", "redirect_url", ",", "'access_token'", ":", "credential", ".", "access_token", ",", "'expires_in_seconds'", ":", "credential", ".", "expires_in_seconds", ",", "'scopes'", ":", "list", "(", "credential", ".", "scopes", ")", ",", "'grant_type'", ":", "credential", ".", "grant_type", ",", "'client_secret'", ":", "credential", ".", "client_secret", ",", "'refresh_token'", ":", "credential", ".", "refresh_token", ",", "}", "with", "open", "(", "storage_filename", ",", "'w'", ")", "as", "yaml_file", ":", "yaml_file", ".", "write", "(", "safe_dump", "(", "credential_data", ",", "default_flow_style", "=", "False", ")", ")", "return", "UberRidesClient", "(", "session", ",", "sandbox_mode", "=", "True", ")" ]
Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (UberRidesClient) An UberRidesClient with OAuth 2.0 Credentials.
[ "Get", "an", "access", "token", "through", "Authorization", "Code", "Grant", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/authorize_driver.py#L58-L110
17,401
uber/rides-python-sdk
uber_rides/auth.py
_request_access_token
def _request_access_token( grant_type, client_id=None, client_secret=None, scopes=None, code=None, redirect_url=None, refresh_token=None ): """Make an HTTP POST to request an access token. Parameters grant_type (str) Either 'client_credientials' (Client Credentials Grant) or 'authorization_code' (Authorization Code Grant). client_id (str) Your app's Client ID. client_secret (str) Your app's Client Secret. scopes (set) Set of permission scopes to request. (e.g. {'profile', 'history'}) code (str) The authorization code to switch for an access token. Only used in Authorization Code Grant. redirect_url (str) The URL that the Uber server will redirect to. refresh_token (str) Refresh token used to get a new access token. Only used for Authorization Code Grant. Returns (requests.Response) Successful HTTP response from a 'POST' to request an access token. Raises ClientError (APIError) Thrown if there was an HTTP error. """ url = build_url(auth.AUTH_HOST, auth.ACCESS_TOKEN_PATH) if isinstance(scopes, set): scopes = ' '.join(scopes) args = { 'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'scope': scopes, 'code': code, 'redirect_uri': redirect_url, 'refresh_token': refresh_token, } response = post(url=url, data=args) if response.status_code == codes.ok: return response message = 'Failed to request access token: {}.' message = message.format(response.reason) raise ClientError(response, message)
python
def _request_access_token( grant_type, client_id=None, client_secret=None, scopes=None, code=None, redirect_url=None, refresh_token=None ): """Make an HTTP POST to request an access token. Parameters grant_type (str) Either 'client_credientials' (Client Credentials Grant) or 'authorization_code' (Authorization Code Grant). client_id (str) Your app's Client ID. client_secret (str) Your app's Client Secret. scopes (set) Set of permission scopes to request. (e.g. {'profile', 'history'}) code (str) The authorization code to switch for an access token. Only used in Authorization Code Grant. redirect_url (str) The URL that the Uber server will redirect to. refresh_token (str) Refresh token used to get a new access token. Only used for Authorization Code Grant. Returns (requests.Response) Successful HTTP response from a 'POST' to request an access token. Raises ClientError (APIError) Thrown if there was an HTTP error. """ url = build_url(auth.AUTH_HOST, auth.ACCESS_TOKEN_PATH) if isinstance(scopes, set): scopes = ' '.join(scopes) args = { 'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'scope': scopes, 'code': code, 'redirect_uri': redirect_url, 'refresh_token': refresh_token, } response = post(url=url, data=args) if response.status_code == codes.ok: return response message = 'Failed to request access token: {}.' message = message.format(response.reason) raise ClientError(response, message)
[ "def", "_request_access_token", "(", "grant_type", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "scopes", "=", "None", ",", "code", "=", "None", ",", "redirect_url", "=", "None", ",", "refresh_token", "=", "None", ")", ":", "url", "=", "build_url", "(", "auth", ".", "AUTH_HOST", ",", "auth", ".", "ACCESS_TOKEN_PATH", ")", "if", "isinstance", "(", "scopes", ",", "set", ")", ":", "scopes", "=", "' '", ".", "join", "(", "scopes", ")", "args", "=", "{", "'grant_type'", ":", "grant_type", ",", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "client_secret", ",", "'scope'", ":", "scopes", ",", "'code'", ":", "code", ",", "'redirect_uri'", ":", "redirect_url", ",", "'refresh_token'", ":", "refresh_token", ",", "}", "response", "=", "post", "(", "url", "=", "url", ",", "data", "=", "args", ")", "if", "response", ".", "status_code", "==", "codes", ".", "ok", ":", "return", "response", "message", "=", "'Failed to request access token: {}.'", "message", "=", "message", ".", "format", "(", "response", ".", "reason", ")", "raise", "ClientError", "(", "response", ",", "message", ")" ]
Make an HTTP POST to request an access token. Parameters grant_type (str) Either 'client_credientials' (Client Credentials Grant) or 'authorization_code' (Authorization Code Grant). client_id (str) Your app's Client ID. client_secret (str) Your app's Client Secret. scopes (set) Set of permission scopes to request. (e.g. {'profile', 'history'}) code (str) The authorization code to switch for an access token. Only used in Authorization Code Grant. redirect_url (str) The URL that the Uber server will redirect to. refresh_token (str) Refresh token used to get a new access token. Only used for Authorization Code Grant. Returns (requests.Response) Successful HTTP response from a 'POST' to request an access token. Raises ClientError (APIError) Thrown if there was an HTTP error.
[ "Make", "an", "HTTP", "POST", "to", "request", "an", "access", "token", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L447-L509
17,402
uber/rides-python-sdk
uber_rides/auth.py
refresh_access_token
def refresh_access_token(credential): """Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Session object with refreshed OAuth 2.0 credentials. Raises UberIllegalState (APIError) Raised if OAuth 2.0 grant type does not support refresh tokens. """ if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT: response = _request_access_token( grant_type=auth.REFRESH_TOKEN, client_id=credential.client_id, client_secret=credential.client_secret, redirect_url=credential.redirect_url, refresh_token=credential.refresh_token, ) oauth2credential = OAuth2Credential.make_from_response( response=response, grant_type=credential.grant_type, client_id=credential.client_id, client_secret=credential.client_secret, redirect_url=credential.redirect_url, ) return Session(oauth2credential=oauth2credential) elif credential.grant_type == auth.CLIENT_CREDENTIALS_GRANT: response = _request_access_token( grant_type=auth.CLIENT_CREDENTIALS_GRANT, client_id=credential.client_id, client_secret=credential.client_secret, scopes=credential.scopes, ) oauth2credential = OAuth2Credential.make_from_response( response=response, grant_type=credential.grant_type, client_id=credential.client_id, client_secret=credential.client_secret, ) return Session(oauth2credential=oauth2credential) message = '{} Grant Type does not support Refresh Tokens.' message = message.format(credential.grant_type) raise UberIllegalState(message)
python
def refresh_access_token(credential): """Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Session object with refreshed OAuth 2.0 credentials. Raises UberIllegalState (APIError) Raised if OAuth 2.0 grant type does not support refresh tokens. """ if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT: response = _request_access_token( grant_type=auth.REFRESH_TOKEN, client_id=credential.client_id, client_secret=credential.client_secret, redirect_url=credential.redirect_url, refresh_token=credential.refresh_token, ) oauth2credential = OAuth2Credential.make_from_response( response=response, grant_type=credential.grant_type, client_id=credential.client_id, client_secret=credential.client_secret, redirect_url=credential.redirect_url, ) return Session(oauth2credential=oauth2credential) elif credential.grant_type == auth.CLIENT_CREDENTIALS_GRANT: response = _request_access_token( grant_type=auth.CLIENT_CREDENTIALS_GRANT, client_id=credential.client_id, client_secret=credential.client_secret, scopes=credential.scopes, ) oauth2credential = OAuth2Credential.make_from_response( response=response, grant_type=credential.grant_type, client_id=credential.client_id, client_secret=credential.client_secret, ) return Session(oauth2credential=oauth2credential) message = '{} Grant Type does not support Refresh Tokens.' message = message.format(credential.grant_type) raise UberIllegalState(message)
[ "def", "refresh_access_token", "(", "credential", ")", ":", "if", "credential", ".", "grant_type", "==", "auth", ".", "AUTHORIZATION_CODE_GRANT", ":", "response", "=", "_request_access_token", "(", "grant_type", "=", "auth", ".", "REFRESH_TOKEN", ",", "client_id", "=", "credential", ".", "client_id", ",", "client_secret", "=", "credential", ".", "client_secret", ",", "redirect_url", "=", "credential", ".", "redirect_url", ",", "refresh_token", "=", "credential", ".", "refresh_token", ",", ")", "oauth2credential", "=", "OAuth2Credential", ".", "make_from_response", "(", "response", "=", "response", ",", "grant_type", "=", "credential", ".", "grant_type", ",", "client_id", "=", "credential", ".", "client_id", ",", "client_secret", "=", "credential", ".", "client_secret", ",", "redirect_url", "=", "credential", ".", "redirect_url", ",", ")", "return", "Session", "(", "oauth2credential", "=", "oauth2credential", ")", "elif", "credential", ".", "grant_type", "==", "auth", ".", "CLIENT_CREDENTIALS_GRANT", ":", "response", "=", "_request_access_token", "(", "grant_type", "=", "auth", ".", "CLIENT_CREDENTIALS_GRANT", ",", "client_id", "=", "credential", ".", "client_id", ",", "client_secret", "=", "credential", ".", "client_secret", ",", "scopes", "=", "credential", ".", "scopes", ",", ")", "oauth2credential", "=", "OAuth2Credential", ".", "make_from_response", "(", "response", "=", "response", ",", "grant_type", "=", "credential", ".", "grant_type", ",", "client_id", "=", "credential", ".", "client_id", ",", "client_secret", "=", "credential", ".", "client_secret", ",", ")", "return", "Session", "(", "oauth2credential", "=", "oauth2credential", ")", "message", "=", "'{} Grant Type does not support Refresh Tokens.'", "message", "=", "message", ".", "format", "(", "credential", ".", "grant_type", ")", "raise", "UberIllegalState", "(", "message", ")" ]
Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Session object with refreshed OAuth 2.0 credentials. Raises UberIllegalState (APIError) Raised if OAuth 2.0 grant type does not support refresh tokens.
[ "Use", "a", "refresh", "token", "to", "request", "a", "new", "access", "token", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L512-L568
17,403
uber/rides-python-sdk
uber_rides/auth.py
OAuth2._build_authorization_request_url
def _build_authorization_request_url( self, response_type, redirect_url, state=None ): """Form URL to request an auth code or access token. Parameters response_type (str) Either 'code' (Authorization Code Grant) or 'token' (Implicit Grant) redirect_url (str) The URL that the Uber server will redirect the user to after finishing authorization. The redirect must be HTTPS-based and match the URL you registered your application with. Localhost URLs are permitted and can be either HTTP or HTTPS. state (str) Optional CSRF State token to send to server. Returns (str) The fully constructed authorization request URL. Raises UberIllegalState (ApiError) Raised if response_type parameter is invalid. """ if response_type not in auth.VALID_RESPONSE_TYPES: message = '{} is not a valid response type.' raise UberIllegalState(message.format(response_type)) args = OrderedDict([ ('scope', ' '.join(self.scopes)), ('state', state), ('redirect_uri', redirect_url), ('response_type', response_type), ('client_id', self.client_id), ]) return build_url(auth.AUTH_HOST, auth.AUTHORIZE_PATH, args)
python
def _build_authorization_request_url( self, response_type, redirect_url, state=None ): """Form URL to request an auth code or access token. Parameters response_type (str) Either 'code' (Authorization Code Grant) or 'token' (Implicit Grant) redirect_url (str) The URL that the Uber server will redirect the user to after finishing authorization. The redirect must be HTTPS-based and match the URL you registered your application with. Localhost URLs are permitted and can be either HTTP or HTTPS. state (str) Optional CSRF State token to send to server. Returns (str) The fully constructed authorization request URL. Raises UberIllegalState (ApiError) Raised if response_type parameter is invalid. """ if response_type not in auth.VALID_RESPONSE_TYPES: message = '{} is not a valid response type.' raise UberIllegalState(message.format(response_type)) args = OrderedDict([ ('scope', ' '.join(self.scopes)), ('state', state), ('redirect_uri', redirect_url), ('response_type', response_type), ('client_id', self.client_id), ]) return build_url(auth.AUTH_HOST, auth.AUTHORIZE_PATH, args)
[ "def", "_build_authorization_request_url", "(", "self", ",", "response_type", ",", "redirect_url", ",", "state", "=", "None", ")", ":", "if", "response_type", "not", "in", "auth", ".", "VALID_RESPONSE_TYPES", ":", "message", "=", "'{} is not a valid response type.'", "raise", "UberIllegalState", "(", "message", ".", "format", "(", "response_type", ")", ")", "args", "=", "OrderedDict", "(", "[", "(", "'scope'", ",", "' '", ".", "join", "(", "self", ".", "scopes", ")", ")", ",", "(", "'state'", ",", "state", ")", ",", "(", "'redirect_uri'", ",", "redirect_url", ")", ",", "(", "'response_type'", ",", "response_type", ")", ",", "(", "'client_id'", ",", "self", ".", "client_id", ")", ",", "]", ")", "return", "build_url", "(", "auth", ".", "AUTH_HOST", ",", "auth", ".", "AUTHORIZE_PATH", ",", "args", ")" ]
Form URL to request an auth code or access token. Parameters response_type (str) Either 'code' (Authorization Code Grant) or 'token' (Implicit Grant) redirect_url (str) The URL that the Uber server will redirect the user to after finishing authorization. The redirect must be HTTPS-based and match the URL you registered your application with. Localhost URLs are permitted and can be either HTTP or HTTPS. state (str) Optional CSRF State token to send to server. Returns (str) The fully constructed authorization request URL. Raises UberIllegalState (ApiError) Raised if response_type parameter is invalid.
[ "Form", "URL", "to", "request", "an", "auth", "code", "or", "access", "token", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L78-L118
17,404
uber/rides-python-sdk
uber_rides/auth.py
OAuth2._extract_query
def _extract_query(self, redirect_url): """Extract query parameters from a url. Parameters redirect_url (str) The full URL that the Uber server redirected to after the user authorized your app. Returns (dict) A dictionary of query parameters. """ qs = urlparse(redirect_url) # Implicit Grant redirect_urls have data after fragment identifier (#) # All other redirect_urls return data after query identifier (?) qs = qs.fragment if isinstance(self, ImplicitGrant) else qs.query query_params = parse_qs(qs) query_params = {qp: query_params[qp][0] for qp in query_params} return query_params
python
def _extract_query(self, redirect_url): """Extract query parameters from a url. Parameters redirect_url (str) The full URL that the Uber server redirected to after the user authorized your app. Returns (dict) A dictionary of query parameters. """ qs = urlparse(redirect_url) # Implicit Grant redirect_urls have data after fragment identifier (#) # All other redirect_urls return data after query identifier (?) qs = qs.fragment if isinstance(self, ImplicitGrant) else qs.query query_params = parse_qs(qs) query_params = {qp: query_params[qp][0] for qp in query_params} return query_params
[ "def", "_extract_query", "(", "self", ",", "redirect_url", ")", ":", "qs", "=", "urlparse", "(", "redirect_url", ")", "# Implicit Grant redirect_urls have data after fragment identifier (#)", "# All other redirect_urls return data after query identifier (?)", "qs", "=", "qs", ".", "fragment", "if", "isinstance", "(", "self", ",", "ImplicitGrant", ")", "else", "qs", ".", "query", "query_params", "=", "parse_qs", "(", "qs", ")", "query_params", "=", "{", "qp", ":", "query_params", "[", "qp", "]", "[", "0", "]", "for", "qp", "in", "query_params", "}", "return", "query_params" ]
Extract query parameters from a url. Parameters redirect_url (str) The full URL that the Uber server redirected to after the user authorized your app. Returns (dict) A dictionary of query parameters.
[ "Extract", "query", "parameters", "from", "a", "url", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L120-L141
17,405
uber/rides-python-sdk
uber_rides/auth.py
AuthorizationCodeGrant._generate_state_token
def _generate_state_token(self, length=32): """Generate CSRF State Token. CSRF State Tokens are passed as a parameter in the authorization URL and are checked when receiving responses from the Uber Auth server to prevent request forgery. """ choices = ascii_letters + digits return ''.join(SystemRandom().choice(choices) for _ in range(length))
python
def _generate_state_token(self, length=32): """Generate CSRF State Token. CSRF State Tokens are passed as a parameter in the authorization URL and are checked when receiving responses from the Uber Auth server to prevent request forgery. """ choices = ascii_letters + digits return ''.join(SystemRandom().choice(choices) for _ in range(length))
[ "def", "_generate_state_token", "(", "self", ",", "length", "=", "32", ")", ":", "choices", "=", "ascii_letters", "+", "digits", "return", "''", ".", "join", "(", "SystemRandom", "(", ")", ".", "choice", "(", "choices", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
Generate CSRF State Token. CSRF State Tokens are passed as a parameter in the authorization URL and are checked when receiving responses from the Uber Auth server to prevent request forgery.
[ "Generate", "CSRF", "State", "Token", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L194-L202
17,406
uber/rides-python-sdk
uber_rides/auth.py
AuthorizationCodeGrant.get_authorization_url
def get_authorization_url(self): """Start the Authorization Code Grant process. This function starts the OAuth 2.0 authorization process and builds an authorization URL. You should redirect your user to this URL, where they can grant your application access to their Uber account. Returns (str) The fully constructed authorization request URL. Tell the user to visit this URL and approve your app. """ return self._build_authorization_request_url( response_type=auth.CODE_RESPONSE_TYPE, redirect_url=self.redirect_url, state=self.state_token, )
python
def get_authorization_url(self): """Start the Authorization Code Grant process. This function starts the OAuth 2.0 authorization process and builds an authorization URL. You should redirect your user to this URL, where they can grant your application access to their Uber account. Returns (str) The fully constructed authorization request URL. Tell the user to visit this URL and approve your app. """ return self._build_authorization_request_url( response_type=auth.CODE_RESPONSE_TYPE, redirect_url=self.redirect_url, state=self.state_token, )
[ "def", "get_authorization_url", "(", "self", ")", ":", "return", "self", ".", "_build_authorization_request_url", "(", "response_type", "=", "auth", ".", "CODE_RESPONSE_TYPE", ",", "redirect_url", "=", "self", ".", "redirect_url", ",", "state", "=", "self", ".", "state_token", ",", ")" ]
Start the Authorization Code Grant process. This function starts the OAuth 2.0 authorization process and builds an authorization URL. You should redirect your user to this URL, where they can grant your application access to their Uber account. Returns (str) The fully constructed authorization request URL. Tell the user to visit this URL and approve your app.
[ "Start", "the", "Authorization", "Code", "Grant", "process", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L204-L220
17,407
uber/rides-python-sdk
uber_rides/auth.py
AuthorizationCodeGrant._verify_query
def _verify_query(self, query_params): """Verify response from the Uber Auth server. Parameters query_params (dict) Dictionary of query parameters attached to your redirect URL after user approved your app and was redirected. Returns authorization_code (str) Code received when user grants your app access. Use this code to request an access token. Raises UberIllegalState (ApiError) Thrown if the redirect URL was missing parameters or if the given parameters were not valid. """ error_message = None if self.state_token is not False: # Check CSRF State Token against state token from GET request received_state_token = query_params.get('state') if received_state_token is None: error_message = 'Bad Request. Missing state parameter.' raise UberIllegalState(error_message) if self.state_token != received_state_token: error_message = 'CSRF Error. Expected {}, got {}' error_message = error_message.format( self.state_token, received_state_token, ) raise UberIllegalState(error_message) # Verify either 'code' or 'error' parameter exists error = query_params.get('error') authorization_code = query_params.get(auth.CODE_RESPONSE_TYPE) if error and authorization_code: error_message = ( 'Code and Error query params code and error ' 'can not both be set.' ) raise UberIllegalState(error_message) if error is None and authorization_code is None: error_message = 'Neither query parameter code or error is set.' raise UberIllegalState(error_message) if error: raise UberIllegalState(error) return authorization_code
python
def _verify_query(self, query_params): """Verify response from the Uber Auth server. Parameters query_params (dict) Dictionary of query parameters attached to your redirect URL after user approved your app and was redirected. Returns authorization_code (str) Code received when user grants your app access. Use this code to request an access token. Raises UberIllegalState (ApiError) Thrown if the redirect URL was missing parameters or if the given parameters were not valid. """ error_message = None if self.state_token is not False: # Check CSRF State Token against state token from GET request received_state_token = query_params.get('state') if received_state_token is None: error_message = 'Bad Request. Missing state parameter.' raise UberIllegalState(error_message) if self.state_token != received_state_token: error_message = 'CSRF Error. Expected {}, got {}' error_message = error_message.format( self.state_token, received_state_token, ) raise UberIllegalState(error_message) # Verify either 'code' or 'error' parameter exists error = query_params.get('error') authorization_code = query_params.get(auth.CODE_RESPONSE_TYPE) if error and authorization_code: error_message = ( 'Code and Error query params code and error ' 'can not both be set.' ) raise UberIllegalState(error_message) if error is None and authorization_code is None: error_message = 'Neither query parameter code or error is set.' raise UberIllegalState(error_message) if error: raise UberIllegalState(error) return authorization_code
[ "def", "_verify_query", "(", "self", ",", "query_params", ")", ":", "error_message", "=", "None", "if", "self", ".", "state_token", "is", "not", "False", ":", "# Check CSRF State Token against state token from GET request", "received_state_token", "=", "query_params", ".", "get", "(", "'state'", ")", "if", "received_state_token", "is", "None", ":", "error_message", "=", "'Bad Request. Missing state parameter.'", "raise", "UberIllegalState", "(", "error_message", ")", "if", "self", ".", "state_token", "!=", "received_state_token", ":", "error_message", "=", "'CSRF Error. Expected {}, got {}'", "error_message", "=", "error_message", ".", "format", "(", "self", ".", "state_token", ",", "received_state_token", ",", ")", "raise", "UberIllegalState", "(", "error_message", ")", "# Verify either 'code' or 'error' parameter exists", "error", "=", "query_params", ".", "get", "(", "'error'", ")", "authorization_code", "=", "query_params", ".", "get", "(", "auth", ".", "CODE_RESPONSE_TYPE", ")", "if", "error", "and", "authorization_code", ":", "error_message", "=", "(", "'Code and Error query params code and error '", "'can not both be set.'", ")", "raise", "UberIllegalState", "(", "error_message", ")", "if", "error", "is", "None", "and", "authorization_code", "is", "None", ":", "error_message", "=", "'Neither query parameter code or error is set.'", "raise", "UberIllegalState", "(", "error_message", ")", "if", "error", ":", "raise", "UberIllegalState", "(", "error", ")", "return", "authorization_code" ]
Verify response from the Uber Auth server. Parameters query_params (dict) Dictionary of query parameters attached to your redirect URL after user approved your app and was redirected. Returns authorization_code (str) Code received when user grants your app access. Use this code to request an access token. Raises UberIllegalState (ApiError) Thrown if the redirect URL was missing parameters or if the given parameters were not valid.
[ "Verify", "response", "from", "the", "Uber", "Auth", "server", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L222-L275
17,408
uber/rides-python-sdk
uber_rides/auth.py
ImplicitGrant.get_authorization_url
def get_authorization_url(self): """Build URL for authorization request. Returns (str) The fully constructed authorization request URL. """ return self._build_authorization_request_url( response_type=auth.TOKEN_RESPONSE_TYPE, redirect_url=self.redirect_url, )
python
def get_authorization_url(self): """Build URL for authorization request. Returns (str) The fully constructed authorization request URL. """ return self._build_authorization_request_url( response_type=auth.TOKEN_RESPONSE_TYPE, redirect_url=self.redirect_url, )
[ "def", "get_authorization_url", "(", "self", ")", ":", "return", "self", ".", "_build_authorization_request_url", "(", "response_type", "=", "auth", ".", "TOKEN_RESPONSE_TYPE", ",", "redirect_url", "=", "self", ".", "redirect_url", ",", ")" ]
Build URL for authorization request. Returns (str) The fully constructed authorization request URL.
[ "Build", "URL", "for", "authorization", "request", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/auth.py#L346-L356
17,409
uber/rides-python-sdk
uber_rides/client.py
surge_handler
def surge_handler(response, **kwargs): """Error Handler to surface 409 Surge Conflict errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments. """ if response.status_code == codes.conflict: json = response.json() errors = json.get('errors', []) error = errors[0] if errors else json.get('error') if error and error.get('code') == 'surge': raise SurgeError(response) return response
python
def surge_handler(response, **kwargs): """Error Handler to surface 409 Surge Conflict errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments. """ if response.status_code == codes.conflict: json = response.json() errors = json.get('errors', []) error = errors[0] if errors else json.get('error') if error and error.get('code') == 'surge': raise SurgeError(response) return response
[ "def", "surge_handler", "(", "response", ",", "*", "*", "kwargs", ")", ":", "if", "response", ".", "status_code", "==", "codes", ".", "conflict", ":", "json", "=", "response", ".", "json", "(", ")", "errors", "=", "json", ".", "get", "(", "'errors'", ",", "[", "]", ")", "error", "=", "errors", "[", "0", "]", "if", "errors", "else", "json", ".", "get", "(", "'error'", ")", "if", "error", "and", "error", ".", "get", "(", "'code'", ")", "==", "'surge'", ":", "raise", "SurgeError", "(", "response", ")", "return", "response" ]
Error Handler to surface 409 Surge Conflict errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments.
[ "Error", "Handler", "to", "surface", "409", "Surge", "Conflict", "errors", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L879-L898
17,410
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_products
def get_products(self, latitude, longitude): """Get information about the Uber products offered at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. Returns (Response) A Response object containing available products information. """ args = OrderedDict([ ('latitude', latitude), ('longitude', longitude), ]) return self._api_call('GET', 'v1.2/products', args=args)
python
def get_products(self, latitude, longitude): """Get information about the Uber products offered at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. Returns (Response) A Response object containing available products information. """ args = OrderedDict([ ('latitude', latitude), ('longitude', longitude), ]) return self._api_call('GET', 'v1.2/products', args=args)
[ "def", "get_products", "(", "self", ",", "latitude", ",", "longitude", ")", ":", "args", "=", "OrderedDict", "(", "[", "(", "'latitude'", ",", "latitude", ")", ",", "(", "'longitude'", ",", "longitude", ")", ",", "]", ")", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1.2/products'", ",", "args", "=", "args", ")" ]
Get information about the Uber products offered at a given location. Parameters latitude (float) The latitude component of a location. longitude (float) The longitude component of a location. Returns (Response) A Response object containing available products information.
[ "Get", "information", "about", "the", "Uber", "products", "offered", "at", "a", "given", "location", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L109-L127
17,411
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_price_estimates
def get_price_estimates( self, start_latitude, start_longitude, end_latitude, end_longitude, seat_count=None, ): """Get price estimates for products at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. seat_count (int) The number of seats required for uberPOOL. Default and maximum value is 2. Returns (Response) A Response object containing each product's price estimates. """ args = OrderedDict([ ('start_latitude', start_latitude), ('start_longitude', start_longitude), ('end_latitude', end_latitude), ('end_longitude', end_longitude), ('seat_count', seat_count), ]) return self._api_call('GET', 'v1.2/estimates/price', args=args)
python
def get_price_estimates( self, start_latitude, start_longitude, end_latitude, end_longitude, seat_count=None, ): """Get price estimates for products at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. seat_count (int) The number of seats required for uberPOOL. Default and maximum value is 2. Returns (Response) A Response object containing each product's price estimates. """ args = OrderedDict([ ('start_latitude', start_latitude), ('start_longitude', start_longitude), ('end_latitude', end_latitude), ('end_longitude', end_longitude), ('seat_count', seat_count), ]) return self._api_call('GET', 'v1.2/estimates/price', args=args)
[ "def", "get_price_estimates", "(", "self", ",", "start_latitude", ",", "start_longitude", ",", "end_latitude", ",", "end_longitude", ",", "seat_count", "=", "None", ",", ")", ":", "args", "=", "OrderedDict", "(", "[", "(", "'start_latitude'", ",", "start_latitude", ")", ",", "(", "'start_longitude'", ",", "start_longitude", ")", ",", "(", "'end_latitude'", ",", "end_latitude", ")", ",", "(", "'end_longitude'", ",", "end_longitude", ")", ",", "(", "'seat_count'", ",", "seat_count", ")", ",", "]", ")", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1.2/estimates/price'", ",", "args", "=", "args", ")" ]
Get price estimates for products at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. seat_count (int) The number of seats required for uberPOOL. Default and maximum value is 2. Returns (Response) A Response object containing each product's price estimates.
[ "Get", "price", "estimates", "for", "products", "at", "a", "given", "location", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L144-L179
17,412
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_pickup_time_estimates
def get_pickup_time_estimates( self, start_latitude, start_longitude, product_id=None, ): """Get pickup time estimates for products at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. Returns (Response) A Response containing each product's pickup time estimates. """ args = OrderedDict([ ('start_latitude', start_latitude), ('start_longitude', start_longitude), ('product_id', product_id), ]) return self._api_call('GET', 'v1.2/estimates/time', args=args)
python
def get_pickup_time_estimates( self, start_latitude, start_longitude, product_id=None, ): """Get pickup time estimates for products at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. Returns (Response) A Response containing each product's pickup time estimates. """ args = OrderedDict([ ('start_latitude', start_latitude), ('start_longitude', start_longitude), ('product_id', product_id), ]) return self._api_call('GET', 'v1.2/estimates/time', args=args)
[ "def", "get_pickup_time_estimates", "(", "self", ",", "start_latitude", ",", "start_longitude", ",", "product_id", "=", "None", ",", ")", ":", "args", "=", "OrderedDict", "(", "[", "(", "'start_latitude'", ",", "start_latitude", ")", ",", "(", "'start_longitude'", ",", "start_longitude", ")", ",", "(", "'product_id'", ",", "product_id", ")", ",", "]", ")", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1.2/estimates/time'", ",", "args", "=", "args", ")" ]
Get pickup time estimates for products at a given location. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. Returns (Response) A Response containing each product's pickup time estimates.
[ "Get", "pickup", "time", "estimates", "for", "products", "at", "a", "given", "location", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L181-L209
17,413
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_promotions
def get_promotions( self, start_latitude, start_longitude, end_latitude, end_longitude, ): """Get information about the promotions available to a user. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. Returns (Response) A Response object containing available promotions. """ args = OrderedDict([ ('start_latitude', start_latitude), ('start_longitude', start_longitude), ('end_latitude', end_latitude), ('end_longitude', end_longitude) ]) return self._api_call('GET', 'v1.2/promotions', args=args)
python
def get_promotions( self, start_latitude, start_longitude, end_latitude, end_longitude, ): """Get information about the promotions available to a user. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. Returns (Response) A Response object containing available promotions. """ args = OrderedDict([ ('start_latitude', start_latitude), ('start_longitude', start_longitude), ('end_latitude', end_latitude), ('end_longitude', end_longitude) ]) return self._api_call('GET', 'v1.2/promotions', args=args)
[ "def", "get_promotions", "(", "self", ",", "start_latitude", ",", "start_longitude", ",", "end_latitude", ",", "end_longitude", ",", ")", ":", "args", "=", "OrderedDict", "(", "[", "(", "'start_latitude'", ",", "start_latitude", ")", ",", "(", "'start_longitude'", ",", "start_longitude", ")", ",", "(", "'end_latitude'", ",", "end_latitude", ")", ",", "(", "'end_longitude'", ",", "end_longitude", ")", "]", ")", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1.2/promotions'", ",", "args", "=", "args", ")" ]
Get information about the promotions available to a user. Parameters start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. Returns (Response) A Response object containing available promotions.
[ "Get", "information", "about", "the", "promotions", "available", "to", "a", "user", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L211-L242
17,414
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_user_activity
def get_user_activity(self, offset=None, limit=None): """Get activity about the user's lifetime activity with Uber. Parameters offset (int) The integer offset for activity results. Default is 0. limit (int) Integer amount of results to return. Maximum is 50. Default is 5. Returns (Response) A Response object containing ride history. """ args = { 'offset': offset, 'limit': limit, } return self._api_call('GET', 'v1.2/history', args=args)
python
def get_user_activity(self, offset=None, limit=None): """Get activity about the user's lifetime activity with Uber. Parameters offset (int) The integer offset for activity results. Default is 0. limit (int) Integer amount of results to return. Maximum is 50. Default is 5. Returns (Response) A Response object containing ride history. """ args = { 'offset': offset, 'limit': limit, } return self._api_call('GET', 'v1.2/history', args=args)
[ "def", "get_user_activity", "(", "self", ",", "offset", "=", "None", ",", "limit", "=", "None", ")", ":", "args", "=", "{", "'offset'", ":", "offset", ",", "'limit'", ":", "limit", ",", "}", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1.2/history'", ",", "args", "=", "args", ")" ]
Get activity about the user's lifetime activity with Uber. Parameters offset (int) The integer offset for activity results. Default is 0. limit (int) Integer amount of results to return. Maximum is 50. Default is 5. Returns (Response) A Response object containing ride history.
[ "Get", "activity", "about", "the", "user", "s", "lifetime", "activity", "with", "Uber", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L244-L263
17,415
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.estimate_ride
def estimate_ride( self, product_id=None, start_latitude=None, start_longitude=None, start_place_id=None, end_latitude=None, end_longitude=None, end_place_id=None, seat_count=None, ): """Estimate ride details given a product, start, and end location. Only pickup time estimates and surge pricing information are provided if no end location is provided. Parameters product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. start_place_id (str) The beginning or pickup place ID. Only "home" or "work" is acceptable. end_latitude (float) Optional latitude component of a end location. end_longitude (float) Optional longitude component of a end location. end_place_id (str) The final or destination place ID. Only "home" or "work" is acceptable. seat_count (str) Optional Seat count for shared products. Default is 2. Returns (Response) A Response object containing fare id, time, price, and distance estimates for a ride. """ args = { 'product_id': product_id, 'start_latitude': start_latitude, 'start_longitude': start_longitude, 'start_place_id': start_place_id, 'end_latitude': end_latitude, 'end_longitude': end_longitude, 'end_place_id': end_place_id, 'seat_count': seat_count } return self._api_call('POST', 'v1.2/requests/estimate', args=args)
python
def estimate_ride( self, product_id=None, start_latitude=None, start_longitude=None, start_place_id=None, end_latitude=None, end_longitude=None, end_place_id=None, seat_count=None, ): """Estimate ride details given a product, start, and end location. Only pickup time estimates and surge pricing information are provided if no end location is provided. Parameters product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. start_place_id (str) The beginning or pickup place ID. Only "home" or "work" is acceptable. end_latitude (float) Optional latitude component of a end location. end_longitude (float) Optional longitude component of a end location. end_place_id (str) The final or destination place ID. Only "home" or "work" is acceptable. seat_count (str) Optional Seat count for shared products. Default is 2. Returns (Response) A Response object containing fare id, time, price, and distance estimates for a ride. """ args = { 'product_id': product_id, 'start_latitude': start_latitude, 'start_longitude': start_longitude, 'start_place_id': start_place_id, 'end_latitude': end_latitude, 'end_longitude': end_longitude, 'end_place_id': end_place_id, 'seat_count': seat_count } return self._api_call('POST', 'v1.2/requests/estimate', args=args)
[ "def", "estimate_ride", "(", "self", ",", "product_id", "=", "None", ",", "start_latitude", "=", "None", ",", "start_longitude", "=", "None", ",", "start_place_id", "=", "None", ",", "end_latitude", "=", "None", ",", "end_longitude", "=", "None", ",", "end_place_id", "=", "None", ",", "seat_count", "=", "None", ",", ")", ":", "args", "=", "{", "'product_id'", ":", "product_id", ",", "'start_latitude'", ":", "start_latitude", ",", "'start_longitude'", ":", "start_longitude", ",", "'start_place_id'", ":", "start_place_id", ",", "'end_latitude'", ":", "end_latitude", ",", "'end_longitude'", ":", "end_longitude", ",", "'end_place_id'", ":", "end_place_id", ",", "'seat_count'", ":", "seat_count", "}", "return", "self", ".", "_api_call", "(", "'POST'", ",", "'v1.2/requests/estimate'", ",", "args", "=", "args", ")" ]
Estimate ride details given a product, start, and end location. Only pickup time estimates and surge pricing information are provided if no end location is provided. Parameters product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. start_latitude (float) The latitude component of a start location. start_longitude (float) The longitude component of a start location. start_place_id (str) The beginning or pickup place ID. Only "home" or "work" is acceptable. end_latitude (float) Optional latitude component of a end location. end_longitude (float) Optional longitude component of a end location. end_place_id (str) The final or destination place ID. Only "home" or "work" is acceptable. seat_count (str) Optional Seat count for shared products. Default is 2. Returns (Response) A Response object containing fare id, time, price, and distance estimates for a ride.
[ "Estimate", "ride", "details", "given", "a", "product", "start", "and", "end", "location", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L319-L374
17,416
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.request_ride
def request_ride( self, product_id=None, start_latitude=None, start_longitude=None, start_place_id=None, start_address=None, start_nickname=None, end_latitude=None, end_longitude=None, end_place_id=None, end_address=None, end_nickname=None, seat_count=None, fare_id=None, surge_confirmation_id=None, payment_method_id=None, ): """Request a ride on behalf of an Uber user. When specifying pickup and dropoff locations, you can either use latitude/longitude pairs or place ID (but not both). Parameters product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. start_latitude (float) Optional latitude component of a start location. start_longitude (float) Optional longitude component of a start location. start_place_id (str) The beginning or pickup place ID. Only "home" or "work" is acceptable. start_address (str) Optional pickup address. start_nickname (str) Optional pickup nickname label. end_latitude (float) Optional latitude component of a end location. end_longitude (float) Optional longitude component of a end location. end_place_id (str) The final or destination place ID. Only "home" or "work" is acceptable. end_address (str) Optional destination address. end_nickname (str) Optional destination nickname label. seat_count (int) Optional seat count for shared products. fare_id (str) Optional fare_id for shared products. surge_confirmation_id (str) Optional unique identifier of the surge session for a user. payment_method_id (str) Optional unique identifier of the payment method selected by a user. If set, the trip will be requested using this payment method. If not, the trip will be requested with the user's last used payment method. Returns (Response) A Response object containing the ride request ID and other details about the requested ride. Raises SurgeError (ClientError) Thrown when the requested product is currently surging. User must confirm surge price through surge_confirmation_href. """ args = { 'product_id': product_id, 'start_latitude': start_latitude, 'start_longitude': start_longitude, 'start_place_id': start_place_id, 'start_address': start_address, 'start_nickname': start_nickname, 'end_latitude': end_latitude, 'end_longitude': end_longitude, 'end_place_id': end_place_id, 'end_address': end_address, 'end_nickname': end_nickname, 'surge_confirmation_id': surge_confirmation_id, 'payment_method_id': payment_method_id, 'seat_count': seat_count, 'fare_id': fare_id } return self._api_call('POST', 'v1.2/requests', args=args)
python
def request_ride( self, product_id=None, start_latitude=None, start_longitude=None, start_place_id=None, start_address=None, start_nickname=None, end_latitude=None, end_longitude=None, end_place_id=None, end_address=None, end_nickname=None, seat_count=None, fare_id=None, surge_confirmation_id=None, payment_method_id=None, ): """Request a ride on behalf of an Uber user. When specifying pickup and dropoff locations, you can either use latitude/longitude pairs or place ID (but not both). Parameters product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. start_latitude (float) Optional latitude component of a start location. start_longitude (float) Optional longitude component of a start location. start_place_id (str) The beginning or pickup place ID. Only "home" or "work" is acceptable. start_address (str) Optional pickup address. start_nickname (str) Optional pickup nickname label. end_latitude (float) Optional latitude component of a end location. end_longitude (float) Optional longitude component of a end location. end_place_id (str) The final or destination place ID. Only "home" or "work" is acceptable. end_address (str) Optional destination address. end_nickname (str) Optional destination nickname label. seat_count (int) Optional seat count for shared products. fare_id (str) Optional fare_id for shared products. surge_confirmation_id (str) Optional unique identifier of the surge session for a user. payment_method_id (str) Optional unique identifier of the payment method selected by a user. If set, the trip will be requested using this payment method. If not, the trip will be requested with the user's last used payment method. Returns (Response) A Response object containing the ride request ID and other details about the requested ride. Raises SurgeError (ClientError) Thrown when the requested product is currently surging. User must confirm surge price through surge_confirmation_href. """ args = { 'product_id': product_id, 'start_latitude': start_latitude, 'start_longitude': start_longitude, 'start_place_id': start_place_id, 'start_address': start_address, 'start_nickname': start_nickname, 'end_latitude': end_latitude, 'end_longitude': end_longitude, 'end_place_id': end_place_id, 'end_address': end_address, 'end_nickname': end_nickname, 'surge_confirmation_id': surge_confirmation_id, 'payment_method_id': payment_method_id, 'seat_count': seat_count, 'fare_id': fare_id } return self._api_call('POST', 'v1.2/requests', args=args)
[ "def", "request_ride", "(", "self", ",", "product_id", "=", "None", ",", "start_latitude", "=", "None", ",", "start_longitude", "=", "None", ",", "start_place_id", "=", "None", ",", "start_address", "=", "None", ",", "start_nickname", "=", "None", ",", "end_latitude", "=", "None", ",", "end_longitude", "=", "None", ",", "end_place_id", "=", "None", ",", "end_address", "=", "None", ",", "end_nickname", "=", "None", ",", "seat_count", "=", "None", ",", "fare_id", "=", "None", ",", "surge_confirmation_id", "=", "None", ",", "payment_method_id", "=", "None", ",", ")", ":", "args", "=", "{", "'product_id'", ":", "product_id", ",", "'start_latitude'", ":", "start_latitude", ",", "'start_longitude'", ":", "start_longitude", ",", "'start_place_id'", ":", "start_place_id", ",", "'start_address'", ":", "start_address", ",", "'start_nickname'", ":", "start_nickname", ",", "'end_latitude'", ":", "end_latitude", ",", "'end_longitude'", ":", "end_longitude", ",", "'end_place_id'", ":", "end_place_id", ",", "'end_address'", ":", "end_address", ",", "'end_nickname'", ":", "end_nickname", ",", "'surge_confirmation_id'", ":", "surge_confirmation_id", ",", "'payment_method_id'", ":", "payment_method_id", ",", "'seat_count'", ":", "seat_count", ",", "'fare_id'", ":", "fare_id", "}", "return", "self", ".", "_api_call", "(", "'POST'", ",", "'v1.2/requests'", ",", "args", "=", "args", ")" ]
Request a ride on behalf of an Uber user. When specifying pickup and dropoff locations, you can either use latitude/longitude pairs or place ID (but not both). Parameters product_id (str) The unique ID of the product being requested. If none is provided, it will default to the cheapest product for the given location. start_latitude (float) Optional latitude component of a start location. start_longitude (float) Optional longitude component of a start location. start_place_id (str) The beginning or pickup place ID. Only "home" or "work" is acceptable. start_address (str) Optional pickup address. start_nickname (str) Optional pickup nickname label. end_latitude (float) Optional latitude component of a end location. end_longitude (float) Optional longitude component of a end location. end_place_id (str) The final or destination place ID. Only "home" or "work" is acceptable. end_address (str) Optional destination address. end_nickname (str) Optional destination nickname label. seat_count (int) Optional seat count for shared products. fare_id (str) Optional fare_id for shared products. surge_confirmation_id (str) Optional unique identifier of the surge session for a user. payment_method_id (str) Optional unique identifier of the payment method selected by a user. If set, the trip will be requested using this payment method. If not, the trip will be requested with the user's last used payment method. Returns (Response) A Response object containing the ride request ID and other details about the requested ride. Raises SurgeError (ClientError) Thrown when the requested product is currently surging. User must confirm surge price through surge_confirmation_href.
[ "Request", "a", "ride", "on", "behalf", "of", "an", "Uber", "user", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L376-L466
17,417
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.update_ride
def update_ride( self, ride_id, end_latitude=None, end_longitude=None, end_place_id=None, ): """Update an ongoing ride's destination. To specify a new dropoff location, you can either use a latitude/longitude pair or place ID (but not both). Params ride_id (str) The unique ID of the Ride Request. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. end_place_id (str) The final or destination place ID. This is the name of an Uber saved place. Only "home" or "work" is acceptable. end_address (str) The final or destination address. end_nickname (str) The final or destination nickname label. Returns (Response) The Response with successful status_code if the ride's destination was updated. """ args = {} if end_latitude is not None: args.update({'end_latitude': end_latitude}) if end_longitude is not None: args.update({'end_longitude': end_longitude}) if end_place_id is not None: args.update({'end_place_id': end_place_id}) endpoint = 'v1.2/requests/{}'.format(ride_id) return self._api_call('PATCH', endpoint, args=args)
python
def update_ride( self, ride_id, end_latitude=None, end_longitude=None, end_place_id=None, ): """Update an ongoing ride's destination. To specify a new dropoff location, you can either use a latitude/longitude pair or place ID (but not both). Params ride_id (str) The unique ID of the Ride Request. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. end_place_id (str) The final or destination place ID. This is the name of an Uber saved place. Only "home" or "work" is acceptable. end_address (str) The final or destination address. end_nickname (str) The final or destination nickname label. Returns (Response) The Response with successful status_code if the ride's destination was updated. """ args = {} if end_latitude is not None: args.update({'end_latitude': end_latitude}) if end_longitude is not None: args.update({'end_longitude': end_longitude}) if end_place_id is not None: args.update({'end_place_id': end_place_id}) endpoint = 'v1.2/requests/{}'.format(ride_id) return self._api_call('PATCH', endpoint, args=args)
[ "def", "update_ride", "(", "self", ",", "ride_id", ",", "end_latitude", "=", "None", ",", "end_longitude", "=", "None", ",", "end_place_id", "=", "None", ",", ")", ":", "args", "=", "{", "}", "if", "end_latitude", "is", "not", "None", ":", "args", ".", "update", "(", "{", "'end_latitude'", ":", "end_latitude", "}", ")", "if", "end_longitude", "is", "not", "None", ":", "args", ".", "update", "(", "{", "'end_longitude'", ":", "end_longitude", "}", ")", "if", "end_place_id", "is", "not", "None", ":", "args", ".", "update", "(", "{", "'end_place_id'", ":", "end_place_id", "}", ")", "endpoint", "=", "'v1.2/requests/{}'", ".", "format", "(", "ride_id", ")", "return", "self", ".", "_api_call", "(", "'PATCH'", ",", "endpoint", ",", "args", "=", "args", ")" ]
Update an ongoing ride's destination. To specify a new dropoff location, you can either use a latitude/longitude pair or place ID (but not both). Params ride_id (str) The unique ID of the Ride Request. end_latitude (float) The latitude component of a end location. end_longitude (float) The longitude component of a end location. end_place_id (str) The final or destination place ID. This is the name of an Uber saved place. Only "home" or "work" is acceptable. end_address (str) The final or destination address. end_nickname (str) The final or destination nickname label. Returns (Response) The Response with successful status_code if the ride's destination was updated.
[ "Update", "an", "ongoing", "ride", "s", "destination", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L498-L539
17,418
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.update_sandbox_ride
def update_sandbox_ride(self, ride_id, new_status): """Update the status of an ongoing sandbox request. Params ride_id (str) The unique ID of the Ride Request. new_status (str) Status from VALID_PRODUCT_STATUS. Returns (Response) A Response object with successful status_code if ride status was updated. """ if new_status not in VALID_PRODUCT_STATUS: message = '{} is not a valid product status.' raise UberIllegalState(message.format(new_status)) args = {'status': new_status} endpoint = 'v1.2/sandbox/requests/{}'.format(ride_id) return self._api_call('PUT', endpoint, args=args)
python
def update_sandbox_ride(self, ride_id, new_status): """Update the status of an ongoing sandbox request. Params ride_id (str) The unique ID of the Ride Request. new_status (str) Status from VALID_PRODUCT_STATUS. Returns (Response) A Response object with successful status_code if ride status was updated. """ if new_status not in VALID_PRODUCT_STATUS: message = '{} is not a valid product status.' raise UberIllegalState(message.format(new_status)) args = {'status': new_status} endpoint = 'v1.2/sandbox/requests/{}'.format(ride_id) return self._api_call('PUT', endpoint, args=args)
[ "def", "update_sandbox_ride", "(", "self", ",", "ride_id", ",", "new_status", ")", ":", "if", "new_status", "not", "in", "VALID_PRODUCT_STATUS", ":", "message", "=", "'{} is not a valid product status.'", "raise", "UberIllegalState", "(", "message", ".", "format", "(", "new_status", ")", ")", "args", "=", "{", "'status'", ":", "new_status", "}", "endpoint", "=", "'v1.2/sandbox/requests/{}'", ".", "format", "(", "ride_id", ")", "return", "self", ".", "_api_call", "(", "'PUT'", ",", "endpoint", ",", "args", "=", "args", ")" ]
Update the status of an ongoing sandbox request. Params ride_id (str) The unique ID of the Ride Request. new_status (str) Status from VALID_PRODUCT_STATUS. Returns (Response) A Response object with successful status_code if ride status was updated.
[ "Update", "the", "status", "of", "an", "ongoing", "sandbox", "request", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L602-L622
17,419
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.update_sandbox_product
def update_sandbox_product( self, product_id, surge_multiplier=None, drivers_available=None, ): """Update sandbox product availability. Params product_id (str) Unique identifier representing a specific product for a given location. surge_multiplier (float) Optional surge multiplier to manipulate pricing of product. drivers_available (bool) Optional boolean to manipulate availability of product. Returns (Response) The Response with successful status_code if product status was updated. """ args = { 'surge_multiplier': surge_multiplier, 'drivers_available': drivers_available, } endpoint = 'v1.2/sandbox/products/{}'.format(product_id) return self._api_call('PUT', endpoint, args=args)
python
def update_sandbox_product( self, product_id, surge_multiplier=None, drivers_available=None, ): """Update sandbox product availability. Params product_id (str) Unique identifier representing a specific product for a given location. surge_multiplier (float) Optional surge multiplier to manipulate pricing of product. drivers_available (bool) Optional boolean to manipulate availability of product. Returns (Response) The Response with successful status_code if product status was updated. """ args = { 'surge_multiplier': surge_multiplier, 'drivers_available': drivers_available, } endpoint = 'v1.2/sandbox/products/{}'.format(product_id) return self._api_call('PUT', endpoint, args=args)
[ "def", "update_sandbox_product", "(", "self", ",", "product_id", ",", "surge_multiplier", "=", "None", ",", "drivers_available", "=", "None", ",", ")", ":", "args", "=", "{", "'surge_multiplier'", ":", "surge_multiplier", ",", "'drivers_available'", ":", "drivers_available", ",", "}", "endpoint", "=", "'v1.2/sandbox/products/{}'", ".", "format", "(", "product_id", ")", "return", "self", ".", "_api_call", "(", "'PUT'", ",", "endpoint", ",", "args", "=", "args", ")" ]
Update sandbox product availability. Params product_id (str) Unique identifier representing a specific product for a given location. surge_multiplier (float) Optional surge multiplier to manipulate pricing of product. drivers_available (bool) Optional boolean to manipulate availability of product. Returns (Response) The Response with successful status_code if product status was updated.
[ "Update", "sandbox", "product", "availability", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L624-L652
17,420
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.revoke_oauth_credential
def revoke_oauth_credential(self): """Revoke the session's OAuth 2.0 credentials.""" if self.session.token_type == auth.SERVER_TOKEN_TYPE: return credential = self.session.oauth2credential revoke_access_token(credential)
python
def revoke_oauth_credential(self): """Revoke the session's OAuth 2.0 credentials.""" if self.session.token_type == auth.SERVER_TOKEN_TYPE: return credential = self.session.oauth2credential revoke_access_token(credential)
[ "def", "revoke_oauth_credential", "(", "self", ")", ":", "if", "self", ".", "session", ".", "token_type", "==", "auth", ".", "SERVER_TOKEN_TYPE", ":", "return", "credential", "=", "self", ".", "session", ".", "oauth2credential", "revoke_access_token", "(", "credential", ")" ]
Revoke the session's OAuth 2.0 credentials.
[ "Revoke", "the", "session", "s", "OAuth", "2", ".", "0", "credentials", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L722-L728
17,421
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_driver_trips
def get_driver_trips(self, offset=None, limit=None, from_time=None, to_time=None ): """Get trips about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information. """ args = { 'offset': offset, 'limit': limit, 'from_time': from_time, 'to_time': to_time, } return self._api_call('GET', 'v1/partners/trips', args=args)
python
def get_driver_trips(self, offset=None, limit=None, from_time=None, to_time=None ): """Get trips about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information. """ args = { 'offset': offset, 'limit': limit, 'from_time': from_time, 'to_time': to_time, } return self._api_call('GET', 'v1/partners/trips', args=args)
[ "def", "get_driver_trips", "(", "self", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ")", ":", "args", "=", "{", "'offset'", ":", "offset", ",", "'limit'", ":", "limit", ",", "'from_time'", ":", "from_time", ",", "'to_time'", ":", "to_time", ",", "}", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1/partners/trips'", ",", "args", "=", "args", ")" ]
Get trips about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information.
[ "Get", "trips", "about", "the", "authorized", "Uber", "driver", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L739-L771
17,422
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.get_driver_payments
def get_driver_payments(self, offset=None, limit=None, from_time=None, to_time=None ): """Get payments about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information. """ args = { 'offset': offset, 'limit': limit, 'from_time': from_time, 'to_time': to_time, } return self._api_call('GET', 'v1/partners/payments', args=args)
python
def get_driver_payments(self, offset=None, limit=None, from_time=None, to_time=None ): """Get payments about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information. """ args = { 'offset': offset, 'limit': limit, 'from_time': from_time, 'to_time': to_time, } return self._api_call('GET', 'v1/partners/payments', args=args)
[ "def", "get_driver_payments", "(", "self", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ")", ":", "args", "=", "{", "'offset'", ":", "offset", ",", "'limit'", ":", "limit", ",", "'from_time'", ":", "from_time", ",", "'to_time'", ":", "to_time", ",", "}", "return", "self", ".", "_api_call", "(", "'GET'", ",", "'v1/partners/payments'", ",", "args", "=", "args", ")" ]
Get payments about the authorized Uber driver. Parameters offset (int) The integer offset for activity results. Offset the list of returned results by this amount. Default is zero. limit (int) Integer amount of results to return. Number of items to retrieve per page. Default is 10, maximum is 50. from_time (int) Unix timestamp of the start time to query. Queries starting from the first trip if omitted. to_time (int) Unix timestamp of the end time to query. Queries starting from the last trip if omitted. Returns (Response) A Response object containing trip information.
[ "Get", "payments", "about", "the", "authorized", "Uber", "driver", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L773-L805
17,423
uber/rides-python-sdk
uber_rides/client.py
UberRidesClient.validiate_webhook_signature
def validiate_webhook_signature(self, webhook, signature): """Validates a webhook signature from a webhook body + client secret Parameters webhook (string) The request body of the webhook. signature (string) The webhook signature specified in X-Uber-Signature header. """ digester = hmac.new(self.session.oauth2credential.client_secret, webhook, hashlib.sha256 ) return (signature == digester.hexdigest())
python
def validiate_webhook_signature(self, webhook, signature): """Validates a webhook signature from a webhook body + client secret Parameters webhook (string) The request body of the webhook. signature (string) The webhook signature specified in X-Uber-Signature header. """ digester = hmac.new(self.session.oauth2credential.client_secret, webhook, hashlib.sha256 ) return (signature == digester.hexdigest())
[ "def", "validiate_webhook_signature", "(", "self", ",", "webhook", ",", "signature", ")", ":", "digester", "=", "hmac", ".", "new", "(", "self", ".", "session", ".", "oauth2credential", ".", "client_secret", ",", "webhook", ",", "hashlib", ".", "sha256", ")", "return", "(", "signature", "==", "digester", ".", "hexdigest", "(", ")", ")" ]
Validates a webhook signature from a webhook body + client secret Parameters webhook (string) The request body of the webhook. signature (string) The webhook signature specified in X-Uber-Signature header.
[ "Validates", "a", "webhook", "signature", "from", "a", "webhook", "body", "+", "client", "secret" ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L863-L876
17,424
uber/rides-python-sdk
uber_rides/client.py
SurgeError.adapt_meta
def adapt_meta(self, meta): """Convert meta from error response to href and surge_id attributes.""" surge = meta.get('surge_confirmation') href = surge.get('href') surge_id = surge.get('surge_confirmation_id') return href, surge_id
python
def adapt_meta(self, meta): """Convert meta from error response to href and surge_id attributes.""" surge = meta.get('surge_confirmation') href = surge.get('href') surge_id = surge.get('surge_confirmation_id') return href, surge_id
[ "def", "adapt_meta", "(", "self", ",", "meta", ")", ":", "surge", "=", "meta", ".", "get", "(", "'surge_confirmation'", ")", "href", "=", "surge", ".", "get", "(", "'href'", ")", "surge_id", "=", "surge", ".", "get", "(", "'surge_confirmation_id'", ")", "return", "href", ",", "surge_id" ]
Convert meta from error response to href and surge_id attributes.
[ "Convert", "meta", "from", "error", "response", "to", "href", "and", "surge_id", "attributes", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/client.py#L928-L935
17,425
uber/rides-python-sdk
example/request_ride.py
estimate_ride
def estimate_ride(api_client): """Use an UberRidesClient to fetch a ride estimate and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. """ try: estimate = api_client.estimate_ride( product_id=SURGE_PRODUCT_ID, start_latitude=START_LAT, start_longitude=START_LNG, end_latitude=END_LAT, end_longitude=END_LNG, seat_count=2 ) except (ClientError, ServerError) as error: fail_print(error) else: success_print(estimate.json)
python
def estimate_ride(api_client): """Use an UberRidesClient to fetch a ride estimate and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. """ try: estimate = api_client.estimate_ride( product_id=SURGE_PRODUCT_ID, start_latitude=START_LAT, start_longitude=START_LNG, end_latitude=END_LAT, end_longitude=END_LNG, seat_count=2 ) except (ClientError, ServerError) as error: fail_print(error) else: success_print(estimate.json)
[ "def", "estimate_ride", "(", "api_client", ")", ":", "try", ":", "estimate", "=", "api_client", ".", "estimate_ride", "(", "product_id", "=", "SURGE_PRODUCT_ID", ",", "start_latitude", "=", "START_LAT", ",", "start_longitude", "=", "START_LNG", ",", "end_latitude", "=", "END_LAT", ",", "end_longitude", "=", "END_LNG", ",", "seat_count", "=", "2", ")", "except", "(", "ClientError", ",", "ServerError", ")", "as", "error", ":", "fail_print", "(", "error", ")", "else", ":", "success_print", "(", "estimate", ".", "json", ")" ]
Use an UberRidesClient to fetch a ride estimate and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope.
[ "Use", "an", "UberRidesClient", "to", "fetch", "a", "ride", "estimate", "and", "print", "the", "results", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/request_ride.py#L75-L96
17,426
uber/rides-python-sdk
example/request_ride.py
update_surge
def update_surge(api_client, surge_multiplier): """Use an UberRidesClient to update surge and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. surge_mutliplier (float) The surge multiple for a sandbox product. A multiplier greater than or equal to 2.0 will require the two stage confirmation screen. """ try: update_surge = api_client.update_sandbox_product( SURGE_PRODUCT_ID, surge_multiplier=surge_multiplier, ) except (ClientError, ServerError) as error: fail_print(error) else: success_print(update_surge.status_code)
python
def update_surge(api_client, surge_multiplier): """Use an UberRidesClient to update surge and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. surge_mutliplier (float) The surge multiple for a sandbox product. A multiplier greater than or equal to 2.0 will require the two stage confirmation screen. """ try: update_surge = api_client.update_sandbox_product( SURGE_PRODUCT_ID, surge_multiplier=surge_multiplier, ) except (ClientError, ServerError) as error: fail_print(error) else: success_print(update_surge.status_code)
[ "def", "update_surge", "(", "api_client", ",", "surge_multiplier", ")", ":", "try", ":", "update_surge", "=", "api_client", ".", "update_sandbox_product", "(", "SURGE_PRODUCT_ID", ",", "surge_multiplier", "=", "surge_multiplier", ",", ")", "except", "(", "ClientError", ",", "ServerError", ")", "as", "error", ":", "fail_print", "(", "error", ")", "else", ":", "success_print", "(", "update_surge", ".", "status_code", ")" ]
Use an UberRidesClient to update surge and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. surge_mutliplier (float) The surge multiple for a sandbox product. A multiplier greater than or equal to 2.0 will require the two stage confirmation screen.
[ "Use", "an", "UberRidesClient", "to", "update", "surge", "and", "print", "the", "results", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/request_ride.py#L99-L119
17,427
uber/rides-python-sdk
example/request_ride.py
update_ride
def update_ride(api_client, ride_status, ride_id): """Use an UberRidesClient to update ride status and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_status (str) New ride status to update to. ride_id (str) Unique identifier for ride to update. """ try: update_product = api_client.update_sandbox_ride(ride_id, ride_status) except (ClientError, ServerError) as error: fail_print(error) else: message = '{} New status: {}' message = message.format(update_product.status_code, ride_status) success_print(message)
python
def update_ride(api_client, ride_status, ride_id): """Use an UberRidesClient to update ride status and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_status (str) New ride status to update to. ride_id (str) Unique identifier for ride to update. """ try: update_product = api_client.update_sandbox_ride(ride_id, ride_status) except (ClientError, ServerError) as error: fail_print(error) else: message = '{} New status: {}' message = message.format(update_product.status_code, ride_status) success_print(message)
[ "def", "update_ride", "(", "api_client", ",", "ride_status", ",", "ride_id", ")", ":", "try", ":", "update_product", "=", "api_client", ".", "update_sandbox_ride", "(", "ride_id", ",", "ride_status", ")", "except", "(", "ClientError", ",", "ServerError", ")", "as", "error", ":", "fail_print", "(", "error", ")", "else", ":", "message", "=", "'{} New status: {}'", "message", "=", "message", ".", "format", "(", "update_product", ".", "status_code", ",", "ride_status", ")", "success_print", "(", "message", ")" ]
Use an UberRidesClient to update ride status and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_status (str) New ride status to update to. ride_id (str) Unique identifier for ride to update.
[ "Use", "an", "UberRidesClient", "to", "update", "ride", "status", "and", "print", "the", "results", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/request_ride.py#L122-L142
17,428
uber/rides-python-sdk
example/request_ride.py
get_ride_details
def get_ride_details(api_client, ride_id): """Use an UberRidesClient to get ride details and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_id (str) Unique ride identifier. """ try: ride_details = api_client.get_ride_details(ride_id) except (ClientError, ServerError) as error: fail_print(error) else: success_print(ride_details.json)
python
def get_ride_details(api_client, ride_id): """Use an UberRidesClient to get ride details and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_id (str) Unique ride identifier. """ try: ride_details = api_client.get_ride_details(ride_id) except (ClientError, ServerError) as error: fail_print(error) else: success_print(ride_details.json)
[ "def", "get_ride_details", "(", "api_client", ",", "ride_id", ")", ":", "try", ":", "ride_details", "=", "api_client", ".", "get_ride_details", "(", "ride_id", ")", "except", "(", "ClientError", ",", "ServerError", ")", "as", "error", ":", "fail_print", "(", "error", ")", "else", ":", "success_print", "(", "ride_details", ".", "json", ")" ]
Use an UberRidesClient to get ride details and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_id (str) Unique ride identifier.
[ "Use", "an", "UberRidesClient", "to", "get", "ride", "details", "and", "print", "the", "results", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/request_ride.py#L238-L254
17,429
uber/rides-python-sdk
uber_rides/utils/request.py
generate_data
def generate_data(method, args): """Assign arguments to body or URL of an HTTP request. Parameters method (str) HTTP Method. (e.g. 'POST') args (dict) Dictionary of data to attach to each Request. e.g. {'latitude': 37.561, 'longitude': -122.742} Returns (str or dict) Either params containing the dictionary of arguments or data containing arugments in JSON-formatted string. """ data = {} params = {} if method in http.BODY_METHODS: data = dumps(args) else: params = args return data, params
python
def generate_data(method, args): """Assign arguments to body or URL of an HTTP request. Parameters method (str) HTTP Method. (e.g. 'POST') args (dict) Dictionary of data to attach to each Request. e.g. {'latitude': 37.561, 'longitude': -122.742} Returns (str or dict) Either params containing the dictionary of arguments or data containing arugments in JSON-formatted string. """ data = {} params = {} if method in http.BODY_METHODS: data = dumps(args) else: params = args return data, params
[ "def", "generate_data", "(", "method", ",", "args", ")", ":", "data", "=", "{", "}", "params", "=", "{", "}", "if", "method", "in", "http", ".", "BODY_METHODS", ":", "data", "=", "dumps", "(", "args", ")", "else", ":", "params", "=", "args", "return", "data", ",", "params" ]
Assign arguments to body or URL of an HTTP request. Parameters method (str) HTTP Method. (e.g. 'POST') args (dict) Dictionary of data to attach to each Request. e.g. {'latitude': 37.561, 'longitude': -122.742} Returns (str or dict) Either params containing the dictionary of arguments or data containing arugments in JSON-formatted string.
[ "Assign", "arguments", "to", "body", "or", "URL", "of", "an", "HTTP", "request", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/utils/request.py#L42-L64
17,430
uber/rides-python-sdk
uber_rides/utils/request.py
generate_prepared_request
def generate_prepared_request(method, url, headers, data, params, handlers): """Add handlers and prepare a Request. Parameters method (str) HTTP Method. (e.g. 'POST') headers (dict) Headers to send. data (JSON-formatted str) Body to attach to the request. params (dict) Dictionary of URL parameters to append to the URL. handlers (list) List of callback hooks, for error handling. Returns (requests.PreparedRequest) The fully mutable PreparedRequest object, containing the exact bytes to send to the server. """ request = Request( method=method, url=url, headers=headers, data=data, params=params, ) handlers.append(error_handler) for handler in handlers: request.register_hook('response', handler) return request.prepare()
python
def generate_prepared_request(method, url, headers, data, params, handlers): """Add handlers and prepare a Request. Parameters method (str) HTTP Method. (e.g. 'POST') headers (dict) Headers to send. data (JSON-formatted str) Body to attach to the request. params (dict) Dictionary of URL parameters to append to the URL. handlers (list) List of callback hooks, for error handling. Returns (requests.PreparedRequest) The fully mutable PreparedRequest object, containing the exact bytes to send to the server. """ request = Request( method=method, url=url, headers=headers, data=data, params=params, ) handlers.append(error_handler) for handler in handlers: request.register_hook('response', handler) return request.prepare()
[ "def", "generate_prepared_request", "(", "method", ",", "url", ",", "headers", ",", "data", ",", "params", ",", "handlers", ")", ":", "request", "=", "Request", "(", "method", "=", "method", ",", "url", "=", "url", ",", "headers", "=", "headers", ",", "data", "=", "data", ",", "params", "=", "params", ",", ")", "handlers", ".", "append", "(", "error_handler", ")", "for", "handler", "in", "handlers", ":", "request", ".", "register_hook", "(", "'response'", ",", "handler", ")", "return", "request", ".", "prepare", "(", ")" ]
Add handlers and prepare a Request. Parameters method (str) HTTP Method. (e.g. 'POST') headers (dict) Headers to send. data (JSON-formatted str) Body to attach to the request. params (dict) Dictionary of URL parameters to append to the URL. handlers (list) List of callback hooks, for error handling. Returns (requests.PreparedRequest) The fully mutable PreparedRequest object, containing the exact bytes to send to the server.
[ "Add", "handlers", "and", "prepare", "a", "Request", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/utils/request.py#L67-L100
17,431
uber/rides-python-sdk
uber_rides/utils/request.py
build_url
def build_url(host, path, params=None): """Build a URL. This method encodes the parameters and adds them to the end of the base URL, then adds scheme and hostname. Parameters host (str) Base URL of the Uber Server that handles API calls. path (str) Target path to add to the host (e.g. 'v1.2/products'). params (dict) Optional dictionary of parameters to add to the URL. Returns (str) The fully formed URL. """ path = quote(path) params = params or {} if params: path = '/{}?{}'.format(path, urlencode(params)) else: path = '/{}'.format(path) if not host.startswith(http.URL_SCHEME): host = '{}{}'.format(http.URL_SCHEME, host) return urljoin(host, path)
python
def build_url(host, path, params=None): """Build a URL. This method encodes the parameters and adds them to the end of the base URL, then adds scheme and hostname. Parameters host (str) Base URL of the Uber Server that handles API calls. path (str) Target path to add to the host (e.g. 'v1.2/products'). params (dict) Optional dictionary of parameters to add to the URL. Returns (str) The fully formed URL. """ path = quote(path) params = params or {} if params: path = '/{}?{}'.format(path, urlencode(params)) else: path = '/{}'.format(path) if not host.startswith(http.URL_SCHEME): host = '{}{}'.format(http.URL_SCHEME, host) return urljoin(host, path)
[ "def", "build_url", "(", "host", ",", "path", ",", "params", "=", "None", ")", ":", "path", "=", "quote", "(", "path", ")", "params", "=", "params", "or", "{", "}", "if", "params", ":", "path", "=", "'/{}?{}'", ".", "format", "(", "path", ",", "urlencode", "(", "params", ")", ")", "else", ":", "path", "=", "'/{}'", ".", "format", "(", "path", ")", "if", "not", "host", ".", "startswith", "(", "http", ".", "URL_SCHEME", ")", ":", "host", "=", "'{}{}'", ".", "format", "(", "http", ".", "URL_SCHEME", ",", "host", ")", "return", "urljoin", "(", "host", ",", "path", ")" ]
Build a URL. This method encodes the parameters and adds them to the end of the base URL, then adds scheme and hostname. Parameters host (str) Base URL of the Uber Server that handles API calls. path (str) Target path to add to the host (e.g. 'v1.2/products'). params (dict) Optional dictionary of parameters to add to the URL. Returns (str) The fully formed URL.
[ "Build", "a", "URL", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/utils/request.py#L103-L132
17,432
uber/rides-python-sdk
uber_rides/utils/handlers.py
error_handler
def error_handler(response, **kwargs): """Error Handler to surface 4XX and 5XX errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments. Raises ClientError (ApiError) Raised if response contains a 4XX status code. ServerError (ApiError) Raised if response contains a 5XX status code. Returns response (requests.Response) The original HTTP response from the API request. """ try: body = response.json() except ValueError: body = {} status_code = response.status_code message = body.get('message', '') fields = body.get('fields', '') error_message = str(status_code) + ': ' + message + ' ' + str(fields) if 400 <= status_code <= 499: raise ClientError(response, error_message) elif 500 <= status_code <= 599: raise ServerError(response, error_message) return response
python
def error_handler(response, **kwargs): """Error Handler to surface 4XX and 5XX errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments. Raises ClientError (ApiError) Raised if response contains a 4XX status code. ServerError (ApiError) Raised if response contains a 5XX status code. Returns response (requests.Response) The original HTTP response from the API request. """ try: body = response.json() except ValueError: body = {} status_code = response.status_code message = body.get('message', '') fields = body.get('fields', '') error_message = str(status_code) + ': ' + message + ' ' + str(fields) if 400 <= status_code <= 499: raise ClientError(response, error_message) elif 500 <= status_code <= 599: raise ServerError(response, error_message) return response
[ "def", "error_handler", "(", "response", ",", "*", "*", "kwargs", ")", ":", "try", ":", "body", "=", "response", ".", "json", "(", ")", "except", "ValueError", ":", "body", "=", "{", "}", "status_code", "=", "response", ".", "status_code", "message", "=", "body", ".", "get", "(", "'message'", ",", "''", ")", "fields", "=", "body", ".", "get", "(", "'fields'", ",", "''", ")", "error_message", "=", "str", "(", "status_code", ")", "+", "': '", "+", "message", "+", "' '", "+", "str", "(", "fields", ")", "if", "400", "<=", "status_code", "<=", "499", ":", "raise", "ClientError", "(", "response", ",", "error_message", ")", "elif", "500", "<=", "status_code", "<=", "599", ":", "raise", "ServerError", "(", "response", ",", "error_message", ")", "return", "response" ]
Error Handler to surface 4XX and 5XX errors. Attached as a callback hook on the Request object. Parameters response (requests.Response) The HTTP response from an API request. **kwargs Arbitrary keyword arguments. Raises ClientError (ApiError) Raised if response contains a 4XX status code. ServerError (ApiError) Raised if response contains a 5XX status code. Returns response (requests.Response) The original HTTP response from the API request.
[ "Error", "Handler", "to", "surface", "4XX", "and", "5XX", "errors", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/uber_rides/utils/handlers.py#L30-L65
17,433
uber/rides-python-sdk
example/utils.py
import_app_credentials
def import_app_credentials(filename=CREDENTIALS_FILENAME): """Import app credentials from configuration file. Parameters filename (str) Name of configuration file. Returns credentials (dict) All your app credentials and information imported from the configuration file. """ with open(filename, 'r') as config_file: config = safe_load(config_file) client_id = config['client_id'] client_secret = config['client_secret'] redirect_url = config['redirect_url'] config_values = [client_id, client_secret, redirect_url] for value in config_values: if value in DEFAULT_CONFIG_VALUES: exit('Missing credentials in {}'.format(filename)) credentials = { 'client_id': client_id, 'client_secret': client_secret, 'redirect_url': redirect_url, 'scopes': set(config['scopes']), } return credentials
python
def import_app_credentials(filename=CREDENTIALS_FILENAME): """Import app credentials from configuration file. Parameters filename (str) Name of configuration file. Returns credentials (dict) All your app credentials and information imported from the configuration file. """ with open(filename, 'r') as config_file: config = safe_load(config_file) client_id = config['client_id'] client_secret = config['client_secret'] redirect_url = config['redirect_url'] config_values = [client_id, client_secret, redirect_url] for value in config_values: if value in DEFAULT_CONFIG_VALUES: exit('Missing credentials in {}'.format(filename)) credentials = { 'client_id': client_id, 'client_secret': client_secret, 'redirect_url': redirect_url, 'scopes': set(config['scopes']), } return credentials
[ "def", "import_app_credentials", "(", "filename", "=", "CREDENTIALS_FILENAME", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "config_file", ":", "config", "=", "safe_load", "(", "config_file", ")", "client_id", "=", "config", "[", "'client_id'", "]", "client_secret", "=", "config", "[", "'client_secret'", "]", "redirect_url", "=", "config", "[", "'redirect_url'", "]", "config_values", "=", "[", "client_id", ",", "client_secret", ",", "redirect_url", "]", "for", "value", "in", "config_values", ":", "if", "value", "in", "DEFAULT_CONFIG_VALUES", ":", "exit", "(", "'Missing credentials in {}'", ".", "format", "(", "filename", ")", ")", "credentials", "=", "{", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "client_secret", ",", "'redirect_url'", ":", "redirect_url", ",", "'scopes'", ":", "set", "(", "config", "[", "'scopes'", "]", ")", ",", "}", "return", "credentials" ]
Import app credentials from configuration file. Parameters filename (str) Name of configuration file. Returns credentials (dict) All your app credentials and information imported from the configuration file.
[ "Import", "app", "credentials", "from", "configuration", "file", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/utils.py#L98-L130
17,434
uber/rides-python-sdk
example/utils.py
create_uber_client
def create_uber_client(credentials): """Create an UberRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (UberRidesClient) An authorized UberRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), redirect_url=credentials.get('redirect_url'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return UberRidesClient(session, sandbox_mode=True)
python
def create_uber_client(credentials): """Create an UberRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (UberRidesClient) An authorized UberRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), redirect_url=credentials.get('redirect_url'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return UberRidesClient(session, sandbox_mode=True)
[ "def", "create_uber_client", "(", "credentials", ")", ":", "oauth2credential", "=", "OAuth2Credential", "(", "client_id", "=", "credentials", ".", "get", "(", "'client_id'", ")", ",", "access_token", "=", "credentials", ".", "get", "(", "'access_token'", ")", ",", "expires_in_seconds", "=", "credentials", ".", "get", "(", "'expires_in_seconds'", ")", ",", "scopes", "=", "credentials", ".", "get", "(", "'scopes'", ")", ",", "grant_type", "=", "credentials", ".", "get", "(", "'grant_type'", ")", ",", "redirect_url", "=", "credentials", ".", "get", "(", "'redirect_url'", ")", ",", "client_secret", "=", "credentials", ".", "get", "(", "'client_secret'", ")", ",", "refresh_token", "=", "credentials", ".", "get", "(", "'refresh_token'", ")", ",", ")", "session", "=", "Session", "(", "oauth2credential", "=", "oauth2credential", ")", "return", "UberRidesClient", "(", "session", ",", "sandbox_mode", "=", "True", ")" ]
Create an UberRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (UberRidesClient) An authorized UberRidesClient to access API resources.
[ "Create", "an", "UberRidesClient", "from", "OAuth", "2", ".", "0", "credentials", "." ]
76ecd75ab5235d792ec1010e36eca679ba285127
https://github.com/uber/rides-python-sdk/blob/76ecd75ab5235d792ec1010e36eca679ba285127/example/utils.py#L167-L189
17,435
kigawas/eciespy
ecies/__init__.py
encrypt
def encrypt(receiver_pubhex: str, msg: bytes) -> bytes: """ Encrypt with eth public key Parameters ---------- receiver_pubhex: str Receiver's ethereum public key hex string msg: bytes Data to encrypt Returns ------- bytes Encrypted data """ disposable_key = generate_key() receiver_pubkey = hex2pub(receiver_pubhex) aes_key = derive(disposable_key, receiver_pubkey) cipher_text = aes_encrypt(aes_key, msg) return disposable_key.public_key.format(False) + cipher_text
python
def encrypt(receiver_pubhex: str, msg: bytes) -> bytes: """ Encrypt with eth public key Parameters ---------- receiver_pubhex: str Receiver's ethereum public key hex string msg: bytes Data to encrypt Returns ------- bytes Encrypted data """ disposable_key = generate_key() receiver_pubkey = hex2pub(receiver_pubhex) aes_key = derive(disposable_key, receiver_pubkey) cipher_text = aes_encrypt(aes_key, msg) return disposable_key.public_key.format(False) + cipher_text
[ "def", "encrypt", "(", "receiver_pubhex", ":", "str", ",", "msg", ":", "bytes", ")", "->", "bytes", ":", "disposable_key", "=", "generate_key", "(", ")", "receiver_pubkey", "=", "hex2pub", "(", "receiver_pubhex", ")", "aes_key", "=", "derive", "(", "disposable_key", ",", "receiver_pubkey", ")", "cipher_text", "=", "aes_encrypt", "(", "aes_key", ",", "msg", ")", "return", "disposable_key", ".", "public_key", ".", "format", "(", "False", ")", "+", "cipher_text" ]
Encrypt with eth public key Parameters ---------- receiver_pubhex: str Receiver's ethereum public key hex string msg: bytes Data to encrypt Returns ------- bytes Encrypted data
[ "Encrypt", "with", "eth", "public", "key" ]
233f3d7726bf03465a6b2470e83f34cc457eea6c
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/__init__.py#L6-L26
17,436
kigawas/eciespy
ecies/__init__.py
decrypt
def decrypt(receiver_prvhex: str, msg: bytes) -> bytes: """ Decrypt with eth private key Parameters ---------- receiver_pubhex: str Receiver's ethereum private key hex string msg: bytes Data to decrypt Returns ------- bytes Plain text """ pubkey = msg[0:65] # pubkey's length is 65 bytes encrypted = msg[65:] sender_public_key = hex2pub(pubkey.hex()) private_key = hex2prv(receiver_prvhex) aes_key = derive(private_key, sender_public_key) return aes_decrypt(aes_key, encrypted)
python
def decrypt(receiver_prvhex: str, msg: bytes) -> bytes: """ Decrypt with eth private key Parameters ---------- receiver_pubhex: str Receiver's ethereum private key hex string msg: bytes Data to decrypt Returns ------- bytes Plain text """ pubkey = msg[0:65] # pubkey's length is 65 bytes encrypted = msg[65:] sender_public_key = hex2pub(pubkey.hex()) private_key = hex2prv(receiver_prvhex) aes_key = derive(private_key, sender_public_key) return aes_decrypt(aes_key, encrypted)
[ "def", "decrypt", "(", "receiver_prvhex", ":", "str", ",", "msg", ":", "bytes", ")", "->", "bytes", ":", "pubkey", "=", "msg", "[", "0", ":", "65", "]", "# pubkey's length is 65 bytes", "encrypted", "=", "msg", "[", "65", ":", "]", "sender_public_key", "=", "hex2pub", "(", "pubkey", ".", "hex", "(", ")", ")", "private_key", "=", "hex2prv", "(", "receiver_prvhex", ")", "aes_key", "=", "derive", "(", "private_key", ",", "sender_public_key", ")", "return", "aes_decrypt", "(", "aes_key", ",", "encrypted", ")" ]
Decrypt with eth private key Parameters ---------- receiver_pubhex: str Receiver's ethereum private key hex string msg: bytes Data to decrypt Returns ------- bytes Plain text
[ "Decrypt", "with", "eth", "private", "key" ]
233f3d7726bf03465a6b2470e83f34cc457eea6c
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/__init__.py#L29-L50
17,437
kigawas/eciespy
ecies/utils.py
hex2pub
def hex2pub(pub_hex: str) -> PublicKey: """ Convert ethereum hex to EllipticCurvePublicKey The hex should be 65 bytes, but ethereum public key only has 64 bytes So have to add \x04 Parameters ---------- pub_hex: str Ethereum public key hex string Returns ------- coincurve.PublicKey A secp256k1 public key calculated from ethereum public key hex string >>> data = b'0'*32 >>> data_hash = sha256(data) >>> eth_prv = generate_eth_key() >>> cc_prv = hex2prv(eth_prv.to_hex()) >>> eth_prv.sign_msg_hash(data_hash).to_bytes() == cc_prv.sign_recoverable(data) True >>> pubhex = eth_prv.public_key.to_hex() >>> computed_pub = hex2pub(pubhex) >>> computed_pub == cc_prv.public_key True """ uncompressed = decode_hex(pub_hex) if len(uncompressed) == 64: uncompressed = b"\x04" + uncompressed return PublicKey(uncompressed)
python
def hex2pub(pub_hex: str) -> PublicKey: """ Convert ethereum hex to EllipticCurvePublicKey The hex should be 65 bytes, but ethereum public key only has 64 bytes So have to add \x04 Parameters ---------- pub_hex: str Ethereum public key hex string Returns ------- coincurve.PublicKey A secp256k1 public key calculated from ethereum public key hex string >>> data = b'0'*32 >>> data_hash = sha256(data) >>> eth_prv = generate_eth_key() >>> cc_prv = hex2prv(eth_prv.to_hex()) >>> eth_prv.sign_msg_hash(data_hash).to_bytes() == cc_prv.sign_recoverable(data) True >>> pubhex = eth_prv.public_key.to_hex() >>> computed_pub = hex2pub(pubhex) >>> computed_pub == cc_prv.public_key True """ uncompressed = decode_hex(pub_hex) if len(uncompressed) == 64: uncompressed = b"\x04" + uncompressed return PublicKey(uncompressed)
[ "def", "hex2pub", "(", "pub_hex", ":", "str", ")", "->", "PublicKey", ":", "uncompressed", "=", "decode_hex", "(", "pub_hex", ")", "if", "len", "(", "uncompressed", ")", "==", "64", ":", "uncompressed", "=", "b\"\\x04\"", "+", "uncompressed", "return", "PublicKey", "(", "uncompressed", ")" ]
Convert ethereum hex to EllipticCurvePublicKey The hex should be 65 bytes, but ethereum public key only has 64 bytes So have to add \x04 Parameters ---------- pub_hex: str Ethereum public key hex string Returns ------- coincurve.PublicKey A secp256k1 public key calculated from ethereum public key hex string >>> data = b'0'*32 >>> data_hash = sha256(data) >>> eth_prv = generate_eth_key() >>> cc_prv = hex2prv(eth_prv.to_hex()) >>> eth_prv.sign_msg_hash(data_hash).to_bytes() == cc_prv.sign_recoverable(data) True >>> pubhex = eth_prv.public_key.to_hex() >>> computed_pub = hex2pub(pubhex) >>> computed_pub == cc_prv.public_key True
[ "Convert", "ethereum", "hex", "to", "EllipticCurvePublicKey", "The", "hex", "should", "be", "65", "bytes", "but", "ethereum", "public", "key", "only", "has", "64", "bytes", "So", "have", "to", "add", "\\", "x04" ]
233f3d7726bf03465a6b2470e83f34cc457eea6c
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/utils.py#L73-L104
17,438
kigawas/eciespy
ecies/utils.py
aes_encrypt
def aes_encrypt(key: bytes, plain_text: bytes) -> bytes: """ AES-GCM encryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys plain_text: bytes Plain text to encrypt Returns ------- bytes nonce(16 bytes) + tag(16 bytes) + encrypted data """ aes_cipher = AES.new(key, AES_CIPHER_MODE) encrypted, tag = aes_cipher.encrypt_and_digest(plain_text) cipher_text = bytearray() cipher_text.extend(aes_cipher.nonce) cipher_text.extend(tag) cipher_text.extend(encrypted) return bytes(cipher_text)
python
def aes_encrypt(key: bytes, plain_text: bytes) -> bytes: """ AES-GCM encryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys plain_text: bytes Plain text to encrypt Returns ------- bytes nonce(16 bytes) + tag(16 bytes) + encrypted data """ aes_cipher = AES.new(key, AES_CIPHER_MODE) encrypted, tag = aes_cipher.encrypt_and_digest(plain_text) cipher_text = bytearray() cipher_text.extend(aes_cipher.nonce) cipher_text.extend(tag) cipher_text.extend(encrypted) return bytes(cipher_text)
[ "def", "aes_encrypt", "(", "key", ":", "bytes", ",", "plain_text", ":", "bytes", ")", "->", "bytes", ":", "aes_cipher", "=", "AES", ".", "new", "(", "key", ",", "AES_CIPHER_MODE", ")", "encrypted", ",", "tag", "=", "aes_cipher", ".", "encrypt_and_digest", "(", "plain_text", ")", "cipher_text", "=", "bytearray", "(", ")", "cipher_text", ".", "extend", "(", "aes_cipher", ".", "nonce", ")", "cipher_text", ".", "extend", "(", "tag", ")", "cipher_text", ".", "extend", "(", "encrypted", ")", "return", "bytes", "(", "cipher_text", ")" ]
AES-GCM encryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys plain_text: bytes Plain text to encrypt Returns ------- bytes nonce(16 bytes) + tag(16 bytes) + encrypted data
[ "AES", "-", "GCM", "encryption" ]
233f3d7726bf03465a6b2470e83f34cc457eea6c
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/utils.py#L159-L182
17,439
kigawas/eciespy
ecies/utils.py
aes_decrypt
def aes_decrypt(key: bytes, cipher_text: bytes) -> bytes: """ AES-GCM decryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys cipher_text: bytes Encrypted text: nonce(16 bytes) + tag(16 bytes) + encrypted data Returns ------- bytes Plain text >>> data = b'this is test data' >>> key = get_valid_secret() >>> aes_decrypt(key, aes_encrypt(key, data)) == data True >>> import os >>> key = os.urandom(32) >>> aes_decrypt(key, aes_encrypt(key, data)) == data True """ nonce = cipher_text[:16] tag = cipher_text[16:32] ciphered_data = cipher_text[32:] aes_cipher = AES.new(key, AES_CIPHER_MODE, nonce=nonce) return aes_cipher.decrypt_and_verify(ciphered_data, tag)
python
def aes_decrypt(key: bytes, cipher_text: bytes) -> bytes: """ AES-GCM decryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys cipher_text: bytes Encrypted text: nonce(16 bytes) + tag(16 bytes) + encrypted data Returns ------- bytes Plain text >>> data = b'this is test data' >>> key = get_valid_secret() >>> aes_decrypt(key, aes_encrypt(key, data)) == data True >>> import os >>> key = os.urandom(32) >>> aes_decrypt(key, aes_encrypt(key, data)) == data True """ nonce = cipher_text[:16] tag = cipher_text[16:32] ciphered_data = cipher_text[32:] aes_cipher = AES.new(key, AES_CIPHER_MODE, nonce=nonce) return aes_cipher.decrypt_and_verify(ciphered_data, tag)
[ "def", "aes_decrypt", "(", "key", ":", "bytes", ",", "cipher_text", ":", "bytes", ")", "->", "bytes", ":", "nonce", "=", "cipher_text", "[", ":", "16", "]", "tag", "=", "cipher_text", "[", "16", ":", "32", "]", "ciphered_data", "=", "cipher_text", "[", "32", ":", "]", "aes_cipher", "=", "AES", ".", "new", "(", "key", ",", "AES_CIPHER_MODE", ",", "nonce", "=", "nonce", ")", "return", "aes_cipher", ".", "decrypt_and_verify", "(", "ciphered_data", ",", "tag", ")" ]
AES-GCM decryption Parameters ---------- key: bytes AES session key, which derived from two secp256k1 keys cipher_text: bytes Encrypted text: nonce(16 bytes) + tag(16 bytes) + encrypted data Returns ------- bytes Plain text >>> data = b'this is test data' >>> key = get_valid_secret() >>> aes_decrypt(key, aes_encrypt(key, data)) == data True >>> import os >>> key = os.urandom(32) >>> aes_decrypt(key, aes_encrypt(key, data)) == data True
[ "AES", "-", "GCM", "decryption" ]
233f3d7726bf03465a6b2470e83f34cc457eea6c
https://github.com/kigawas/eciespy/blob/233f3d7726bf03465a6b2470e83f34cc457eea6c/ecies/utils.py#L185-L216
17,440
wtolson/pysis
pysis/cubefile.py
CubeFile.apply_scaling
def apply_scaling(self, copy=True): """Scale pixel values to there true DN. :param copy: whether to apply the scalling to a copy of the pixel data and leave the orginial unaffected :returns: a scalled version of the pixel data """ if copy: return self.multiplier * self.data + self.base if self.multiplier != 1: self.data *= self.multiplier if self.base != 0: self.data += self.base return self.data
python
def apply_scaling(self, copy=True): """Scale pixel values to there true DN. :param copy: whether to apply the scalling to a copy of the pixel data and leave the orginial unaffected :returns: a scalled version of the pixel data """ if copy: return self.multiplier * self.data + self.base if self.multiplier != 1: self.data *= self.multiplier if self.base != 0: self.data += self.base return self.data
[ "def", "apply_scaling", "(", "self", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "return", "self", ".", "multiplier", "*", "self", ".", "data", "+", "self", ".", "base", "if", "self", ".", "multiplier", "!=", "1", ":", "self", ".", "data", "*=", "self", ".", "multiplier", "if", "self", ".", "base", "!=", "0", ":", "self", ".", "data", "+=", "self", ".", "base", "return", "self", ".", "data" ]
Scale pixel values to there true DN. :param copy: whether to apply the scalling to a copy of the pixel data and leave the orginial unaffected :returns: a scalled version of the pixel data
[ "Scale", "pixel", "values", "to", "there", "true", "DN", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/cubefile.py#L65-L82
17,441
wtolson/pysis
pysis/cubefile.py
CubeFile.specials_mask
def specials_mask(self): """Create a pixel map for special pixels. :returns: an array where the value is `False` if the pixel is special and `True` otherwise """ mask = self.data >= self.specials['Min'] mask &= self.data <= self.specials['Max'] return mask
python
def specials_mask(self): """Create a pixel map for special pixels. :returns: an array where the value is `False` if the pixel is special and `True` otherwise """ mask = self.data >= self.specials['Min'] mask &= self.data <= self.specials['Max'] return mask
[ "def", "specials_mask", "(", "self", ")", ":", "mask", "=", "self", ".", "data", ">=", "self", ".", "specials", "[", "'Min'", "]", "mask", "&=", "self", ".", "data", "<=", "self", ".", "specials", "[", "'Max'", "]", "return", "mask" ]
Create a pixel map for special pixels. :returns: an array where the value is `False` if the pixel is special and `True` otherwise
[ "Create", "a", "pixel", "map", "for", "special", "pixels", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/cubefile.py#L122-L130
17,442
wtolson/pysis
pysis/cubefile.py
CubeFile.get_image_array
def get_image_array(self): """Create an array for use in making an image. Creates a linear stretch of the image and scales it to between `0` and `255`. `Null`, `Lis` and `Lrs` pixels are set to `0`. `His` and `Hrs` pixels are set to `255`. Usage:: from pysis import CubeFile from PIL import Image # Read in the image and create the image data image = CubeFile.open('test.cub') data = image.get_image_array() # Save the first band to a new file Image.fromarray(data[0]).save('test.png') :returns: A uint8 array of pixel values. """ specials_mask = self.specials_mask() data = self.data.copy() data[specials_mask] -= data[specials_mask].min() data[specials_mask] *= 255 / data[specials_mask].max() data[data == self.specials['His']] = 255 data[data == self.specials['Hrs']] = 255 return data.astype(numpy.uint8)
python
def get_image_array(self): """Create an array for use in making an image. Creates a linear stretch of the image and scales it to between `0` and `255`. `Null`, `Lis` and `Lrs` pixels are set to `0`. `His` and `Hrs` pixels are set to `255`. Usage:: from pysis import CubeFile from PIL import Image # Read in the image and create the image data image = CubeFile.open('test.cub') data = image.get_image_array() # Save the first band to a new file Image.fromarray(data[0]).save('test.png') :returns: A uint8 array of pixel values. """ specials_mask = self.specials_mask() data = self.data.copy() data[specials_mask] -= data[specials_mask].min() data[specials_mask] *= 255 / data[specials_mask].max() data[data == self.specials['His']] = 255 data[data == self.specials['Hrs']] = 255 return data.astype(numpy.uint8)
[ "def", "get_image_array", "(", "self", ")", ":", "specials_mask", "=", "self", ".", "specials_mask", "(", ")", "data", "=", "self", ".", "data", ".", "copy", "(", ")", "data", "[", "specials_mask", "]", "-=", "data", "[", "specials_mask", "]", ".", "min", "(", ")", "data", "[", "specials_mask", "]", "*=", "255", "/", "data", "[", "specials_mask", "]", ".", "max", "(", ")", "data", "[", "data", "==", "self", ".", "specials", "[", "'His'", "]", "]", "=", "255", "data", "[", "data", "==", "self", ".", "specials", "[", "'Hrs'", "]", "]", "=", "255", "return", "data", ".", "astype", "(", "numpy", ".", "uint8", ")" ]
Create an array for use in making an image. Creates a linear stretch of the image and scales it to between `0` and `255`. `Null`, `Lis` and `Lrs` pixels are set to `0`. `His` and `Hrs` pixels are set to `255`. Usage:: from pysis import CubeFile from PIL import Image # Read in the image and create the image data image = CubeFile.open('test.cub') data = image.get_image_array() # Save the first band to a new file Image.fromarray(data[0]).save('test.png') :returns: A uint8 array of pixel values.
[ "Create", "an", "array", "for", "use", "in", "making", "an", "image", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/cubefile.py#L132-L163
17,443
wtolson/pysis
pysis/env.py
check_isis_version
def check_isis_version(major, minor=0, patch=0): """Checks that the current isis version is equal to or above the suplied version.""" if ISIS_VERSION and (major, minor, patch) <= ISIS_VERISON_TUPLE: return msg = 'Version %s.%s.%s of isis required (%s found).' raise VersionError(msg % (major, minor, patch, ISIS_VERSION))
python
def check_isis_version(major, minor=0, patch=0): """Checks that the current isis version is equal to or above the suplied version.""" if ISIS_VERSION and (major, minor, patch) <= ISIS_VERISON_TUPLE: return msg = 'Version %s.%s.%s of isis required (%s found).' raise VersionError(msg % (major, minor, patch, ISIS_VERSION))
[ "def", "check_isis_version", "(", "major", ",", "minor", "=", "0", ",", "patch", "=", "0", ")", ":", "if", "ISIS_VERSION", "and", "(", "major", ",", "minor", ",", "patch", ")", "<=", "ISIS_VERISON_TUPLE", ":", "return", "msg", "=", "'Version %s.%s.%s of isis required (%s found).'", "raise", "VersionError", "(", "msg", "%", "(", "major", ",", "minor", ",", "patch", ",", "ISIS_VERSION", ")", ")" ]
Checks that the current isis version is equal to or above the suplied version.
[ "Checks", "that", "the", "current", "isis", "version", "is", "equal", "to", "or", "above", "the", "suplied", "version", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/env.py#L67-L74
17,444
wtolson/pysis
pysis/env.py
require_isis_version
def require_isis_version(major, minor=0, patch=0): """Decorator that ensures a function is called with a minimum isis version. """ def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): check_isis_version(major, minor, patch) return fn(*args, **kwargs) return wrapper return decorator
python
def require_isis_version(major, minor=0, patch=0): """Decorator that ensures a function is called with a minimum isis version. """ def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): check_isis_version(major, minor, patch) return fn(*args, **kwargs) return wrapper return decorator
[ "def", "require_isis_version", "(", "major", ",", "minor", "=", "0", ",", "patch", "=", "0", ")", ":", "def", "decorator", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "check_isis_version", "(", "major", ",", "minor", ",", "patch", ")", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
Decorator that ensures a function is called with a minimum isis version.
[ "Decorator", "that", "ensures", "a", "function", "is", "called", "with", "a", "minimum", "isis", "version", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/env.py#L77-L86
17,445
wtolson/pysis
pysis/util/file_manipulation.py
write_file_list
def write_file_list(filename, file_list=[], glob=None): """Write a list of files to a file. :param filename: the name of the file to write the list to :param file_list: a list of filenames to write to a file :param glob: if glob is specified, it will ignore file_list and instead create a list of files based on the pattern provide by glob (ex. *.cub) """ if glob: file_list = iglob(glob) with open(filename, 'w') as f: for line in file_list: f.write(line + '\n')
python
def write_file_list(filename, file_list=[], glob=None): """Write a list of files to a file. :param filename: the name of the file to write the list to :param file_list: a list of filenames to write to a file :param glob: if glob is specified, it will ignore file_list and instead create a list of files based on the pattern provide by glob (ex. *.cub) """ if glob: file_list = iglob(glob) with open(filename, 'w') as f: for line in file_list: f.write(line + '\n')
[ "def", "write_file_list", "(", "filename", ",", "file_list", "=", "[", "]", ",", "glob", "=", "None", ")", ":", "if", "glob", ":", "file_list", "=", "iglob", "(", "glob", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "line", "in", "file_list", ":", "f", ".", "write", "(", "line", "+", "'\\n'", ")" ]
Write a list of files to a file. :param filename: the name of the file to write the list to :param file_list: a list of filenames to write to a file :param glob: if glob is specified, it will ignore file_list and instead create a list of files based on the pattern provide by glob (ex. *.cub)
[ "Write", "a", "list", "of", "files", "to", "a", "file", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/util/file_manipulation.py#L11-L26
17,446
wtolson/pysis
pysis/util/file_manipulation.py
file_variations
def file_variations(filename, extensions): """Create a variation of file names. Generate a list of variations on a filename by replacing the extension with a the provided list. :param filename: The original file name to use as a base. :param extensions: A list of file extensions to generate new filenames. """ (label, ext) = splitext(filename) return [label + extention for extention in extensions]
python
def file_variations(filename, extensions): """Create a variation of file names. Generate a list of variations on a filename by replacing the extension with a the provided list. :param filename: The original file name to use as a base. :param extensions: A list of file extensions to generate new filenames. """ (label, ext) = splitext(filename) return [label + extention for extention in extensions]
[ "def", "file_variations", "(", "filename", ",", "extensions", ")", ":", "(", "label", ",", "ext", ")", "=", "splitext", "(", "filename", ")", "return", "[", "label", "+", "extention", "for", "extention", "in", "extensions", "]" ]
Create a variation of file names. Generate a list of variations on a filename by replacing the extension with a the provided list. :param filename: The original file name to use as a base. :param extensions: A list of file extensions to generate new filenames.
[ "Create", "a", "variation", "of", "file", "names", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/util/file_manipulation.py#L29-L40
17,447
wtolson/pysis
pysis/binning/abstract.py
AbstractBinnedKeys.insert
def insert(self, key, value, data={}): """Insert the `key` into a bin based on the given `value`. Optionally, `data` dictionary may be provided to attach arbitrary data to the key. """ if value < self.min_value or value > self.max_value: raise BoundsError('item value out of bounds') item = self.Item(key, value, data) index = self.get_bin_index(value) self.bins[index].append(item)
python
def insert(self, key, value, data={}): """Insert the `key` into a bin based on the given `value`. Optionally, `data` dictionary may be provided to attach arbitrary data to the key. """ if value < self.min_value or value > self.max_value: raise BoundsError('item value out of bounds') item = self.Item(key, value, data) index = self.get_bin_index(value) self.bins[index].append(item)
[ "def", "insert", "(", "self", ",", "key", ",", "value", ",", "data", "=", "{", "}", ")", ":", "if", "value", "<", "self", ".", "min_value", "or", "value", ">", "self", ".", "max_value", ":", "raise", "BoundsError", "(", "'item value out of bounds'", ")", "item", "=", "self", ".", "Item", "(", "key", ",", "value", ",", "data", ")", "index", "=", "self", ".", "get_bin_index", "(", "value", ")", "self", ".", "bins", "[", "index", "]", ".", "append", "(", "item", ")" ]
Insert the `key` into a bin based on the given `value`. Optionally, `data` dictionary may be provided to attach arbitrary data to the key.
[ "Insert", "the", "key", "into", "a", "bin", "based", "on", "the", "given", "value", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/binning/abstract.py#L40-L52
17,448
wtolson/pysis
pysis/binning/abstract.py
AbstractBinnedKeys.iterkeys
def iterkeys(self): """An iterator over the keys of each bin.""" def _iterkeys(bin): for item in bin: yield item.key for bin in self.bins: yield _iterkeys(bin)
python
def iterkeys(self): """An iterator over the keys of each bin.""" def _iterkeys(bin): for item in bin: yield item.key for bin in self.bins: yield _iterkeys(bin)
[ "def", "iterkeys", "(", "self", ")", ":", "def", "_iterkeys", "(", "bin", ")", ":", "for", "item", "in", "bin", ":", "yield", "item", ".", "key", "for", "bin", "in", "self", ".", "bins", ":", "yield", "_iterkeys", "(", "bin", ")" ]
An iterator over the keys of each bin.
[ "An", "iterator", "over", "the", "keys", "of", "each", "bin", "." ]
7b907c8104bddfbb14c603de4d666c2101e1f999
https://github.com/wtolson/pysis/blob/7b907c8104bddfbb14c603de4d666c2101e1f999/pysis/binning/abstract.py#L54-L61
17,449
signaturit/python-sdk
signaturit_sdk/resources/connection.py
Connection.file_request
def file_request(self): """ Request that retrieve a binary file """ response = requests.get( self.__base_url, headers=self.__headers, stream=True) return response.raw.read(), response.headers
python
def file_request(self): """ Request that retrieve a binary file """ response = requests.get( self.__base_url, headers=self.__headers, stream=True) return response.raw.read(), response.headers
[ "def", "file_request", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "self", ".", "__base_url", ",", "headers", "=", "self", ".", "__headers", ",", "stream", "=", "True", ")", "return", "response", ".", "raw", ".", "read", "(", ")", ",", "response", ".", "headers" ]
Request that retrieve a binary file
[ "Request", "that", "retrieve", "a", "binary", "file" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/resources/connection.py#L77-L86
17,450
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_signatures
def get_signatures(self, limit=100, offset=0, conditions={}): """ Get all signatures """ url = self.SIGNS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_signatures(self, limit=100, offset=0, conditions={}): """ Get all signatures """ url = self.SIGNS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_signatures", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SIGNS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "key", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all signatures
[ "Get", "all", "signatures" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L57-L72
17,451
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_signature
def get_signature(self, signature_id): """ Get a concrete Signature @return Signature data """ connection = Connection(self.token) connection.set_url(self.production, self.SIGNS_ID_URL % signature_id) return connection.get_request()
python
def get_signature(self, signature_id): """ Get a concrete Signature @return Signature data """ connection = Connection(self.token) connection.set_url(self.production, self.SIGNS_ID_URL % signature_id) return connection.get_request()
[ "def", "get_signature", "(", "self", ",", "signature_id", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "SIGNS_ID_URL", "%", "signature_id", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get a concrete Signature @return Signature data
[ "Get", "a", "concrete", "Signature" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L74-L82
17,452
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.count_signatures
def count_signatures(self, conditions={}): """ Count all signatures """ url = self.SIGNS_COUNT_URL + '?' for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def count_signatures(self, conditions={}): """ Count all signatures """ url = self.SIGNS_COUNT_URL + '?' for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "count_signatures", "(", "self", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SIGNS_COUNT_URL", "+", "'?'", "for", "key", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Count all signatures
[ "Count", "all", "signatures" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L84-L99
17,453
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.cancel_signature
def cancel_signature(self, signature_id): """ Cancel a concrete Signature @signature_id: Id of signature @return Signature data """ connection = Connection(self.token) connection.set_url(self.production, self.SIGNS_CANCEL_URL % signature_id) return connection.patch_request()
python
def cancel_signature(self, signature_id): """ Cancel a concrete Signature @signature_id: Id of signature @return Signature data """ connection = Connection(self.token) connection.set_url(self.production, self.SIGNS_CANCEL_URL % signature_id) return connection.patch_request()
[ "def", "cancel_signature", "(", "self", ",", "signature_id", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "SIGNS_CANCEL_URL", "%", "signature_id", ")", "return", "connection", ".", "patch_request", "(", ")" ]
Cancel a concrete Signature @signature_id: Id of signature @return Signature data
[ "Cancel", "a", "concrete", "Signature" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L175-L185
17,454
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.send_signature_reminder
def send_signature_reminder(self, signature_id): """ Send a reminder email @signature_id: Id of signature @document_id: Id of document """ connection = Connection(self.token) connection.set_url(self.production, self.SIGNS_SEND_REMINDER_URL % signature_id) return connection.post_request()
python
def send_signature_reminder(self, signature_id): """ Send a reminder email @signature_id: Id of signature @document_id: Id of document """ connection = Connection(self.token) connection.set_url(self.production, self.SIGNS_SEND_REMINDER_URL % signature_id) return connection.post_request()
[ "def", "send_signature_reminder", "(", "self", ",", "signature_id", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "SIGNS_SEND_REMINDER_URL", "%", "signature_id", ")", "return", "connection", ".", "post_request", "(", ")" ]
Send a reminder email @signature_id: Id of signature @document_id: Id of document
[ "Send", "a", "reminder", "email" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L187-L197
17,455
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_branding
def get_branding(self, branding_id): """ Get a concrete branding @branding_id: Id of the branding to fetch @return Branding """ connection = Connection(self.token) connection.set_url(self.production, self.BRANDINGS_ID_URL % branding_id) return connection.get_request()
python
def get_branding(self, branding_id): """ Get a concrete branding @branding_id: Id of the branding to fetch @return Branding """ connection = Connection(self.token) connection.set_url(self.production, self.BRANDINGS_ID_URL % branding_id) return connection.get_request()
[ "def", "get_branding", "(", "self", ",", "branding_id", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "BRANDINGS_ID_URL", "%", "branding_id", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get a concrete branding @branding_id: Id of the branding to fetch @return Branding
[ "Get", "a", "concrete", "branding" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L199-L209
17,456
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_brandings
def get_brandings(self): """ Get all account brandings @return List of brandings """ connection = Connection(self.token) connection.set_url(self.production, self.BRANDINGS_URL) return connection.get_request()
python
def get_brandings(self): """ Get all account brandings @return List of brandings """ connection = Connection(self.token) connection.set_url(self.production, self.BRANDINGS_URL) return connection.get_request()
[ "def", "get_brandings", "(", "self", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "BRANDINGS_URL", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all account brandings @return List of brandings
[ "Get", "all", "account", "brandings" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L211-L220
17,457
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.create_branding
def create_branding(self, params): """ Create a new branding @params: An array of params (all params are optional) - layout: Default color for all application widgets (hex code) - text: Default text color for all application widgets (hex code) - application_texts: A dict with the new text values - sign_button: Text for sign button - send_button: Text for send button - decline_button: Text for decline button: - decline_modal_title: Title for decline modal (when you click decline button) - decline_modal_body: Body for decline modal (when you click decline button) - photo: Photo message text, which tells the user that a photo is needed in the current process - multi_pages: Header of the document, which tells the user the number of pages to sign ex: { 'photo': 'Hey! Take a photo of yourself to validate the process!'} """ connection = Connection(self.token) connection.add_header('Content-Type', 'application/json') connection.set_url(self.production, self.BRANDINGS_URL) connection.add_params(params, json_format=True) return connection.post_request()
python
def create_branding(self, params): """ Create a new branding @params: An array of params (all params are optional) - layout: Default color for all application widgets (hex code) - text: Default text color for all application widgets (hex code) - application_texts: A dict with the new text values - sign_button: Text for sign button - send_button: Text for send button - decline_button: Text for decline button: - decline_modal_title: Title for decline modal (when you click decline button) - decline_modal_body: Body for decline modal (when you click decline button) - photo: Photo message text, which tells the user that a photo is needed in the current process - multi_pages: Header of the document, which tells the user the number of pages to sign ex: { 'photo': 'Hey! Take a photo of yourself to validate the process!'} """ connection = Connection(self.token) connection.add_header('Content-Type', 'application/json') connection.set_url(self.production, self.BRANDINGS_URL) connection.add_params(params, json_format=True) return connection.post_request()
[ "def", "create_branding", "(", "self", ",", "params", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "add_header", "(", "'Content-Type'", ",", "'application/json'", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "BRANDINGS_URL", ")", "connection", ".", "add_params", "(", "params", ",", "json_format", "=", "True", ")", "return", "connection", ".", "post_request", "(", ")" ]
Create a new branding @params: An array of params (all params are optional) - layout: Default color for all application widgets (hex code) - text: Default text color for all application widgets (hex code) - application_texts: A dict with the new text values - sign_button: Text for sign button - send_button: Text for send button - decline_button: Text for decline button: - decline_modal_title: Title for decline modal (when you click decline button) - decline_modal_body: Body for decline modal (when you click decline button) - photo: Photo message text, which tells the user that a photo is needed in the current process - multi_pages: Header of the document, which tells the user the number of pages to sign ex: { 'photo': 'Hey! Take a photo of yourself to validate the process!'}
[ "Create", "a", "new", "branding" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L222-L244
17,458
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.update_branding
def update_branding(self, branding_id, params): """ Update a existing branding @branding_id: Id of the branding to update @params: Same params as method create_branding, see above @return: A dict with updated branding data """ connection = Connection(self.token) connection.add_header('Content-Type', 'application/json') connection.set_url(self.production, self.BRANDINGS_ID_URL % branding_id) connection.add_params(params) return connection.patch_request()
python
def update_branding(self, branding_id, params): """ Update a existing branding @branding_id: Id of the branding to update @params: Same params as method create_branding, see above @return: A dict with updated branding data """ connection = Connection(self.token) connection.add_header('Content-Type', 'application/json') connection.set_url(self.production, self.BRANDINGS_ID_URL % branding_id) connection.add_params(params) return connection.patch_request()
[ "def", "update_branding", "(", "self", ",", "branding_id", ",", "params", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "add_header", "(", "'Content-Type'", ",", "'application/json'", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "BRANDINGS_ID_URL", "%", "branding_id", ")", "connection", ".", "add_params", "(", "params", ")", "return", "connection", ".", "patch_request", "(", ")" ]
Update a existing branding @branding_id: Id of the branding to update @params: Same params as method create_branding, see above @return: A dict with updated branding data
[ "Update", "a", "existing", "branding" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L246-L259
17,459
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_templates
def get_templates(self, limit=100, offset=0): """ Get all account templates """ url = self.TEMPLATES_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_templates(self, limit=100, offset=0): """ Get all account templates """ url = self.TEMPLATES_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_templates", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEMPLATES_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all account templates
[ "Get", "all", "account", "templates" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L261-L271
17,460
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_emails
def get_emails(self, limit=100, offset=0, conditions={}): """ Get all certified emails """ url = self.EMAILS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_emails(self, limit=100, offset=0, conditions={}): """ Get all certified emails """ url = self.EMAILS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_emails", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "EMAILS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "key", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all certified emails
[ "Get", "all", "certified", "emails" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L273-L288
17,461
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.count_emails
def count_emails(self, conditions={}): """ Count all certified emails """ url = self.EMAILS_COUNT_URL + "?" for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) connection.set_url(self.production, url) return connection.get_request()
python
def count_emails(self, conditions={}): """ Count all certified emails """ url = self.EMAILS_COUNT_URL + "?" for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) connection.set_url(self.production, url) return connection.get_request()
[ "def", "count_emails", "(", "self", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "EMAILS_COUNT_URL", "+", "\"?\"", "for", "key", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Count all certified emails
[ "Count", "all", "certified", "emails" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L290-L306
17,462
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_email
def get_email(self, email_id): """ Get a specific email """ connection = Connection(self.token) connection.set_url(self.production, self.EMAILS_ID_URL % email_id) return connection.get_request()
python
def get_email(self, email_id): """ Get a specific email """ connection = Connection(self.token) connection.set_url(self.production, self.EMAILS_ID_URL % email_id) return connection.get_request()
[ "def", "get_email", "(", "self", ",", "email_id", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "EMAILS_ID_URL", "%", "email_id", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get a specific email
[ "Get", "a", "specific", "email" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L308-L316
17,463
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.count_SMS
def count_SMS(self, conditions={}): """ Count all certified sms """ url = self.SMS_COUNT_URL + "?" for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) connection.set_url(self.production, url) return connection.get_request()
python
def count_SMS(self, conditions={}): """ Count all certified sms """ url = self.SMS_COUNT_URL + "?" for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) connection.set_url(self.production, url) return connection.get_request()
[ "def", "count_SMS", "(", "self", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SMS_COUNT_URL", "+", "\"?\"", "for", "key", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Count all certified sms
[ "Count", "all", "certified", "sms" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L377-L393
17,464
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_SMS
def get_SMS(self, limit=100, offset=0, conditions={}): """ Get all certified sms """ url = self.SMS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_SMS(self, limit=100, offset=0, conditions={}): """ Get all certified sms """ url = self.SMS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in conditions.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_SMS", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "conditions", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SMS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "key", ",", "value", "in", "conditions", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all certified sms
[ "Get", "all", "certified", "sms" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L395-L410
17,465
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_single_SMS
def get_single_SMS(self, sms_id): """ Get a specific sms """ connection = Connection(self.token) connection.set_url(self.production, self.SMS_ID_URL % sms_id) return connection.get_request()
python
def get_single_SMS(self, sms_id): """ Get a specific sms """ connection = Connection(self.token) connection.set_url(self.production, self.SMS_ID_URL % sms_id) return connection.get_request()
[ "def", "get_single_SMS", "(", "self", ",", "sms_id", ")", ":", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "SMS_ID_URL", "%", "sms_id", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get a specific sms
[ "Get", "a", "specific", "sms" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L412-L420
17,466
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.create_SMS
def create_SMS(self, files, recipients, body, params={}): """ Create a new certified sms @files Files to send ex: ['/documents/internet_contract.pdf', ... ] @recipients A dictionary with the phone and name of the person you want to sign. Phone must be always with prefix If you wanna send only to one person: - [{"phone": "34123456", "name": "John"}] For multiple recipients, yo need to submit a list of dicts: - [{"email": "34123456, "name": "John"}, {"email":"34654321", "name": "Bob"}] @body Email body @params """ parameters = {} parser = Parser() documents = {} parser.fill_array(documents, files, 'files') recipients = recipients if isinstance(recipients, list) else [recipients] index = 0 for recipient in recipients: parser.fill_array(parameters, recipient, 'recipients[%i]' % index) index += 1 parser.fill_array(parameters, params, '') parameters['body'] = body connection = Connection(self.token) connection.set_url(self.production, self.SMS_URL) connection.add_params(parameters) connection.add_files(documents) return connection.post_request()
python
def create_SMS(self, files, recipients, body, params={}): """ Create a new certified sms @files Files to send ex: ['/documents/internet_contract.pdf', ... ] @recipients A dictionary with the phone and name of the person you want to sign. Phone must be always with prefix If you wanna send only to one person: - [{"phone": "34123456", "name": "John"}] For multiple recipients, yo need to submit a list of dicts: - [{"email": "34123456, "name": "John"}, {"email":"34654321", "name": "Bob"}] @body Email body @params """ parameters = {} parser = Parser() documents = {} parser.fill_array(documents, files, 'files') recipients = recipients if isinstance(recipients, list) else [recipients] index = 0 for recipient in recipients: parser.fill_array(parameters, recipient, 'recipients[%i]' % index) index += 1 parser.fill_array(parameters, params, '') parameters['body'] = body connection = Connection(self.token) connection.set_url(self.production, self.SMS_URL) connection.add_params(parameters) connection.add_files(documents) return connection.post_request()
[ "def", "create_SMS", "(", "self", ",", "files", ",", "recipients", ",", "body", ",", "params", "=", "{", "}", ")", ":", "parameters", "=", "{", "}", "parser", "=", "Parser", "(", ")", "documents", "=", "{", "}", "parser", ".", "fill_array", "(", "documents", ",", "files", ",", "'files'", ")", "recipients", "=", "recipients", "if", "isinstance", "(", "recipients", ",", "list", ")", "else", "[", "recipients", "]", "index", "=", "0", "for", "recipient", "in", "recipients", ":", "parser", ".", "fill_array", "(", "parameters", ",", "recipient", ",", "'recipients[%i]'", "%", "index", ")", "index", "+=", "1", "parser", ".", "fill_array", "(", "parameters", ",", "params", ",", "''", ")", "parameters", "[", "'body'", "]", "=", "body", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "self", ".", "SMS_URL", ")", "connection", ".", "add_params", "(", "parameters", ")", "connection", ".", "add_files", "(", "documents", ")", "return", "connection", ".", "post_request", "(", ")" ]
Create a new certified sms @files Files to send ex: ['/documents/internet_contract.pdf', ... ] @recipients A dictionary with the phone and name of the person you want to sign. Phone must be always with prefix If you wanna send only to one person: - [{"phone": "34123456", "name": "John"}] For multiple recipients, yo need to submit a list of dicts: - [{"email": "34123456, "name": "John"}, {"email":"34654321", "name": "Bob"}] @body Email body @params
[ "Create", "a", "new", "certified", "sms" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L434-L476
17,467
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_users
def get_users(self, limit=100, offset=0): """ Get all users from your current team """ url = self.TEAM_USERS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_users(self, limit=100, offset=0): """ Get all users from your current team """ url = self.TEAM_USERS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_users", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEAM_USERS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all users from your current team
[ "Get", "all", "users", "from", "your", "current", "team" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L478-L487
17,468
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_seats
def get_seats(self, limit=100, offset=0): """ Get all seats from your current team """ url = self.TEAM_SEATS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_seats(self, limit=100, offset=0): """ Get all seats from your current team """ url = self.TEAM_SEATS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_seats", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEAM_SEATS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all seats from your current team
[ "Get", "all", "seats", "from", "your", "current", "team" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L489-L498
17,469
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_groups
def get_groups(self, limit=100, offset=0): """ Get all groups from your current team """ url = self.TEAM_GROUPS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_groups(self, limit=100, offset=0): """ Get all groups from your current team """ url = self.TEAM_GROUPS_URL + "?limit=%s&offset=%s" % (limit, offset) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_groups", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEAM_GROUPS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all groups from your current team
[ "Get", "all", "groups", "from", "your", "current", "team" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L572-L581
17,470
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_subscriptions
def get_subscriptions(self, limit=100, offset=0, params={}): """ Get all subscriptions """ url = self.SUBSCRIPTIONS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in params.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_subscriptions(self, limit=100, offset=0, params={}): """ Get all subscriptions """ url = self.SUBSCRIPTIONS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in params.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_subscriptions", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "params", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SUBSCRIPTIONS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all subscriptions
[ "Get", "all", "subscriptions" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L695-L710
17,471
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.count_subscriptions
def count_subscriptions(self, params={}): """ Count all subscriptions """ url = self.SUBSCRIPTIONS_COUNT_URL + '?' for key, value in params.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def count_subscriptions(self, params={}): """ Count all subscriptions """ url = self.SUBSCRIPTIONS_COUNT_URL + '?' for key, value in params.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "count_subscriptions", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "self", ".", "SUBSCRIPTIONS_COUNT_URL", "+", "'?'", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Count all subscriptions
[ "Count", "all", "subscriptions" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L712-L727
17,472
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_subscription
def get_subscription(self, subscription_id): """ Get single subscription """ url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_subscription(self, subscription_id): """ Get single subscription """ url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_subscription", "(", "self", ",", "subscription_id", ")", ":", "url", "=", "self", ".", "SUBSCRIPTIONS_ID_URL", "%", "subscription_id", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get single subscription
[ "Get", "single", "subscription" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L729-L738
17,473
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.delete_subscription
def delete_subscription(self, subscription_id): """ Delete single subscription """ url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
python
def delete_subscription(self, subscription_id): """ Delete single subscription """ url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
[ "def", "delete_subscription", "(", "self", ",", "subscription_id", ")", ":", "url", "=", "self", ".", "SUBSCRIPTIONS_ID_URL", "%", "subscription_id", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "delete_request", "(", ")" ]
Delete single subscription
[ "Delete", "single", "subscription" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L784-L793
17,474
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_contacts
def get_contacts(self, limit=100, offset=0, params={}): """ Get all account contacts """ url = self.CONTACTS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in params.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_contacts(self, limit=100, offset=0, params={}): """ Get all account contacts """ url = self.CONTACTS_URL + "?limit=%s&offset=%s" % (limit, offset) for key, value in params.items(): if key is 'ids': value = ",".join(value) url += '&%s=%s' % (key, value) connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_contacts", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ",", "params", "=", "{", "}", ")", ":", "url", "=", "self", ".", "CONTACTS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "key", "is", "'ids'", ":", "value", "=", "\",\"", ".", "join", "(", "value", ")", "url", "+=", "'&%s=%s'", "%", "(", "key", ",", "value", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get all account contacts
[ "Get", "all", "account", "contacts" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L795-L810
17,475
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.get_contact
def get_contact(self, contact_id): """ Get single contact """ url = self.CONTACTS_ID_URL % contact_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
python
def get_contact(self, contact_id): """ Get single contact """ url = self.CONTACTS_ID_URL % contact_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.get_request()
[ "def", "get_contact", "(", "self", ",", "contact_id", ")", ":", "url", "=", "self", ".", "CONTACTS_ID_URL", "%", "contact_id", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Get single contact
[ "Get", "single", "contact" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L812-L821
17,476
signaturit/python-sdk
signaturit_sdk/signaturit_client.py
SignaturitClient.delete_contact
def delete_contact(self, contact_id): """ Delete single contact """ url = self.CONTACTS_ID_URL % contact_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
python
def delete_contact(self, contact_id): """ Delete single contact """ url = self.CONTACTS_ID_URL % contact_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
[ "def", "delete_contact", "(", "self", ",", "contact_id", ")", ":", "url", "=", "self", ".", "CONTACTS_ID_URL", "%", "contact_id", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "delete_request", "(", ")" ]
Delete single contact
[ "Delete", "single", "contact" ]
2419c6d9675d901244f807ae360dc58aa46109a9
https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L864-L873
17,477
pygridtools/gridmap
examples/map_reduce.py
main
def main(): """ execute map example """ logging.captureWarnings(True) logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s'), level=logging.INFO) args = [3, 5, 10, 20] # The default queue used by grid_map is all.q. You must specify # the `queue` keyword argument if that is not the name of your queue. intermediate_results = grid_map(computeFactorial, args, quiet=False, max_processes=4, queue='all.q') # Just print the items instead of really reducing. We could always sum them. print("reducing result") for i, ret in enumerate(intermediate_results): print("f({0}) = {1}".format(args[i], ret))
python
def main(): """ execute map example """ logging.captureWarnings(True) logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s'), level=logging.INFO) args = [3, 5, 10, 20] # The default queue used by grid_map is all.q. You must specify # the `queue` keyword argument if that is not the name of your queue. intermediate_results = grid_map(computeFactorial, args, quiet=False, max_processes=4, queue='all.q') # Just print the items instead of really reducing. We could always sum them. print("reducing result") for i, ret in enumerate(intermediate_results): print("f({0}) = {1}".format(args[i], ret))
[ "def", "main", "(", ")", ":", "logging", ".", "captureWarnings", "(", "True", ")", "logging", ".", "basicConfig", "(", "format", "=", "(", "'%(asctime)s - %(name)s - %(levelname)s - '", "+", "'%(message)s'", ")", ",", "level", "=", "logging", ".", "INFO", ")", "args", "=", "[", "3", ",", "5", ",", "10", ",", "20", "]", "# The default queue used by grid_map is all.q. You must specify", "# the `queue` keyword argument if that is not the name of your queue.", "intermediate_results", "=", "grid_map", "(", "computeFactorial", ",", "args", ",", "quiet", "=", "False", ",", "max_processes", "=", "4", ",", "queue", "=", "'all.q'", ")", "# Just print the items instead of really reducing. We could always sum them.", "print", "(", "\"reducing result\"", ")", "for", "i", ",", "ret", "in", "enumerate", "(", "intermediate_results", ")", ":", "print", "(", "\"f({0}) = {1}\"", ".", "format", "(", "args", "[", "i", "]", ",", "ret", ")", ")" ]
execute map example
[ "execute", "map", "example" ]
be4fb1478ab8d19fa3acddecdf1a5d8bd3789127
https://github.com/pygridtools/gridmap/blob/be4fb1478ab8d19fa3acddecdf1a5d8bd3789127/examples/map_reduce.py#L62-L81
17,478
pygridtools/gridmap
examples/manual.py
main
def main(): """ run a set of jobs on cluster """ logging.captureWarnings(True) logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s'), level=logging.INFO) print("=====================================") print("======== Submit and Wait ========") print("=====================================") print("") functionJobs = make_jobs() print("sending function jobs to cluster") print("") job_outputs = process_jobs(functionJobs, max_processes=4) print("results from each job") for (i, result) in enumerate(job_outputs): print("Job {0}- result: {1}".format(i, result))
python
def main(): """ run a set of jobs on cluster """ logging.captureWarnings(True) logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s'), level=logging.INFO) print("=====================================") print("======== Submit and Wait ========") print("=====================================") print("") functionJobs = make_jobs() print("sending function jobs to cluster") print("") job_outputs = process_jobs(functionJobs, max_processes=4) print("results from each job") for (i, result) in enumerate(job_outputs): print("Job {0}- result: {1}".format(i, result))
[ "def", "main", "(", ")", ":", "logging", ".", "captureWarnings", "(", "True", ")", "logging", ".", "basicConfig", "(", "format", "=", "(", "'%(asctime)s - %(name)s - %(levelname)s - '", "+", "'%(message)s'", ")", ",", "level", "=", "logging", ".", "INFO", ")", "print", "(", "\"=====================================\"", ")", "print", "(", "\"======== Submit and Wait ========\"", ")", "print", "(", "\"=====================================\"", ")", "print", "(", "\"\"", ")", "functionJobs", "=", "make_jobs", "(", ")", "print", "(", "\"sending function jobs to cluster\"", ")", "print", "(", "\"\"", ")", "job_outputs", "=", "process_jobs", "(", "functionJobs", ",", "max_processes", "=", "4", ")", "print", "(", "\"results from each job\"", ")", "for", "(", "i", ",", "result", ")", "in", "enumerate", "(", "job_outputs", ")", ":", "print", "(", "\"Job {0}- result: {1}\"", ".", "format", "(", "i", ",", "result", ")", ")" ]
run a set of jobs on cluster
[ "run", "a", "set", "of", "jobs", "on", "cluster" ]
be4fb1478ab8d19fa3acddecdf1a5d8bd3789127
https://github.com/pygridtools/gridmap/blob/be4fb1478ab8d19fa3acddecdf1a5d8bd3789127/examples/manual.py#L86-L109
17,479
jupyterhub/nbgitpuller
nbgitpuller/pull.py
execute_cmd
def execute_cmd(cmd, **kwargs): """ Call given command, yielding output line by line """ yield '$ {}\n'.format(' '.join(cmd)) kwargs['stdout'] = subprocess.PIPE kwargs['stderr'] = subprocess.STDOUT proc = subprocess.Popen(cmd, **kwargs) # Capture output for logging. # Each line will be yielded as text. # This should behave the same as .readline(), but splits on `\r` OR `\n`, # not just `\n`. buf = [] def flush(): line = b''.join(buf).decode('utf8', 'replace') buf[:] = [] return line c_last = '' try: for c in iter(partial(proc.stdout.read, 1), b''): if c_last == b'\r' and buf and c != b'\n': yield flush() buf.append(c) if c == b'\n': yield flush() c_last = c finally: ret = proc.wait() if ret != 0: raise subprocess.CalledProcessError(ret, cmd)
python
def execute_cmd(cmd, **kwargs): """ Call given command, yielding output line by line """ yield '$ {}\n'.format(' '.join(cmd)) kwargs['stdout'] = subprocess.PIPE kwargs['stderr'] = subprocess.STDOUT proc = subprocess.Popen(cmd, **kwargs) # Capture output for logging. # Each line will be yielded as text. # This should behave the same as .readline(), but splits on `\r` OR `\n`, # not just `\n`. buf = [] def flush(): line = b''.join(buf).decode('utf8', 'replace') buf[:] = [] return line c_last = '' try: for c in iter(partial(proc.stdout.read, 1), b''): if c_last == b'\r' and buf and c != b'\n': yield flush() buf.append(c) if c == b'\n': yield flush() c_last = c finally: ret = proc.wait() if ret != 0: raise subprocess.CalledProcessError(ret, cmd)
[ "def", "execute_cmd", "(", "cmd", ",", "*", "*", "kwargs", ")", ":", "yield", "'$ {}\\n'", ".", "format", "(", "' '", ".", "join", "(", "cmd", ")", ")", "kwargs", "[", "'stdout'", "]", "=", "subprocess", ".", "PIPE", "kwargs", "[", "'stderr'", "]", "=", "subprocess", ".", "STDOUT", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "*", "*", "kwargs", ")", "# Capture output for logging.", "# Each line will be yielded as text.", "# This should behave the same as .readline(), but splits on `\\r` OR `\\n`,", "# not just `\\n`.", "buf", "=", "[", "]", "def", "flush", "(", ")", ":", "line", "=", "b''", ".", "join", "(", "buf", ")", ".", "decode", "(", "'utf8'", ",", "'replace'", ")", "buf", "[", ":", "]", "=", "[", "]", "return", "line", "c_last", "=", "''", "try", ":", "for", "c", "in", "iter", "(", "partial", "(", "proc", ".", "stdout", ".", "read", ",", "1", ")", ",", "b''", ")", ":", "if", "c_last", "==", "b'\\r'", "and", "buf", "and", "c", "!=", "b'\\n'", ":", "yield", "flush", "(", ")", "buf", ".", "append", "(", "c", ")", "if", "c", "==", "b'\\n'", ":", "yield", "flush", "(", ")", "c_last", "=", "c", "finally", ":", "ret", "=", "proc", ".", "wait", "(", ")", "if", "ret", "!=", "0", ":", "raise", "subprocess", ".", "CalledProcessError", "(", "ret", ",", "cmd", ")" ]
Call given command, yielding output line by line
[ "Call", "given", "command", "yielding", "output", "line", "by", "line" ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L11-L43
17,480
jupyterhub/nbgitpuller
nbgitpuller/pull.py
main
def main(): """ Synchronizes a github repository with a local repository. """ logging.basicConfig( format='[%(asctime)s] %(levelname)s -- %(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser(description='Synchronizes a github repository with a local repository.') parser.add_argument('git_url', help='Url of the repo to sync') parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?') parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?') args = parser.parse_args() for line in GitPuller( args.git_url, args.branch_name, args.repo_dir ).pull(): print(line)
python
def main(): """ Synchronizes a github repository with a local repository. """ logging.basicConfig( format='[%(asctime)s] %(levelname)s -- %(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser(description='Synchronizes a github repository with a local repository.') parser.add_argument('git_url', help='Url of the repo to sync') parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?') parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?') args = parser.parse_args() for line in GitPuller( args.git_url, args.branch_name, args.repo_dir ).pull(): print(line)
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "'[%(asctime)s] %(levelname)s -- %(message)s'", ",", "level", "=", "logging", ".", "DEBUG", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Synchronizes a github repository with a local repository.'", ")", "parser", ".", "add_argument", "(", "'git_url'", ",", "help", "=", "'Url of the repo to sync'", ")", "parser", ".", "add_argument", "(", "'branch_name'", ",", "default", "=", "'master'", ",", "help", "=", "'Branch of repo to sync'", ",", "nargs", "=", "'?'", ")", "parser", ".", "add_argument", "(", "'repo_dir'", ",", "default", "=", "'.'", ",", "help", "=", "'Path to clone repo under'", ",", "nargs", "=", "'?'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "for", "line", "in", "GitPuller", "(", "args", ".", "git_url", ",", "args", ".", "branch_name", ",", "args", ".", "repo_dir", ")", ".", "pull", "(", ")", ":", "print", "(", "line", ")" ]
Synchronizes a github repository with a local repository.
[ "Synchronizes", "a", "github", "repository", "with", "a", "local", "repository", "." ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L220-L239
17,481
jupyterhub/nbgitpuller
nbgitpuller/pull.py
GitPuller.pull
def pull(self): """ Pull selected repo from a remote git repository, while preserving user changes """ if not os.path.exists(self.repo_dir): yield from self.initialize_repo() else: yield from self.update()
python
def pull(self): """ Pull selected repo from a remote git repository, while preserving user changes """ if not os.path.exists(self.repo_dir): yield from self.initialize_repo() else: yield from self.update()
[ "def", "pull", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "repo_dir", ")", ":", "yield", "from", "self", ".", "initialize_repo", "(", ")", "else", ":", "yield", "from", "self", ".", "update", "(", ")" ]
Pull selected repo from a remote git repository, while preserving user changes
[ "Pull", "selected", "repo", "from", "a", "remote", "git", "repository", "while", "preserving", "user", "changes" ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L73-L81
17,482
jupyterhub/nbgitpuller
nbgitpuller/pull.py
GitPuller.initialize_repo
def initialize_repo(self): """ Clones repository & sets up usernames. """ logging.info('Repo {} doesn\'t exist. Cloning...'.format(self.repo_dir)) clone_args = ['git', 'clone'] if self.depth and self.depth > 0: clone_args.extend(['--depth', str(self.depth)]) clone_args.extend(['--branch', self.branch_name]) clone_args.extend([self.git_url, self.repo_dir]) yield from execute_cmd(clone_args) yield from execute_cmd(['git', 'config', 'user.email', 'nbgitpuller@example.com'], cwd=self.repo_dir) yield from execute_cmd(['git', 'config', 'user.name', 'nbgitpuller'], cwd=self.repo_dir) logging.info('Repo {} initialized'.format(self.repo_dir))
python
def initialize_repo(self): """ Clones repository & sets up usernames. """ logging.info('Repo {} doesn\'t exist. Cloning...'.format(self.repo_dir)) clone_args = ['git', 'clone'] if self.depth and self.depth > 0: clone_args.extend(['--depth', str(self.depth)]) clone_args.extend(['--branch', self.branch_name]) clone_args.extend([self.git_url, self.repo_dir]) yield from execute_cmd(clone_args) yield from execute_cmd(['git', 'config', 'user.email', 'nbgitpuller@example.com'], cwd=self.repo_dir) yield from execute_cmd(['git', 'config', 'user.name', 'nbgitpuller'], cwd=self.repo_dir) logging.info('Repo {} initialized'.format(self.repo_dir))
[ "def", "initialize_repo", "(", "self", ")", ":", "logging", ".", "info", "(", "'Repo {} doesn\\'t exist. Cloning...'", ".", "format", "(", "self", ".", "repo_dir", ")", ")", "clone_args", "=", "[", "'git'", ",", "'clone'", "]", "if", "self", ".", "depth", "and", "self", ".", "depth", ">", "0", ":", "clone_args", ".", "extend", "(", "[", "'--depth'", ",", "str", "(", "self", ".", "depth", ")", "]", ")", "clone_args", ".", "extend", "(", "[", "'--branch'", ",", "self", ".", "branch_name", "]", ")", "clone_args", ".", "extend", "(", "[", "self", ".", "git_url", ",", "self", ".", "repo_dir", "]", ")", "yield", "from", "execute_cmd", "(", "clone_args", ")", "yield", "from", "execute_cmd", "(", "[", "'git'", ",", "'config'", ",", "'user.email'", ",", "'nbgitpuller@example.com'", "]", ",", "cwd", "=", "self", ".", "repo_dir", ")", "yield", "from", "execute_cmd", "(", "[", "'git'", ",", "'config'", ",", "'user.name'", ",", "'nbgitpuller'", "]", ",", "cwd", "=", "self", ".", "repo_dir", ")", "logging", ".", "info", "(", "'Repo {} initialized'", ".", "format", "(", "self", ".", "repo_dir", ")", ")" ]
Clones repository & sets up usernames.
[ "Clones", "repository", "&", "sets", "up", "usernames", "." ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L83-L97
17,483
jupyterhub/nbgitpuller
nbgitpuller/pull.py
GitPuller.repo_is_dirty
def repo_is_dirty(self): """ Return true if repo is dirty """ try: subprocess.check_call(['git', 'diff-files', '--quiet'], cwd=self.repo_dir) # Return code is 0 return False except subprocess.CalledProcessError: return True
python
def repo_is_dirty(self): """ Return true if repo is dirty """ try: subprocess.check_call(['git', 'diff-files', '--quiet'], cwd=self.repo_dir) # Return code is 0 return False except subprocess.CalledProcessError: return True
[ "def", "repo_is_dirty", "(", "self", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'diff-files'", ",", "'--quiet'", "]", ",", "cwd", "=", "self", ".", "repo_dir", ")", "# Return code is 0", "return", "False", "except", "subprocess", ".", "CalledProcessError", ":", "return", "True" ]
Return true if repo is dirty
[ "Return", "true", "if", "repo", "is", "dirty" ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L116-L125
17,484
jupyterhub/nbgitpuller
nbgitpuller/pull.py
GitPuller.find_upstream_changed
def find_upstream_changed(self, kind): """ Return list of files that have been changed upstream belonging to a particular kind of change """ output = subprocess.check_output([ 'git', 'log', '{}..origin/{}'.format(self.branch_name, self.branch_name), '--oneline', '--name-status' ], cwd=self.repo_dir).decode() files = [] for line in output.split('\n'): if line.startswith(kind): files.append(os.path.join(self.repo_dir, line.split('\t', 1)[1])) return files
python
def find_upstream_changed(self, kind): """ Return list of files that have been changed upstream belonging to a particular kind of change """ output = subprocess.check_output([ 'git', 'log', '{}..origin/{}'.format(self.branch_name, self.branch_name), '--oneline', '--name-status' ], cwd=self.repo_dir).decode() files = [] for line in output.split('\n'): if line.startswith(kind): files.append(os.path.join(self.repo_dir, line.split('\t', 1)[1])) return files
[ "def", "find_upstream_changed", "(", "self", ",", "kind", ")", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "'git'", ",", "'log'", ",", "'{}..origin/{}'", ".", "format", "(", "self", ".", "branch_name", ",", "self", ".", "branch_name", ")", ",", "'--oneline'", ",", "'--name-status'", "]", ",", "cwd", "=", "self", ".", "repo_dir", ")", ".", "decode", "(", ")", "files", "=", "[", "]", "for", "line", "in", "output", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "kind", ")", ":", "files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "repo_dir", ",", "line", ".", "split", "(", "'\\t'", ",", "1", ")", "[", "1", "]", ")", ")", "return", "files" ]
Return list of files that have been changed upstream belonging to a particular kind of change
[ "Return", "list", "of", "files", "that", "have", "been", "changed", "upstream", "belonging", "to", "a", "particular", "kind", "of", "change" ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L133-L146
17,485
jupyterhub/nbgitpuller
nbgitpuller/pull.py
GitPuller.rename_local_untracked
def rename_local_untracked(self): """ Rename local untracked files that would require pulls """ # Find what files have been added! new_upstream_files = self.find_upstream_changed('A') for f in new_upstream_files: if os.path.exists(f): # If there's a file extension, put the timestamp before that ts = datetime.datetime.now().strftime('__%Y%m%d%H%M%S') path_head, path_tail = os.path.split(f) path_tail = ts.join(os.path.splitext(path_tail)) new_file_name = os.path.join(path_head, path_tail) os.rename(f, new_file_name) yield 'Renamed {} to {} to avoid conflict with upstream'.format(f, new_file_name)
python
def rename_local_untracked(self): """ Rename local untracked files that would require pulls """ # Find what files have been added! new_upstream_files = self.find_upstream_changed('A') for f in new_upstream_files: if os.path.exists(f): # If there's a file extension, put the timestamp before that ts = datetime.datetime.now().strftime('__%Y%m%d%H%M%S') path_head, path_tail = os.path.split(f) path_tail = ts.join(os.path.splitext(path_tail)) new_file_name = os.path.join(path_head, path_tail) os.rename(f, new_file_name) yield 'Renamed {} to {} to avoid conflict with upstream'.format(f, new_file_name)
[ "def", "rename_local_untracked", "(", "self", ")", ":", "# Find what files have been added!", "new_upstream_files", "=", "self", ".", "find_upstream_changed", "(", "'A'", ")", "for", "f", "in", "new_upstream_files", ":", "if", "os", ".", "path", ".", "exists", "(", "f", ")", ":", "# If there's a file extension, put the timestamp before that", "ts", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'__%Y%m%d%H%M%S'", ")", "path_head", ",", "path_tail", "=", "os", ".", "path", ".", "split", "(", "f", ")", "path_tail", "=", "ts", ".", "join", "(", "os", ".", "path", ".", "splitext", "(", "path_tail", ")", ")", "new_file_name", "=", "os", ".", "path", ".", "join", "(", "path_head", ",", "path_tail", ")", "os", ".", "rename", "(", "f", ",", "new_file_name", ")", "yield", "'Renamed {} to {} to avoid conflict with upstream'", ".", "format", "(", "f", ",", "new_file_name", ")" ]
Rename local untracked files that would require pulls
[ "Rename", "local", "untracked", "files", "that", "would", "require", "pulls" ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L172-L186
17,486
jupyterhub/nbgitpuller
nbgitpuller/pull.py
GitPuller.update
def update(self): """ Do the pulling if necessary """ # Fetch remotes, so we know we're dealing with latest remote yield from self.update_remotes() # Rename local untracked files that might be overwritten by pull yield from self.rename_local_untracked() # Reset local files that have been deleted. We don't actually expect users to # delete something that's present upstream and expect to keep it. This prevents # unnecessary conflicts, and also allows users to click the link again to get # a fresh copy of a file they might have screwed up. yield from self.reset_deleted_files() # If there are local changes, make a commit so we can do merges when pulling # We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false # positive, returning True even when there are no local changes (git diff-files seems to return # bogus output?). While ideally that would not happen, allowing empty commits keeps us # resilient to that issue. if self.repo_is_dirty(): yield from self.ensure_lock() yield from execute_cmd(['git', 'commit', '-am', 'WIP', '--allow-empty'], cwd=self.repo_dir) # Merge master into local! yield from self.ensure_lock() yield from execute_cmd(['git', 'merge', '-Xours', 'origin/{}'.format(self.branch_name)], cwd=self.repo_dir)
python
def update(self): """ Do the pulling if necessary """ # Fetch remotes, so we know we're dealing with latest remote yield from self.update_remotes() # Rename local untracked files that might be overwritten by pull yield from self.rename_local_untracked() # Reset local files that have been deleted. We don't actually expect users to # delete something that's present upstream and expect to keep it. This prevents # unnecessary conflicts, and also allows users to click the link again to get # a fresh copy of a file they might have screwed up. yield from self.reset_deleted_files() # If there are local changes, make a commit so we can do merges when pulling # We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false # positive, returning True even when there are no local changes (git diff-files seems to return # bogus output?). While ideally that would not happen, allowing empty commits keeps us # resilient to that issue. if self.repo_is_dirty(): yield from self.ensure_lock() yield from execute_cmd(['git', 'commit', '-am', 'WIP', '--allow-empty'], cwd=self.repo_dir) # Merge master into local! yield from self.ensure_lock() yield from execute_cmd(['git', 'merge', '-Xours', 'origin/{}'.format(self.branch_name)], cwd=self.repo_dir)
[ "def", "update", "(", "self", ")", ":", "# Fetch remotes, so we know we're dealing with latest remote", "yield", "from", "self", ".", "update_remotes", "(", ")", "# Rename local untracked files that might be overwritten by pull", "yield", "from", "self", ".", "rename_local_untracked", "(", ")", "# Reset local files that have been deleted. We don't actually expect users to", "# delete something that's present upstream and expect to keep it. This prevents", "# unnecessary conflicts, and also allows users to click the link again to get", "# a fresh copy of a file they might have screwed up.", "yield", "from", "self", ".", "reset_deleted_files", "(", ")", "# If there are local changes, make a commit so we can do merges when pulling", "# We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false", "# positive, returning True even when there are no local changes (git diff-files seems to return", "# bogus output?). While ideally that would not happen, allowing empty commits keeps us", "# resilient to that issue.", "if", "self", ".", "repo_is_dirty", "(", ")", ":", "yield", "from", "self", ".", "ensure_lock", "(", ")", "yield", "from", "execute_cmd", "(", "[", "'git'", ",", "'commit'", ",", "'-am'", ",", "'WIP'", ",", "'--allow-empty'", "]", ",", "cwd", "=", "self", ".", "repo_dir", ")", "# Merge master into local!", "yield", "from", "self", ".", "ensure_lock", "(", ")", "yield", "from", "execute_cmd", "(", "[", "'git'", ",", "'merge'", ",", "'-Xours'", ",", "'origin/{}'", ".", "format", "(", "self", ".", "branch_name", ")", "]", ",", "cwd", "=", "self", ".", "repo_dir", ")" ]
Do the pulling if necessary
[ "Do", "the", "pulling", "if", "necessary" ]
30df8d548078c58665ce0ae920308f991122abe3
https://github.com/jupyterhub/nbgitpuller/blob/30df8d548078c58665ce0ae920308f991122abe3/nbgitpuller/pull.py#L189-L216
17,487
jcrobak/parquet-python
parquet/__init__.py
_get_footer_size
def _get_footer_size(file_obj): """Read the footer size in bytes, which is serialized as little endian.""" file_obj.seek(-8, 2) tup = struct.unpack(b"<i", file_obj.read(4)) return tup[0]
python
def _get_footer_size(file_obj): """Read the footer size in bytes, which is serialized as little endian.""" file_obj.seek(-8, 2) tup = struct.unpack(b"<i", file_obj.read(4)) return tup[0]
[ "def", "_get_footer_size", "(", "file_obj", ")", ":", "file_obj", ".", "seek", "(", "-", "8", ",", "2", ")", "tup", "=", "struct", ".", "unpack", "(", "b\"<i\"", ",", "file_obj", ".", "read", "(", "4", ")", ")", "return", "tup", "[", "0", "]" ]
Read the footer size in bytes, which is serialized as little endian.
[ "Read", "the", "footer", "size", "in", "bytes", "which", "is", "serialized", "as", "little", "endian", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L64-L68
17,488
jcrobak/parquet-python
parquet/__init__.py
_read_footer
def _read_footer(file_obj): """Read the footer from the given file object and returns a FileMetaData object. This method assumes that the fo references a valid parquet file. """ footer_size = _get_footer_size(file_obj) if logger.isEnabledFor(logging.DEBUG): logger.debug("Footer size in bytes: %s", footer_size) file_obj.seek(-(8 + footer_size), 2) # seek to beginning of footer tin = TFileTransport(file_obj) pin = TCompactProtocolFactory().get_protocol(tin) fmd = parquet_thrift.FileMetaData() fmd.read(pin) return fmd
python
def _read_footer(file_obj): """Read the footer from the given file object and returns a FileMetaData object. This method assumes that the fo references a valid parquet file. """ footer_size = _get_footer_size(file_obj) if logger.isEnabledFor(logging.DEBUG): logger.debug("Footer size in bytes: %s", footer_size) file_obj.seek(-(8 + footer_size), 2) # seek to beginning of footer tin = TFileTransport(file_obj) pin = TCompactProtocolFactory().get_protocol(tin) fmd = parquet_thrift.FileMetaData() fmd.read(pin) return fmd
[ "def", "_read_footer", "(", "file_obj", ")", ":", "footer_size", "=", "_get_footer_size", "(", "file_obj", ")", "if", "logger", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "logger", ".", "debug", "(", "\"Footer size in bytes: %s\"", ",", "footer_size", ")", "file_obj", ".", "seek", "(", "-", "(", "8", "+", "footer_size", ")", ",", "2", ")", "# seek to beginning of footer", "tin", "=", "TFileTransport", "(", "file_obj", ")", "pin", "=", "TCompactProtocolFactory", "(", ")", ".", "get_protocol", "(", "tin", ")", "fmd", "=", "parquet_thrift", ".", "FileMetaData", "(", ")", "fmd", ".", "read", "(", "pin", ")", "return", "fmd" ]
Read the footer from the given file object and returns a FileMetaData object. This method assumes that the fo references a valid parquet file.
[ "Read", "the", "footer", "from", "the", "given", "file", "object", "and", "returns", "a", "FileMetaData", "object", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L71-L84
17,489
jcrobak/parquet-python
parquet/__init__.py
_read_page_header
def _read_page_header(file_obj): """Read the page_header from the given fo.""" tin = TFileTransport(file_obj) pin = TCompactProtocolFactory().get_protocol(tin) page_header = parquet_thrift.PageHeader() page_header.read(pin) return page_header
python
def _read_page_header(file_obj): """Read the page_header from the given fo.""" tin = TFileTransport(file_obj) pin = TCompactProtocolFactory().get_protocol(tin) page_header = parquet_thrift.PageHeader() page_header.read(pin) return page_header
[ "def", "_read_page_header", "(", "file_obj", ")", ":", "tin", "=", "TFileTransport", "(", "file_obj", ")", "pin", "=", "TCompactProtocolFactory", "(", ")", ".", "get_protocol", "(", "tin", ")", "page_header", "=", "parquet_thrift", ".", "PageHeader", "(", ")", "page_header", ".", "read", "(", "pin", ")", "return", "page_header" ]
Read the page_header from the given fo.
[ "Read", "the", "page_header", "from", "the", "given", "fo", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L87-L93
17,490
jcrobak/parquet-python
parquet/__init__.py
read_footer
def read_footer(filename): """Read the footer and return the FileMetaData for the specified filename.""" with open(filename, 'rb') as file_obj: if not _check_header_magic_bytes(file_obj) or \ not _check_footer_magic_bytes(file_obj): raise ParquetFormatException("{0} is not a valid parquet file " "(missing magic bytes)" .format(filename)) return _read_footer(file_obj)
python
def read_footer(filename): """Read the footer and return the FileMetaData for the specified filename.""" with open(filename, 'rb') as file_obj: if not _check_header_magic_bytes(file_obj) or \ not _check_footer_magic_bytes(file_obj): raise ParquetFormatException("{0} is not a valid parquet file " "(missing magic bytes)" .format(filename)) return _read_footer(file_obj)
[ "def", "read_footer", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "file_obj", ":", "if", "not", "_check_header_magic_bytes", "(", "file_obj", ")", "or", "not", "_check_footer_magic_bytes", "(", "file_obj", ")", ":", "raise", "ParquetFormatException", "(", "\"{0} is not a valid parquet file \"", "\"(missing magic bytes)\"", ".", "format", "(", "filename", ")", ")", "return", "_read_footer", "(", "file_obj", ")" ]
Read the footer and return the FileMetaData for the specified filename.
[ "Read", "the", "footer", "and", "return", "the", "FileMetaData", "for", "the", "specified", "filename", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L96-L104
17,491
jcrobak/parquet-python
parquet/__init__.py
_get_offset
def _get_offset(cmd): """Return the offset into the cmd based upon if it's a dictionary page or a data page.""" dict_offset = cmd.dictionary_page_offset data_offset = cmd.data_page_offset if dict_offset is None or data_offset < dict_offset: return data_offset return dict_offset
python
def _get_offset(cmd): """Return the offset into the cmd based upon if it's a dictionary page or a data page.""" dict_offset = cmd.dictionary_page_offset data_offset = cmd.data_page_offset if dict_offset is None or data_offset < dict_offset: return data_offset return dict_offset
[ "def", "_get_offset", "(", "cmd", ")", ":", "dict_offset", "=", "cmd", ".", "dictionary_page_offset", "data_offset", "=", "cmd", ".", "data_page_offset", "if", "dict_offset", "is", "None", "or", "data_offset", "<", "dict_offset", ":", "return", "data_offset", "return", "dict_offset" ]
Return the offset into the cmd based upon if it's a dictionary page or a data page.
[ "Return", "the", "offset", "into", "the", "cmd", "based", "upon", "if", "it", "s", "a", "dictionary", "page", "or", "a", "data", "page", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L115-L121
17,492
jcrobak/parquet-python
parquet/__init__.py
_read_data
def _read_data(file_obj, fo_encoding, value_count, bit_width): """Read data from the file-object using the given encoding. The data could be definition levels, repetition levels, or actual values. """ vals = [] if fo_encoding == parquet_thrift.Encoding.RLE: seen = 0 while seen < value_count: values = encoding.read_rle_bit_packed_hybrid(file_obj, bit_width) if values is None: break # EOF was reached. vals += values seen += len(values) elif fo_encoding == parquet_thrift.Encoding.BIT_PACKED: raise NotImplementedError("Bit packing not yet supported") return vals
python
def _read_data(file_obj, fo_encoding, value_count, bit_width): """Read data from the file-object using the given encoding. The data could be definition levels, repetition levels, or actual values. """ vals = [] if fo_encoding == parquet_thrift.Encoding.RLE: seen = 0 while seen < value_count: values = encoding.read_rle_bit_packed_hybrid(file_obj, bit_width) if values is None: break # EOF was reached. vals += values seen += len(values) elif fo_encoding == parquet_thrift.Encoding.BIT_PACKED: raise NotImplementedError("Bit packing not yet supported") return vals
[ "def", "_read_data", "(", "file_obj", ",", "fo_encoding", ",", "value_count", ",", "bit_width", ")", ":", "vals", "=", "[", "]", "if", "fo_encoding", "==", "parquet_thrift", ".", "Encoding", ".", "RLE", ":", "seen", "=", "0", "while", "seen", "<", "value_count", ":", "values", "=", "encoding", ".", "read_rle_bit_packed_hybrid", "(", "file_obj", ",", "bit_width", ")", "if", "values", "is", "None", ":", "break", "# EOF was reached.", "vals", "+=", "values", "seen", "+=", "len", "(", "values", ")", "elif", "fo_encoding", "==", "parquet_thrift", ".", "Encoding", ".", "BIT_PACKED", ":", "raise", "NotImplementedError", "(", "\"Bit packing not yet supported\"", ")", "return", "vals" ]
Read data from the file-object using the given encoding. The data could be definition levels, repetition levels, or actual values.
[ "Read", "data", "from", "the", "file", "-", "object", "using", "the", "given", "encoding", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L258-L275
17,493
jcrobak/parquet-python
parquet/__init__.py
_read_dictionary_page
def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata): """Read a page containing dictionary data. Consumes data using the plain encoding and returns an array of values. """ raw_bytes = _read_page(file_obj, page_header, column_metadata) io_obj = io.BytesIO(raw_bytes) values = encoding.read_plain( io_obj, column_metadata.type, page_header.dictionary_page_header.num_values ) # convert the values once, if the dictionary is associated with a converted_type. schema_element = schema_helper.schema_element(column_metadata.path_in_schema[-1]) return convert_column(values, schema_element) if schema_element.converted_type is not None else values
python
def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata): """Read a page containing dictionary data. Consumes data using the plain encoding and returns an array of values. """ raw_bytes = _read_page(file_obj, page_header, column_metadata) io_obj = io.BytesIO(raw_bytes) values = encoding.read_plain( io_obj, column_metadata.type, page_header.dictionary_page_header.num_values ) # convert the values once, if the dictionary is associated with a converted_type. schema_element = schema_helper.schema_element(column_metadata.path_in_schema[-1]) return convert_column(values, schema_element) if schema_element.converted_type is not None else values
[ "def", "_read_dictionary_page", "(", "file_obj", ",", "schema_helper", ",", "page_header", ",", "column_metadata", ")", ":", "raw_bytes", "=", "_read_page", "(", "file_obj", ",", "page_header", ",", "column_metadata", ")", "io_obj", "=", "io", ".", "BytesIO", "(", "raw_bytes", ")", "values", "=", "encoding", ".", "read_plain", "(", "io_obj", ",", "column_metadata", ".", "type", ",", "page_header", ".", "dictionary_page_header", ".", "num_values", ")", "# convert the values once, if the dictionary is associated with a converted_type.", "schema_element", "=", "schema_helper", ".", "schema_element", "(", "column_metadata", ".", "path_in_schema", "[", "-", "1", "]", ")", "return", "convert_column", "(", "values", ",", "schema_element", ")", "if", "schema_element", ".", "converted_type", "is", "not", "None", "else", "values" ]
Read a page containing dictionary data. Consumes data using the plain encoding and returns an array of values.
[ "Read", "a", "page", "containing", "dictionary", "data", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L386-L400
17,494
jcrobak/parquet-python
parquet/__init__.py
_dump
def _dump(file_obj, options, out=sys.stdout): """Dump to fo with given options.""" # writer and keys are lazily loaded. We don't know the keys until we have # the first item. And we need the keys for the csv writer. total_count = 0 writer = None keys = None for row in DictReader(file_obj, options.col): if not keys: keys = row.keys() if not writer: writer = csv.DictWriter(out, keys, delimiter=u'\t', quotechar=u'\'', quoting=csv.QUOTE_MINIMAL) \ if options.format == 'csv' \ else JsonWriter(out) if options.format == 'json' \ else None if total_count == 0 and options.format == "csv" and not options.no_headers: writer.writeheader() if options.limit != -1 and total_count >= options.limit: return row_unicode = {k: v.decode("utf-8") if isinstance(v, bytes) else v for k, v in row.items()} writer.writerow(row_unicode) total_count += 1
python
def _dump(file_obj, options, out=sys.stdout): """Dump to fo with given options.""" # writer and keys are lazily loaded. We don't know the keys until we have # the first item. And we need the keys for the csv writer. total_count = 0 writer = None keys = None for row in DictReader(file_obj, options.col): if not keys: keys = row.keys() if not writer: writer = csv.DictWriter(out, keys, delimiter=u'\t', quotechar=u'\'', quoting=csv.QUOTE_MINIMAL) \ if options.format == 'csv' \ else JsonWriter(out) if options.format == 'json' \ else None if total_count == 0 and options.format == "csv" and not options.no_headers: writer.writeheader() if options.limit != -1 and total_count >= options.limit: return row_unicode = {k: v.decode("utf-8") if isinstance(v, bytes) else v for k, v in row.items()} writer.writerow(row_unicode) total_count += 1
[ "def", "_dump", "(", "file_obj", ",", "options", ",", "out", "=", "sys", ".", "stdout", ")", ":", "# writer and keys are lazily loaded. We don't know the keys until we have", "# the first item. And we need the keys for the csv writer.", "total_count", "=", "0", "writer", "=", "None", "keys", "=", "None", "for", "row", "in", "DictReader", "(", "file_obj", ",", "options", ".", "col", ")", ":", "if", "not", "keys", ":", "keys", "=", "row", ".", "keys", "(", ")", "if", "not", "writer", ":", "writer", "=", "csv", ".", "DictWriter", "(", "out", ",", "keys", ",", "delimiter", "=", "u'\\t'", ",", "quotechar", "=", "u'\\''", ",", "quoting", "=", "csv", ".", "QUOTE_MINIMAL", ")", "if", "options", ".", "format", "==", "'csv'", "else", "JsonWriter", "(", "out", ")", "if", "options", ".", "format", "==", "'json'", "else", "None", "if", "total_count", "==", "0", "and", "options", ".", "format", "==", "\"csv\"", "and", "not", "options", ".", "no_headers", ":", "writer", ".", "writeheader", "(", ")", "if", "options", ".", "limit", "!=", "-", "1", "and", "total_count", ">=", "options", ".", "limit", ":", "return", "row_unicode", "=", "{", "k", ":", "v", ".", "decode", "(", "\"utf-8\"", ")", "if", "isinstance", "(", "v", ",", "bytes", ")", "else", "v", "for", "k", ",", "v", "in", "row", ".", "items", "(", ")", "}", "writer", ".", "writerow", "(", "row_unicode", ")", "total_count", "+=", "1" ]
Dump to fo with given options.
[ "Dump", "to", "fo", "with", "given", "options", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L504-L525
17,495
jcrobak/parquet-python
parquet/__init__.py
dump
def dump(filename, options, out=sys.stdout): """Dump parquet file with given filename using options to `out`.""" with open(filename, 'rb') as file_obj: return _dump(file_obj, options=options, out=out)
python
def dump(filename, options, out=sys.stdout): """Dump parquet file with given filename using options to `out`.""" with open(filename, 'rb') as file_obj: return _dump(file_obj, options=options, out=out)
[ "def", "dump", "(", "filename", ",", "options", ",", "out", "=", "sys", ".", "stdout", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "file_obj", ":", "return", "_dump", "(", "file_obj", ",", "options", "=", "options", ",", "out", "=", "out", ")" ]
Dump parquet file with given filename using options to `out`.
[ "Dump", "parquet", "file", "with", "given", "filename", "using", "options", "to", "out", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L528-L531
17,496
jcrobak/parquet-python
parquet/__init__.py
JsonWriter.writerow
def writerow(self, row): """Write a single row.""" json_text = json.dumps(row) if isinstance(json_text, bytes): json_text = json_text.decode('utf-8') self._out.write(json_text) self._out.write(u'\n')
python
def writerow(self, row): """Write a single row.""" json_text = json.dumps(row) if isinstance(json_text, bytes): json_text = json_text.decode('utf-8') self._out.write(json_text) self._out.write(u'\n')
[ "def", "writerow", "(", "self", ",", "row", ")", ":", "json_text", "=", "json", ".", "dumps", "(", "row", ")", "if", "isinstance", "(", "json_text", ",", "bytes", ")", ":", "json_text", "=", "json_text", ".", "decode", "(", "'utf-8'", ")", "self", ".", "_out", ".", "write", "(", "json_text", ")", "self", ".", "_out", ".", "write", "(", "u'\\n'", ")" ]
Write a single row.
[ "Write", "a", "single", "row", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/__init__.py#L495-L501
17,497
jcrobak/parquet-python
parquet/encoding.py
read_plain_boolean
def read_plain_boolean(file_obj, count): """Read `count` booleans using the plain encoding.""" # for bit packed, the count is stored shifted up. But we want to pass in a count, # so we shift up. # bit width is 1 for a single-bit boolean. return read_bitpacked(file_obj, count << 1, 1, logger.isEnabledFor(logging.DEBUG))
python
def read_plain_boolean(file_obj, count): """Read `count` booleans using the plain encoding.""" # for bit packed, the count is stored shifted up. But we want to pass in a count, # so we shift up. # bit width is 1 for a single-bit boolean. return read_bitpacked(file_obj, count << 1, 1, logger.isEnabledFor(logging.DEBUG))
[ "def", "read_plain_boolean", "(", "file_obj", ",", "count", ")", ":", "# for bit packed, the count is stored shifted up. But we want to pass in a count,", "# so we shift up.", "# bit width is 1 for a single-bit boolean.", "return", "read_bitpacked", "(", "file_obj", ",", "count", "<<", "1", ",", "1", ",", "logger", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ")" ]
Read `count` booleans using the plain encoding.
[ "Read", "count", "booleans", "using", "the", "plain", "encoding", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L28-L33
17,498
jcrobak/parquet-python
parquet/encoding.py
read_plain_int32
def read_plain_int32(file_obj, count): """Read `count` 32-bit ints using the plain encoding.""" length = 4 * count data = file_obj.read(length) if len(data) != length: raise EOFError("Expected {} bytes but got {} bytes".format(length, len(data))) res = struct.unpack("<{}i".format(count).encode("utf-8"), data) return res
python
def read_plain_int32(file_obj, count): """Read `count` 32-bit ints using the plain encoding.""" length = 4 * count data = file_obj.read(length) if len(data) != length: raise EOFError("Expected {} bytes but got {} bytes".format(length, len(data))) res = struct.unpack("<{}i".format(count).encode("utf-8"), data) return res
[ "def", "read_plain_int32", "(", "file_obj", ",", "count", ")", ":", "length", "=", "4", "*", "count", "data", "=", "file_obj", ".", "read", "(", "length", ")", "if", "len", "(", "data", ")", "!=", "length", ":", "raise", "EOFError", "(", "\"Expected {} bytes but got {} bytes\"", ".", "format", "(", "length", ",", "len", "(", "data", ")", ")", ")", "res", "=", "struct", ".", "unpack", "(", "\"<{}i\"", ".", "format", "(", "count", ")", ".", "encode", "(", "\"utf-8\"", ")", ",", "data", ")", "return", "res" ]
Read `count` 32-bit ints using the plain encoding.
[ "Read", "count", "32", "-", "bit", "ints", "using", "the", "plain", "encoding", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L36-L43
17,499
jcrobak/parquet-python
parquet/encoding.py
read_plain_int64
def read_plain_int64(file_obj, count): """Read `count` 64-bit ints using the plain encoding.""" return struct.unpack("<{}q".format(count).encode("utf-8"), file_obj.read(8 * count))
python
def read_plain_int64(file_obj, count): """Read `count` 64-bit ints using the plain encoding.""" return struct.unpack("<{}q".format(count).encode("utf-8"), file_obj.read(8 * count))
[ "def", "read_plain_int64", "(", "file_obj", ",", "count", ")", ":", "return", "struct", ".", "unpack", "(", "\"<{}q\"", ".", "format", "(", "count", ")", ".", "encode", "(", "\"utf-8\"", ")", ",", "file_obj", ".", "read", "(", "8", "*", "count", ")", ")" ]
Read `count` 64-bit ints using the plain encoding.
[ "Read", "count", "64", "-", "bit", "ints", "using", "the", "plain", "encoding", "." ]
e2caab7aceca91a3075998d0113e186f8ba2ca37
https://github.com/jcrobak/parquet-python/blob/e2caab7aceca91a3075998d0113e186f8ba2ca37/parquet/encoding.py#L46-L48